文档菜单
文档首页
/ / /
Kotlin 同步驱动程序
/

时间序列数据

本页内容

  • 概述
  • 创建时间序列集合
  • 存储时间序列数据
  • 查询时间序列数据
  • 附加信息

在本指南中,您可以了解如何使用 Kotlin 同步驱动程序来存储和交互 时间序列数据

时间序列数据由以下组件组成

  • 测量的量

  • 测量的时间戳

  • 描述测量的元数据

以下表格描述了您可以存储时间序列数据的示例情况

情况
测量的量
元数据
按行业记录月度销售额
美元收入
公司,国家
跟踪天气变化
降水量水平
位置,传感器类型
记录房价波动
月租金价格
位置,货币

重要

时间序列集合的服务器版本

要创建和交互时间序列集合,您必须连接到运行MongoDB服务器5.0或更高版本的部署。

您可以创建一个时间序列集合来存储时间序列数据。要创建时间序列集合,请将以下参数传递给createCollection() 方法

  • 要创建的新集合的名称

  • A创建集合选项 对象,使用 时间序列选项 方法设置 timeSeriesOptions()

此示例在 fall_weather 数据库中创建了 october2024 时间序列集合,并将 timeField 选项设置为 "timestamp" 字段

val database = mongoClient.getDatabase("fall_weather")
val tsOptions = TimeSeriesOptions("timestamp")
val collectionOptions = CreateCollectionOptions().timeSeriesOptions(tsOptions)
database.createCollection("october2024", collectionOptions)

为了验证您已成功创建了时间序列集合,请在数据库上运行 listCollections() 方法并打印结果

val results = database.listCollections()
val jsonSettings = JsonWriterSettings.builder().indent(true).build()
results.forEach { result ->
println(result.toJson(jsonSettings))
}
{
"name": "october2024",
"type": "timeseries",
"options": {
"timeseries": {
"timeField": "temperature",
"granularity": "seconds",
"bucketMaxSpanSeconds": 3600
}
},
"info": {
"readOnly": false
}
}
...

您可以通过使用 insertOne()insertMany() 方法并将测量值、时间戳和元数据指定在每个插入的文档中来将数据插入到时间序列集合中。

提示

要了解更多关于将文档插入集合的信息,请参阅插入文档 指南。

此示例将纽约市的温度数据插入到在创建时间序列集合示例中创建的october2024时间序列集合中。每个文档包含以下字段:

  • temperature,存储华氏度温度测量值

  • location,存储位置元数据

  • timestamp,存储测量收集的时间

val collection = database.getCollection<Document>("october2024")
// Temperature data for October 1, 2024
val temperature1 = Document("temperature", 54)
.append("location", "New York City")
.append("timestamp", Date(1727755200000))
// Temperature data for October 2, 2024
val temperature2 = Document("temperature", 55)
.append("location", "New York City")
.append("timestamp", Date(1727841600000))
collection.insertMany(listOf(temperature1, temperature2))

您可以使用与在其他集合上执行读取或聚合操作时相同的语法和约定来查询存储在时间序列集合中的数据。有关这些操作的更多信息,请参阅更多信息部分。

要了解本指南中提到的概念,请参阅以下MongoDB服务器手册条目:

要了解有关执行读取操作的更多信息,请参阅从MongoDB读取数据。

要了解有关执行聚合操作的更多信息,请参阅使用聚合转换您的数据指南。

要了解本指南中提到的方法的更多信息,请参阅以下API文档:

返回

BSON