- Introduction to MongoDB >
- Databases and Collections >
- Time Series Collections >
- Create and Query a Time Series Collection
Create and Query a Time Series Collection¶
On this page
This page shows how to create and query a time series collection with code examples.
Create a Time Series Collection¶
Before you can insert data into a time series collection, you must
explicitly create the collection using either the
db.createCollection()
method or the create
command:
Note
Feature Compatibility Version
You can only create time series collections on a system with featureCompatibilityVersion set to 5.0 or greater.
timeseries
Object Fields¶
When creating a time series collection, specify the following options:
Field | Type | Description |
---|---|---|
timeseries.timeField |
string | Required. The name of the field which contains the date in each
time series document. Documents in a time series collection must
have a valid BSON date as the value for the timeField . |
timeseries.metaField |
string | Optional. The name of the field which contains metadata in each time series document. The metadata in the specified field should be data that is used to label a unique series of documents. The metadata should rarely, if ever, change. The name of the specified field may not be |
timeseries.granularity |
string | Optional. Possible values are:
By default, MongoDB sets the Manually set the If you specify the If you do not specify |
expireAfterSeconds |
number | Optional. Enable the automatic deletion of documents in a time series collection by specifying the number of seconds after which documents expire. MongoDB deletes expired documents automatically. See Set up Automatic Removal for Time Series Collections (TTL) for more information. |
Other options allowed with the timeseries
option are:
storageEngine
indexOptionDefaults
collation
writeConcern
comment
See
Insert Measurements into a Time Series Collection¶
Each document you insert should contain a single measurement. To insert multiple documents at once, issue the following command:
To insert a single document, use the db.collection.insertOne()
method.
Tip
Optimize Insert Performance
To learn how to optimize inserts for large operations, see Optimize Inserts.
Query a Time Series Collection¶
To retrieve one document from a time series collection, issue the following command:
Run Aggregations on a Time Series Collection¶
For additional query functionality, use an aggregation pipeline such as:
The example aggregation pipeline groups all documents by the date of the measurement and then returns the average of all temperature measurements that day:
Check if a Collection is of Type Time Series¶
To determine if a collection is of type time series, use the listCollections command:
If the collection is a time series collection, it returns this: