0Pricing
MongoDB Academy · Lesson

Inserting and Querying Time Series Data

Learners will insert batches of measurements and query them with filters on time ranges and metadata fields.

Inserting Measurements Into Time Series

Inserting into a time series collection uses the exact same insertOne() and insertMany() methods as regular collections. MongoDB inspects the timeField (which must be a BSON Date) and the metaField to place the measurement into the correct internal bucket. The insert API is intentionally identical so existing application code requires minimal changes when adopting time series collections.

const now = new Date()

db.sensorReadings.insertOne({
  timestamp: now,
  sensorId: 'sensor-42',
  temperature: 23.1,
  humidity: 58.4,
  batteryLevel: 87
})

Bulk Inserting Historical Data

When loading historical measurements, always prefer insertMany() over repeated insertOne() calls. MongoDB can batch the data into buckets far more efficiently with bulk operations. For very large datasets (millions of rows), consider using mongoimport or the Node.js driver's bulkWrite() with insertOne operations grouped in batches of 1,000–5,000 documents.

const readings = []
const base = new Date('2024-06-01T00:00:00Z')

for (let i = 0; i < 1440; i++) {
  readings.push({
    timestamp: new Date(base.getTime() + i * 60000),
    sensorId: 'sensor-42',
    temperature: 20 + Math.random() * 5,
    humidity: 50 + Math.random() * 20
  })
}

db.sensorReadings.insertMany(readings)

All lessons in this course

  1. Creating a Time Series Collection
  2. Inserting and Querying Time Series Data
  3. Windowed Aggregations on Time Series
  4. Automatic Data Expiration With expireAfterSeconds
← Back to MongoDB Academy