时间序列集合
概述
在此指南中,您可以了解 MongoDB 中的时间序列集合以及如何在 MongoDB Kotlin 驱动程序中与之交互。
时间序列集合有效地存储一段时间内的测量值序列。时间序列数据包括任何随时间收集的数据、描述测量的元数据和测量的时间。
示例 | 测量值 | 元数据 |
---|---|---|
销售数据 | 收入 | 公司 |
感染率 | 感染人数 | 位置 |
创建时间序列集合
要创建时间序列集合,请将以下参数传递给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 版本将窗口函数引入到聚合管道中。您可以使用窗口函数对连续的时间序列数据范围执行操作。
有关更多信息,请参阅我们的 聚合构建器指南。