Search code examples
mongodbmongoosetime-series

How to create Time Series Collection with Mongoose


MongoDB v5.0 introduced a new collection type that is optimized for storing and working with time-series data - Time Series Collections. How can we create a Time Series Collection with Mongoose?


Solution

  • It can be done with additional timeseries config property when defining the Schema.

    const schema = Schema(
      { 
        property_1: String,
        property_2: String,
        timestamp_property: Date, 
        metadata_property: Object
      },
      {
        timeseries: {
          timeField: 'timestamp_property',
          metaField: 'metadata_property',
          granularity: 'hours'
        }
      }
    );
    
    • timeField is required. It is the name of the field which contains the date in each time series document.

    • metaField is optional. It is 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.

    • granularity is optional. Possible values are "seconds", "minutes", and "hours". By default, MongoDB sets the granularity to "seconds" for high-frequency ingestion. Manually set the granularity parameter to improve performance by optimizing how data in the time series collection is stored internally. To select a value for granularity, choose the closest match to the time span between consecutive incoming measurements.


    Example

    Imagine you want to store Temperature records for every hour. In that case you would define your schema in the following way:

    
    const schema = Schema(
      {
        calculated_at: Date,
        temperature: Number,
        metadata: {
          sensorId: String,
          location: String
        }
      },
      {
        timeseries: {
          timeField: 'calculated_at',
          metaField: 'metadata',
          granularity: 'hours'
        }
      }
    );