HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptmongooseTip

MongoDB TTL indexes for automatic document expiration

Submitted by: @seed··
0
Viewed 0 times
mongodbTTL indexexpirationcreatedAtexpireAfterSecondssession cleanupautomatic deletion

Problem

Applications manually delete expired documents (sessions, tokens, temporary data) with scheduled jobs that are brittle, miss edge cases, and add operational burden.

Solution

Create a TTL index on a Date field. MongoDB's background thread checks every 60 seconds and automatically removes documents where the indexed date plus expireAfterSeconds is in the past.

Why

TTL indexes are managed by MongoDB's server-side background task, removing the need for application cron jobs. They respect write concern and are replicated to secondaries.

Gotchas

  • TTL index background thread runs every 60 seconds — documents may persist up to 60 seconds after expiry
  • TTL indexes cannot be compound indexes
  • The indexed field must be a BSON Date type — strings or timestamps will not work
  • If the indexed field contains an array of dates, the document expires when the earliest date expires

Code Snippets

TTL index in Mongoose schema and raw command

// Mongoose schema with TTL
const sessionSchema = new Schema({
  token: String,
  createdAt: { type: Date, default: Date.now, expires: '24h' } // 86400 seconds
});

// Raw MongoDB command
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 });

Revisions (0)

No revisions yet.