对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

时间序列集合

在本指南中,您可以了解 MongoDB 中的时间序列集合,以及如何在 MongoDB Java 驱动程序中与之交互。

时间序列集合可有效存储一段时间内的测量序列。 时间序列数据包括随时间推移收集的任何数据、描述测量的元数据以及测量时间。

例子
测量
Metadata

销售数据

收入

公司

感染率

感染人数

地点

要创建时间序列集合,请将以下参数传递给 createCollection() 方法:

MongoDatabase database = mongoClient.getDatabase("fall_weather");TimeSeriesOptions tsOptions = new TimeSeriesOptions("temperature");CreateCollectionOptions collOptions = new CreateCollectionOptions().timeSeriesOptions(tsOptions); // Creates a time series collection that stores "temperature" values over timedatabase.createCollection("september2021", collOptions);

重要

MongoDB 5.0之前的版本无法创建时间序列集合。

要检查是否成功创建集合,请将 "listCollections" 命令发送到 runCommand() 方法。

Document commandResult = database.runCommand(new Document("listCollections", new BsonInt64(1))); List<String> keys = Arrays.asList("cursor"); // Prints information about the database's collections and viewsSystem.out.println("listCollections: " + commandResult.getEmbedded(keys, Document.class).toJson());

输出应如下所示:

{ "id": <some number>, "ns": "<db name>.$cmd.listCollections", "firstBatch": [ { "name": "<time series collection name>", "type": "timeseries", "options": { "expireAfterSeconds": <some number>, "timeseries": { ... } }, ... }, ... ]}

要在时间序列集合中查询,请使用与检索和聚合数据相同的约定。

注意

窗口功能

MongoDB 5.0版本将窗口函数引入聚合管道。 您可以使用窗口函数对连续的时间序列数据范围执行操作。 有关更多信息,请参阅我们的聚合构建指南。