Docs 菜单
Docs 主页
/ / /
Java Reactive Streams 驱动程序
/

时间序列数据

在此页面上

  • Overview
  • 创建时间序列集合
  • 存储时间序列数据
  • 查询时间序列数据
  • 更多信息

在本指南中,您可以了解如何使用 Java Reactive Streams 驱动程序存储时间序列数据并与之交互。

时间序列数据由以下部分组成:

  • 测量数量

  • 测量的时间戳

  • 描述测量的元数据

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

情况
测量数量
Metadata
按行业记录月度销售额
收入(美元)
公司、国家/地区
追踪天气变化
降水量
位置、传感器类型
记录房价波动
月租价格
位置、货币

重要

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

要创建时间序列集合并与之交互,必须连接到运行 MongoDB Server 5.0或更高版本的部署。

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

  • 要创建的新集合的名称

  • CreateCollectionOptions 对象与 TimeSeriesOptions 使用timeSeriesOptions() 方法设置

以下示例在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);

要验证是否已成功创建time-series collection,请对数据库运行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 Server 手册条目:

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

要了解有关执行聚合操作的更多信息,请参阅聚合框架指南。

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

后退

专用数据格式