Docs Menu

Time Series Collections

In this guide, you can learn about time series collections in MongoDB, and how to interact with them in the MongoDB Kotlin 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

To create a time series collection, pass the following parameters to the createCollection() method:

val database = mongoClient.getDatabase("fall_weather")
val tsOptions = TimeSeriesOptions("temperature")
val collOptions = 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.

val commandResult = database.listCollections().toList()
.find { it["name"] == "september2021" }
println(commandResult?.toJson(JsonWriterSettings.builder().indent(true).build()))
{
"name": "september2021",
"type": "timeseries",
"options": {
"timeseries": {
"timeField": "temperature",
"granularity": "seconds",
"bucketMaxSpanSeconds": 3600
}
},
"info": {
"readOnly": false
}
}

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.