What are TTL indexes in MongoDB?

Why Interviewers Ask This

This is a classic screening question for MongoDB roles. Hiring managers ask it early in interviews to gauge your baseline understanding and determine if you can communicate technical concepts clearly.

Answer

TTL (Time-To-Live) indexes are special single-field indexes on Date fields that automatically delete documents after a specified time period — MongoDB runs a background process every 60 seconds that removes expired documents. Creating a TTL index: db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 }) — documents are deleted 1 hour after their createdAt value. db.logs.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }) — documents are deleted at the exact time stored in expiresAt (when expireAfterSeconds is 0, MongoDB deletes documents when the indexed Date field's value is in the past). Behavior: (1) The indexed field must be a BSON Date type or array of Date types; (2) MongoDB checks for and deletes expired documents every 60 seconds — documents may live up to 60 seconds beyond their expiry; (3) TTL indexes on replica sets: only the primary deletes documents (secondaries delete by replicating the deletes from primary); (4) On sharded collections: each shard's primary handles TTL deletions independently. Use cases: session expiration, log rotation, cache entries, temporary tokens (password reset, email verification), sensor data retention, shopping cart cleanup. Modifying TTL: db.runCommand({ collMod: "sessions", index: { keyPattern: { createdAt: 1 }, expireAfterSeconds: 7200 } }). Limitation: only one TTL index per collection. No TTL on compound indexes.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex MongoDB answers easy to follow.