How do TTL indexes work in MongoDB?
Understand MongoDB TTL indexes: expireAfterSeconds, the background sweep, absolute expiry with 0, and use cases like sessions, logs, and tokens.
Expected Interview Answer
A TTL (Time To Live) index is a special single-field index on a date-typed field that lets MongoDB automatically delete documents once a configured number of seconds has elapsed past that field's value. A background thread periodically scans the index and removes expired documents.
You create it by adding expireAfterSeconds to a single-field index on a BSON Date (or an array of dates, where the earliest date governs). A background TTL monitor runs roughly every 60 seconds and deletes documents whose date field plus expireAfterSeconds is in the past. Because the sweep is periodic and subject to load, expiration is not precise to the second — documents may linger briefly past their deadline. Setting expireAfterSeconds to 0 expires documents exactly at the stored date, which is how you implement absolute-time expiry.
- Automatic cleanup of stale data with no application cron job
- Ideal for sessions, logs, caches, and OTP/token expiry
- Reduces storage and keeps collections lean
- expireAfterSeconds: 0 enables exact expire-at timestamps
- Works with the normal query planner as a regular index
AI Mentor Explanation
Think of a groundskeeper who walks the boundary every over and removes any drinks bottles left out longer than the allowed break. Players don't clear their own bottles at an exact second; the keeper sweeps on his rounds. A TTL index is that keeper: it doesn't delete a document the instant it expires, but on its periodic patrol it clears everything whose time is up.
Step-by-Step Explanation
Step 1
Add a date field
Ensure documents store a BSON Date field such as createdAt or expiresAt that marks the reference time.
Step 2
Create the index
Call createIndex on that single field with the expireAfterSeconds option set to the desired lifetime in seconds.
Step 3
Understand the sweep
A background TTL monitor runs about every 60 seconds and deletes documents whose date + expireAfterSeconds is in the past.
Step 4
Use 0 for absolute expiry
Set expireAfterSeconds: 0 and store the exact expiry moment in the field so documents expire at that timestamp.
Step 5
Mind the constraints
The indexed field must be a Date (or array of dates); non-date values are ignored and never expire.
Step 6
Account for imprecision
Expiry is not real-time — under load documents may persist a little past their deadline, so don't rely on it for security-critical instant deletion.
What Interviewer Expects
- Knowing TTL indexes require a Date-typed field
- Understanding the ~60s background sweep and its imprecision
- Explaining expireAfterSeconds and the special 0 value
- Common use cases: sessions, logs, caches, tokens
- Awareness that non-date values are never expired
Common Mistakes
- Expecting deletion at the exact expiry second
- Creating a TTL index on a non-date or compound field
- Assuming expireAfterSeconds: 0 means never expire (it means expire at the stored date)
- Relying on TTL for security-critical instant purging
- Forgetting only the earliest date governs when the field is an array
Best Answer (HR Friendly)
“A TTL index tells MongoDB to automatically delete documents a set amount of time after a date stored on them — great for things like sessions or logs that should clean themselves up. A background process sweeps every minute or so, so removal is automatic but not precise to the second.”
Code Example
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
);
// A document with createdAt = now is removed ~1 hour later by the TTL monitordb.tokens.createIndex(
{ expiresAt: 1 },
{ expireAfterSeconds: 0 }
);
db.tokens.insertOne({
token: 'abc',
expiresAt: new Date('2026-08-01T00:00:00Z') // expires exactly at this instant
});db.runCommand({
collMod: 'sessions',
index: { keyPattern: { createdAt: 1 }, expireAfterSeconds: 7200 }
});Follow-up Questions
- Why might a document survive briefly past its TTL deadline?
- What does expireAfterSeconds: 0 accomplish?
- Can a TTL index be a compound index? Why or why not?
- How do you change the expiry duration without dropping the index?
- What happens if the indexed field is missing or not a date?
MCQ Practice
1. What field type must a TTL index be built on?
TTL indexes only act on BSON Date fields (or arrays of dates); other types are ignored and never expire.
2. What does expireAfterSeconds: 0 do?
With 0, the document expires at the exact time stored in the indexed date field — enabling absolute expire-at timestamps.
3. How often does the TTL background monitor typically run?
The TTL monitor runs roughly every 60 seconds, so expiration is periodic rather than instant.
Flash Cards
What is a TTL index? — An index on a Date field with expireAfterSeconds that auto-deletes documents after they expire.
How precise is TTL deletion? — Not precise — a background sweep runs ~every 60s, so documents may linger briefly past expiry.
What does expireAfterSeconds: 0 mean? — Expire the document exactly at the timestamp stored in the indexed field (absolute expiry).
Can TTL indexes be compound? — No — TTL applies only to single-field indexes on a date.
Typical use cases? — Sessions, logs, caches, OTP/tokens, and any self-expiring data.