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:
package main import ( "context" "encoding/json" "fmt" "log" "os" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/mongo" "go.mongodb.org/mongo-driver/mongo/options" ) func main() { var uri string if uri = os.Getenv("MONGODB_URI"); uri == "" { log.Fatal("You must set your 'MONGODB_URI' environment variable. See\n\t https://www.mongodb.com/ja-jp/docs/drivers/go/current/usage-examples/") } client, err := mongo.Connect(options.Client().ApplyURI(uri)) if err != nil { panic(err) } defer client.Disconnect(context.TODO()) db := client.Database("myDB") // 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) }
{ ... "cursor": { "firstBatch": [ { "info": { "readOnly": false }, "name": "march2022", "options": { "timeseries": { ... } }, "type": "timeseries" }, ... }
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: