时间序列数据
概述
在本指南中,您可以学习如何使用 Java Reactive Streams 驱动程序存储和交互 时间序列数据。
时间序列数据由以下组件组成
测量的量
测量的时间戳
描述测量的元数据
以下表格描述了您可以存储时间序列数据的示例情况
情况 | 测量的量 | 元数据 |
---|---|---|
按行业记录月度销售额 | 美元收入 | 公司,国家 |
跟踪天气变化 | 降水级别 | 位置,传感器类型 |
记录房价波动 | 月租金价格 | 位置,货币 |
创建时间序列集合
重要
时间序列集合的服务器版本
要创建和交互时间序列集合,您必须连接到运行MongoDB服务器5.0或更高版本的部署。
您可以使用时间序列集合来存储时间序列数据。要创建时间序列集合,请将以下参数传递给createCollection()
方法
以下示例在 fall_weather
数据库中创建了一个名为 october2024
的时间序列集合,并将 timeField
选项设置为 "timestamp"
字段
MongoDatabase database = mongoClient.getDatabase("fall_weather"); TimeSeriesOptions tsOptions = new TimeSeriesOptions("timestamp"); CreateCollectionOptions collectionOptions = new CreateCollectionOptions().timeSeriesOptions(tsOptions); database.createCollection("october2024", collectionOptions);
为了验证您是否成功创建了时间序列集合,请在数据库上运行 listCollections()
方法并打印结果
ListCollectionsPublisher<Document> listCollectionsPublisher = database.listCollections(); Flux.from(listCollectionsPublisher) .doOnNext(System.out::println) .blockLast();
Document{{name=october2024, type=timeseries, options=Document{{timeseries=Document{{timeField=timestamp, granularity=seconds, bucketMaxSpanSeconds=3600}}}}, info=Document{{readOnly=false}}}} ...
存储时间序列数据
您可以通过使用 insertOne()
或 insertMany()
方法并将测量值、时间戳和元数据指定在每个插入的文档中来将数据插入到时间序列集合中。
提示
有关将文档插入集合的更多信息,请参阅插入文档 指南。
示例
以下示例将纽约市温度数据插入到在创建时间序列集合示例中创建的 october2024
时间序列集合。每个文档包含以下字段
temperature
,存储华氏温度测量值location
,存储位置元数据timestamp
,存储测量收集的时间
MongoCollection<Document> collection = database.getCollection("october2024"); // Temperature data for October 1, 2024 Document temperature1 = new Document("temperature", 54) .append("location", "New York City") .append("timestamp", new Date(1727755200000L)); // Temperature data for October 2, 2024 Document temperature2 = new Document("temperature", 55) .append("location", "New York City") .append("timestamp", new Date(1727841600000L)); Publisher<InsertManyResult> insertPublisher = collection.insertMany(Arrays.asList(temperature1, temperature2)); Mono.from(insertPublisher).block();
查询时间序列数据
您可以使用与在其他集合上执行读取或聚合操作时相同的语法和约定来查询存储在时间序列集合中的数据。有关这些操作的更多信息,请参阅更多信息部分。
更多信息
有关本指南中提到的概念的更多信息,请参阅以下MongoDB服务器手册条目
有关执行读取操作的更多信息,请参阅从MongoDB读取数据。
有关执行聚合操作的更多信息,请参阅聚合框架指南。
API 文档
要了解更多关于本指南中提到的方法的详细信息,请参阅以下API文档