时间序列集合
概述
在本指南中,您可以了解MongoDB中的时间序列集合,以及如何使用MongoDB Java驱动程序与之交互。
时间序列集合有效地存储一段时间内的测量序列。时间序列数据包括任何随时间收集的数据、描述测量的元数据和测量的时间。
示例 | 测量 | 元数据 |
---|---|---|
销售数据 | 收入 | 公司 |
感染率 | 感染者人数 | 位置 |
创建时间序列集合
要创建时间序列集合,请将以下参数传递给createCollection() 方法
要创建的新集合名称
用于在 TimeSeriesOptions 对象中创建集合的 CreateCollectionOptions
MongoDatabase database = mongoClient.getDatabase("fall_weather"); TimeSeriesOptions tsOptions = new TimeSeriesOptions("temperature"); CreateCollectionOptions collOptions = new CreateCollectionOptions().timeSeriesOptions(tsOptions); // Creates a time series collection that stores "temperature" values over time database.createCollection("september2021", collOptions);
重要
MongoDB 5.0 之前的版本无法创建时间序列集合。
要检查是否成功创建了集合,发送"listCollections"
命令通过 runCommand() 方法。
Document commandResult = database.runCommand(new Document("listCollections", new BsonInt64(1))); List<String> keys = Arrays.asList("cursor"); // Prints information about the database's collections and views System.out.println("listCollections: " + commandResult.getEmbedded(keys, Document.class).toJson());
你的输出应类似于以下内容
{ "id": <some number>, "ns": "<db name>.$cmd.listCollections", "firstBatch": [ { "name": "<time series collection name>", "type": "timeseries", "options": { "expireAfterSeconds": <some number>, "timeseries": { ... } }, ... }, ... ] }