What is a TTL index?
IntermediateConceptMongoDB
Answer
Short answer
A TTL (time-to-live) index makes MongoDB automatically delete documents a set time after a date field's value. It's perfect for sessions, temporary tokens, logs or caches that should expire without a cleanup job.
Example
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 86400 }) // delete 24h after createdAt
db.sessions.insertOne({ userId: 42, token: "abc", createdAt: new Date() })
// expire at an exact time: store the expiry date and use 0
db.resetTokens.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
How it works
- A background task runs about every 60 seconds and removes expired documents — so deletion isn't instant.
- The field must be a BSON Date (or array of dates). Strings won't expire.
Change the TTL later
db.runCommand({ collMod: "sessions", index: { keyPattern: { createdAt: 1 }, expireAfterSeconds: 3600 } })
What to say in the interview
"A TTL index on a date field deletes documents automatically after expireAfterSeconds, checked roughly every minute. We use it for sessions and tokens instead of cron cleanup jobs; the field must be a real Date."