时间序列集合
Overview
在本指南中,您可以了解 MongoDB 中的time-series collection,以及如何在 MongoDB Kotlin 驱动程序中与之交互。
时间序列集合可有效存储一段时间内的测量序列。 时间序列数据包括随时间推移收集的任何数据、描述测量的元数据以及测量时间。
例子 | 测量 | Metadata |
---|---|---|
销售数据 | 收入 | 公司 |
感染率 | 感染人数 | 地点 |
创建时间序列集合
要创建时间序列集合,请将以下参数传递给 createCollection() 方法:
要创建的新集合的名称
TimeSeriesOptions 用于在 CreateCollectionOptions 中创建集合 对象
val database = mongoClient.getDatabase("fall_weather") val tsOptions = TimeSeriesOptions("temperature") val collOptions = CreateCollectionOptions().timeSeriesOptions(tsOptions) database.createCollection("september2021", collOptions)
重要
MongoDB 5.0之前的版本无法创建时间序列集合。
要检查是否已成功创建集合,请将"listCollections"
命令发送到 runCommand() 方法。
val commandResult = database.listCollections().toList() .find { it["name"] == "september2021" } println(commandResult?.toJson(JsonWriterSettings.builder().indent(true).build()))
{ "name": "september2021", "type": "timeseries", "options": { "timeseries": { "timeField": "temperature", "granularity": "seconds", "bucketMaxSpanSeconds": 3600 } }, "info": { "readOnly": false } }
查询时间序列集合
要在时间序列集合中进行查询,请使用与检索和聚合数据相同的约定。
注意
窗口功能
MongoDB 5.0 版本将窗口函数引入聚合管道。 您可以使用窗口函数对连续的time-series数据范围执行操作。
有关更多信息,请参阅我们的聚合构建器指南。