0
0
MongodbConceptBeginner · 3 min read

TTL Index in MongoDB: What It Is and How It Works

A TTL index in MongoDB is a special type of index that automatically removes documents from a collection after a specified time period. It helps manage data lifecycle by deleting expired data without manual intervention.
⚙️

How It Works

Think of a TTL index like a timer attached to each document in a MongoDB collection. When you create a TTL index on a date field, MongoDB watches that field and automatically deletes documents once the time passes a set limit. This is similar to how a library might remove books that are overdue for return after a certain number of days.

Under the hood, MongoDB runs a background task approximately every 60 seconds that checks documents against the TTL index. If a document's date value is older than the specified expiration time, MongoDB deletes it. This process helps keep collections clean and prevents old data from piling up.

💻

Example

This example creates a TTL index on the createdAt field that expires documents 3600 seconds (1 hour) after their creation.

mongodb
db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })
Output
{ "createdAt_1": 1 }
🎯

When to Use

Use TTL indexes when you want MongoDB to automatically delete data after a certain time. This is useful for session data, temporary caches, logs, or any data that should not persist forever. For example, a website might store user login sessions that expire after an hour, or an app might keep event logs only for a week.

TTL indexes reduce the need for manual cleanup scripts and help maintain efficient storage by removing stale data automatically.

Key Points

  • TTL indexes automatically delete documents after a set time.
  • They work by monitoring a date field in each document.
  • MongoDB runs a background task approximately every minute to remove expired documents.
  • TTL indexes are ideal for temporary or time-sensitive data.
  • They simplify data management by automating cleanup.

Key Takeaways

A TTL index automatically removes documents after a specified time to manage data lifecycle.
It works by monitoring a date field and deleting documents once they expire.
Ideal for session data, logs, caches, and temporary information.
MongoDB runs a background task approximately every 60 seconds to enforce TTL expiration.
Using TTL indexes reduces manual cleanup and keeps data storage efficient.