When should a TTL (Time-To-Live) index be used in a MongoDB collection?
TTL indexes are perfect for data with a limited lifespan, such as user session data, audit logs, or temporary caches. The database automatically removes these documents once they reach their expiration time, reducing the need for manual cleanup and keeping the collection size manageable for the active data set.
Why this answer
TTL indexes are designed to automatically remove documents from a collection after a certain period of time or at a specific time. This is ideal for ephemeral data like session logs, cached items, or temporary alerts. By relying on the database engine to handle the deletion, developers avoid writing custom cleanup scripts, ensuring that data is purged consistently without impacting application logic or manual overhead on the system.
Exam trap
Candidates often select TTL indexes for precise, exact-time transactional data scheduling or permanent data archiving, confusing background automatic cleanup with deterministic job execution.