Time Series Collections
Overview
In this guide, you can learn about time series collections in MongoDB, and how to interact with them in the MongoDB Java driver.
Time series collections efficiently store sequences of measurements over a period of time. Time series data consists of any data collected over time, metadata that describes the measurement, and the time of the measurement.
Example | Measurement | Metadata |
---|---|---|
Sales Data | Revenue | Company |
Infection Rates | Amount of People Infected | Location |
Create a Time Series Collection
To create a time series collection, pass the following parameters to the createCollection() method:
The name of the new collection to create
The TimeSeriesOptions for creating the collection in a CreateCollectionOptions object
MongoDatabase database = mongoClient.getDatabase("fall_weather"); TimeSeriesOptions tsOptions = new TimeSeriesOptions("temperature"); CreateCollectionOptions collOptions = new CreateCollectionOptions().timeSeriesOptions(tsOptions); database.createCollection("september2021", collOptions);
Important
Versions prior to MongoDB 5.0 cannot create a time series collection.
To check if you successfully created the collection, send the
"listCollections"
command to the runCommand() method.
Document commandResult = database.runCommand(new Document("listCollections", new BsonInt64(1))); List<String> keys = Arrays.asList("cursor"); System.out.println("listCollections: " + commandResult.getEmbedded(keys, Document.class).toJson());
Your output should look similar to the following:
{ "id": <some number>, "ns": "<db name>.$cmd.listCollections", "firstBatch": [ { "name": "<time series collection name>", "type": "timeseries", "options": { "expireAfterSeconds": <some number>, "timeseries": { ... } }, ... }, ... ] }
Query a Time Series Collection
To query in a time series collection, use the same conventions as you would for retrieving and aggregating data.
Note
Window Functions
MongoDB version 5.0 introduces window functions into the aggregation pipeline. You can use window functions to perform operations on a contiguous span of time series data. For more information, see our Aggregates Builders guide.