Time-to-Live (TTL) Indexes
Time-to-Live (TTL) Indexes
TTL (Time-to-Live) Indexes are single-field indexes that automatically remove documents from a collection after a defined period. They eliminate the need for manual cron jobs or deletion scripts.
TTL Mechanics & Specifications
| Parameter / Behavior | Specification | Important Requirement / Note |
|---|---|---|
| Target Field | Must contain a BSON Date value |
Documents with non-Date fields or missing fields are not expired |
| Index Option | expireAfterSeconds: <seconds> |
Defines elapsed seconds after the indexed Date before deletion occurs |
| Background Thread | Runs once every 60 seconds | Deletions are not sub-second precise; up to 60 seconds delay is normal |
| Replication | Deletions happen on Primary and are written to the Oplog | Ensures secondaries replicate deletions consistently |
Common Implementation Patterns
- Fixed Expiration (e.g. 24 hours):
CODE
db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 86400 }); - Dynamic Expiration Per Document (at exact timestamp):
CODE
// Set expireAfterSeconds: 0 and populate expireAt with future Date db.tokens.createIndex({ "expireAt": 1 }, { expireAfterSeconds: 0 });