Time Series Collections
On this page
Overview
In this guide, you can learn about time series collections in MongoDB, and how to interact with them in the MongoDB Go Driver.
Time series collections efficiently store sequences of measurements over a period of time. The collection consists of time series data with the following information:
Data collected over time
Metadata that describes the measurement
Date of the measurement
Example | Measurement | Metadata |
---|---|---|
Sales Data | Revenue | Company |
Infection Rates | Amount of People Infected | Location |
Create a Time Series Collection
Important
Time series collections require MongoDB 5.0 or later.
To create a time series collection, pass the following parameters to the
CreateCollection()
method:
The name of the new collection to create
The
TimeSeriesOptions
object specifying at least the time field
Example
The following example creates the march2022
time series collection in the
db
database with the temperature
as the time field:
db := client.Database("db") // Creates a time series collection that stores "temperature" values over time tso := options.TimeSeries().SetTimeField("temperature") opts := options.CreateCollection().SetTimeSeriesOptions(tso) db.CreateCollection(context.TODO(), "march2022", opts)
To check if you created the collection, send the "listCollections"
command to the RunCommand()
method:
// Creates a command to list collections command := bson.D{{"listCollections", 1}} var result bson.M // Runs the command on the database commandErr := db.RunCommand(context.TODO(), command).Decode(&result) if commandErr != nil { panic(commandErr) } // Prints the command results output, outputErr := json.MarshalIndent(result, "", " ") if outputErr != nil { panic(outputErr) } fmt.Printf("%s\n", output)
Query a Time Series Collection
To query a time series collection, use the same conventions as you would for retrieving and aggregating data.
Additional Information
To learn more about the operations mentioned, see the following guides:
API Documentation
To learn more about any of the methods or types discussed in this guide, see the following API Documentation: