时间序列数据
Overview
在本指南中,您可以学习;了解如何使用Scala驾驶员存储时间序列数据并与之交互。
时间序列数据由以下部分组成:
测量数量
测量的时间戳
描述测量的元数据
下表描述了可以存储时间序列数据的示例情况:
情况 | 测量数量 | Metadata |
---|---|---|
按行业记录月度销售额 | 收入(美元) | 公司、国家/地区 |
追踪天气变化 | 降水量 | 位置、传感器类型 |
记录房价波动 | 月租价格 | 位置、货币 |
创建时间序列集合
重要
时间序列集合的服务器版本
要创建时间序列集合并与之交互,必须连接到运行 MongoDB Server 5.0或更高版本的部署。
您可以创建时间序列集合来存储时间序列数据。 要创建时间序列集合,请将以下参数传递给 createCollection()
方法:
要创建的新集合的名称
CreateCollectionOptions 对象,并使用 方法设立了TimeSeriesOptions
timeSeriesOptions()
例子
此示例在 fall_weather
数据库中创建 october2024
时间序列集合,并将 timeField
选项设立为 "timestamp"
字段,并将 metaField
选项设立为 "location"
字段:
val database = mongoClient.getDatabase("fall_weather") val tsOptions = TimeSeriesOptions("timestamp").metaField("location") val collectionOptions = CreateCollectionOptions().timeSeriesOptions(tsOptions) val createObservable = database.createCollection("october2024", collectionOptions) Await.result(createObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
要验证是否已成功创建time-series collection,请对数据库运行listCollections()
方法并打印结果:
val listObservable = database.listCollections() val list = Await.result(listObservable.toFuture(), Duration(10, TimeUnit.SECONDS)) val jsonSettings = JsonWriterSettings.builder().indent(true).build() list.foreach(collection => { println(collection.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("october2024") val temperatures = Seq( Document("timestamp" -> BsonDateTime(1727755200000L), "temperature" -> 54, "location" -> "New York City"), Document("timestamp" -> BsonDateTime(1727841600000L), "temperature" -> 55, "location" -> "New York City"), ) val insertObservable = collection.insertMany(temperatures) Await.result(insertObservable.toFuture(), Duration(10, TimeUnit.SECONDS))
查询时间序列数据
您可以使用与对其他集合执行读取或聚合操作时相同的语法和约定来查询时间序列集合中存储的数据。 要学习;了解有关这些操作的更多信息,请参阅“其他信息”部分。
更多信息
要学习;了解有关本指南中提到的概念的更多信息,请参阅以下MongoDB Server手册条目:
要学习;了解有关执行读取操作的更多信息,请参阅从MongoDB读取数据。
要学习;了解有关执行聚合操作的更多信息,请参阅《使用聚合转换数据》指南。
API 文档
要学习;了解有关本指南中提到的方法的更多信息,请参阅以下API文档: