Overview
このガイドでは、MongoDB の時系列コレクションと、MongoDB Java ドライバーでそれらを操作する方法を学習できます。
時系列コレクションは一定期間にわたる測定値のシーケンスを効率的に保存します。 時系列データは、一定時間にわたって収集されたデータ、測定を説明するメタデータ、測定時間で構成されています。
| 例 | 測定値 | Metadata | 
|---|---|---|
| 販売データ | 収益 | 会社 | 
| 影響率 | 影響を受けた人口の量 | ロケーション | 
時系列コレクションの作成
時系列コレクションを作成するには、次のパラメータを createCollection() メソッドに渡します。
- 作成する新しいコレクションの名前 
- CreateCollectionOptionsオブジェクトにコレクションを作成するための TimeseriesOptions 
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": { ... }      },      ...    },    ...  ] } 
時系列コレクションをクエリする
時系列コレクションでクエリするには、 がデータを取得して集計するのと同じ規則を使用します。
注意
ウィンドウ関数
MongoDB バージョン5.0では、集計パイプラインにウィンドウ関数が導入されています。 ウィンドウ関数を使用して、時系列データの連続した範囲に対して操作を実行できます。 詳細については、集計ビルダ のガイドをご覧ください。