Tired of bloated log collections and messy data? TTL indexes in MongoDB automate your cleanup no cron jobs, no scripts. Learn how to set up, monitor, and optimize TTL for cleaner, faster, and self-maintaining databases.
Rexcily September 09, 2025
In a world drowning in logs, every millisecond counts.
Have you ever:
Good news. It can.
With TTL (Time-To-Live) Indexes, MongoDB does the cleanup for you quietly, efficiently, and automatically.In this blog, we’ll explore how TTL indexes work, how to set them up, and how they silently clean up stale data while you focus on what matters most.
A TTL index in MongoDB is a type of index that automatically removes documents from a collection after a certain period. Perfect for:
Why use it?
MongoDB runs a background job every 60 seconds, known as the TTL monitor. It checks documents in collections with TTL indexes and deletes those whose timestamp exceeds the specified age.
To better understand this, here’s a visual flowchart of how MongoDB handles TTL expiration:
If it’s still within the threshold, it’s retained.
This cycle repeats automatically—no developer effort needed.
db.logs.insertOne({
message: "User login",
level: "INFO",
createdAt: new Date()
});db.logs.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 864000 } // 10 days
);db.logs.getIndexes();That’s it -MongoDB takes care of the rest.
Advanced Feature: Partial TTL Indexes (MongoDB 4.2)
Introduced in MongoDB 4.2, partial TTL indexes allow you to automatically expire only a subset of documents based on a filter expression. This is particularly useful when:
Example: Create a Partial TTL Index
db.eventlog.createIndex(
{ "timestamp": 1 },
{
partialFilterExpression: { "sensor": { $eq: "40.761873, -73.984287" } },
expireAfterSeconds: 3600
}
);Only documents where sensor = "40.761873, -73.984287" will be considered for TTL expiration. Others remain untouched.
Monitoring TTL Activity: Stay Informed
After enabling TTL indexes, it’s important to verify that they're working correctly.
Check TTL Metrics
db.serverStatus().metrics.ttlSample Output
{
"deletedDocuments": 100000,
"passes": 60
}deletedDocuments → Total documents auto-deleted by TTL
passes → Total scans performed by the TTL monitor thread
The chart below visually represents the number of documents deleted by the TTL process.
Why Monitor TTL Metrics?
Adjusting TTL Monitor Frequency
MongoDB’s TTL monitor runs by default every 60 seconds, scanning for expired documents. You can tune this interval to reduce background load or delay deletions.
To increase the interval (e.g., once per hour):
db.adminCommand({ setParameter: 1, ttlMonitorSleepSecs: 3600 });Important: Clean Historical Data Before Enabling TTL
If your collection already contains a large number of past (expired) records, enabling a TTL index may trigger bulk deletions, causing performance spikes.
It’s best to manually clean old records first, especially for collections with:
Real-World Impact
We applied TTL indexes in a microservice environment logging over 3 million events/month.
Results:
When Not to Use TTL?
TTL is not suitable if:
In such cases, use background jobs or ETL pipelines instead.
Conclusion
TTL Indexes in MongoDB are a developer’s dream for automating the cleanup of obsolete data. They’re simple, efficient, and powerful—especially for time-bound datasets like logs and cache.
So stop writing cleanup scripts. Let MongoDB clean up after itself.
Miru IT Park, Vallankumaranvillai,
Nagercoil, Tamilnadu - 629 002.
Unit 303, Vanguard Rise,
5th Main, Konena Agrahara,
Old Airport Road, Bangalore - 560 017.
Call: +91 6383016411
Email: sales@mafiree.com