12. TTL Indexes for Expiring Data

A TTL index allows MongoDB to automatically remove documents after a configured time period or at a specified expiration time. It is useful for sessions, temporary tokens, short-lived cache records, and event data with a retention policy.

TTL deletion is asynchronous. Do not treat the configured expiration time as a precise deletion deadline. The background process checks eligible documents periodically, and actual deletion can occur later depending on workload.

A TTL index is a single-field index on a date field or a field containing date values in a supported array form. For relative expiration, use expireAfterSeconds; for per-document expiration, a zero-second configuration can use each document's date as the expiration time.

TTL indexes physically delete documents. Do not use them as the only mechanism for legally required retention or as a precise scheduling mechanism without considering their behavior.

TTL deletion is not immediate

TTL cleanup runs asynchronously. Applications should enforce authorization and expiration rules themselves rather than relying on the document having already been deleted.

Code Example
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 86400 }
);
Key Takeaways
  • TTL indexes support automatic document expiration.
  • TTL deletion is asynchronous, not an exact timer.
  • Use a date field and choose retention semantics carefully.
  • Enforce security and expiration rules in application logic too.
Knowledge Check

Can an application rely on a TTL document being deleted at the exact expiration second?