MongoDB & NoSQL (50 Qs)•Part 2: Core Architecture & Implementation (Mid-Level)
What is a TTL (Time-To-Live) Index in MongoDB?
senior LevelMost AskedCode ExampleSystem DesignDatabases & SQL
In Simple Words: A single-field index on a Date field that automatically deletes expired documents:
javascript
// Automatically delete user sessions 30 minutes (1800s) after createdAt:
db.sessions.createIndex(
{ "createdAt": 1 },
{ expireAfterSeconds: 1800 }
);
- A background thread scans the TTL index once every 60 seconds and removes expired records.