0Pricing
MongoDB Academy · Lesson

Automatic Data Expiration With expireAfterSeconds

Learners will configure the expireAfterSeconds option on a time series collection to automatically purge old measurements and control storage costs.

Why Automatic Data Expiration Matters

Time series data is almost always finite in value — sensor readings from 5 years ago rarely inform today's decisions. Retaining stale data wastes storage, slows backups, and increases index sizes. MongoDB's expireAfterSeconds option lets you declare a retention period at collection creation time so the database handles cleanup automatically, without cron jobs or application-level delete routines.

Setting expireAfterSeconds at Creation

Pass expireAfterSeconds as a top-level option alongside the timeseries object when calling db.createCollection(). The value is an integer representing the number of seconds to retain data. Documents whose timeField value is older than now − expireAfterSeconds become eligible for deletion by the TTL background thread.

// Create a collection that retains data for 30 days
db.createCollection('sensorReadings', {
  timeseries: {
    timeField: 'timestamp',
    metaField: 'sensorId',
    granularity: 'seconds'
  },
  expireAfterSeconds: 60 * 60 * 24 * 30  // 2592000 seconds = 30 days
})

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