Mafiree logo
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
Schedule a Call
Menu
  • About
  • Services
  • Blogs
  • Careers
  • Products
    • orbit logo Orbit
    • streamer logo Xstreami
  • Contact
  • Schedule a Call
Database
Database Database Managed Services
MySQL MySQL
MySQL Consulting Services
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB MongoDB
MongoDB Consulting Services
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL PostgreSQL
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
SQL Server MSSQL
MSSQL Consulting Services
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Aerospike
Aerospike Consulting Services
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Database Administration
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
Analytics DB
Analytics DB Analytics DB Services
Clickhouse Clickhouse
ClickHouse Consulting Services
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB TiDB
TiDB Consulting & Architecture Planning
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB ScyllaDB
ScyllaDB Consulting & Architecture Planning
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
DevOps
DevOps DevOps Services
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Networking
Networking Networking Services
Basic Basic
Advanced Advanced
MySQL MySQL
MongoDB MongoDB
PostgreSQL PostgreSQL
MSSQL MSSQL
Aerospike Aerospike
Clickhouse Clickhouse
TiDB TiDB
ScyllaDB ScyllaDB
Version Control Version Control
Kubernetes Kubernetes
Infrastructure Infrastructure Management
Web Servers Web Servers
Basic Basic
Advanced Advanced
MySQL Consulting Services
MySQL Migration Services
MySQL Optimization & Query Tuning
MySQL Database Administration
MySQL Backup & Recovery
MySQL Security & Maintenance
MySQL Cloud Services (AWS RDS, Aurora, Google Cloud SQL, Azure)
MySQL for Ecommerce
MySQL High Availability & Replication
MongoDB Consulting Services
MongoDB Migration Services
MongoDB Optimization & Query Tuning
MongoDB Database Administration
MongoDB Backup & Recovery
MongoDB Security & Maintenance
MongoDB Cloud (Atlas)
MongoDB Solutions by Industry
MongoDB High Availability & Replication
PostgreSQL Consulting
PostgreSQL Migration & Upgrades
Performance Tuning & Query Optimization
PostgreSQL Administration & Managed Services
High Availability, Clustering & Replication
PostgreSQL Backup, Recovery & Disaster Planning
PostgreSQL Security, Compliance & Auditing
PostgreSQL for Analytics & Data Warehousing
PostgreSQL on Cloud & Containers
PostgreSQL Extensions & Open-Source Integrations
PostgreSQL for Every Industry
MSSQL Consulting Services
MSSQL Migration Services
MSSQL Optimization & Query Tuning Services
MSSQL Database Administration Services
MSSQL Backup & Recovery Services
MSSQL High Availability & Replication Services
MSSQL Security & Compliance Services
MSSQL Performance Monitoring & Health Checks
MSSQL Solutions by Industry
Aerospike Consulting Services
Aerospike Migration Services
Aerospike Performance Optimization & Tuning
Aerospike Database Administration
Aerospike Backup & Recovery
Aerospike High Availability
Aerospike Cloud & Hybrid Deployments
Aerospike for Real-Time Applications (AdTech, FinTech, Retail, IoT)
ClickHouse Consulting Services
ClickHouse Migration Services
ClickHouse Optimization & Query Tuning
ClickHouse Database Administration
ClickHouse Backup & Recovery
ClickHouse Security & Maintenance
ClickHouse Cloud Services (ClickHouse Cloud, AWS, GCP, Azure)
ClickHouse Solutions by Industry
ClickHouse High Availability & Replication
TiDB Consulting & Architecture Planning
TiDB Administration & Maintenance
TiDB Security and Privacy Maintenance
TiDB Performance & Query Optimization
TiDB Migration Services
TiDB Backup & Disaster Recovery
TiDB High Availability Solutions
TiDB Solutions by Industry
TiDB Cloud Services
ScyllaDB Consulting & Architecture Planning
ScyllaDB Administration & Maintenance
ScyllaDB Security and Privacy Maintenance
ScyllaDB Performance & Query Optimization
ScyllaDB Migration Services
ScyllaDB Backup & Disaster Recovery
ScyllaDB High Availability Solutions
ScyllaDB Solutions by Industry
ScyllaDB Cloud Services
  1. Home
  2. > Blogs
  3. > MongoDB
  4. > Let MongoDB Clean Up After Itself: A Complete Guide to TTL Indexes

Let MongoDB Clean Up After Itself: A Complete Guide to TTL Indexes

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

Subscribe for email updates

In a world drowning in logs, every millisecond counts.

 

Have you ever:

  • Struggled with a bloated MongoDB collection full of outdated logs?
  • Set cron jobs to purge old data manually?
  • Wished MongoDB could just “clean itself”?

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.

 

What’s a TTL Index?

A TTL index in MongoDB is a type of index that automatically removes documents from a collection after a certain period. Perfect for:

  • Application logs
  • User sessions or tokens
  • Expired notifications
  • Cache data

Why use it?   

  • Automatic cleanup
  • Saves storage
  • Boosts query performance
  • Zero scripting or cron jobs

How TTL Indexes Work

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.

 

Internal Flow – TTL Operation Logic

To better understand this, here’s a visual flowchart of how MongoDB handles TTL expiration:

 

 

Flow Description:

  1. Index Creation: TTL index is created on a date field (e.g., createdAt) with a threshold (e.g., 1 month).
  2. Background Monitor: Every 60 seconds, MongoDB checks the timestamp of each document.
  3. Evaluation:     If a document is older than the TTL, it is deleted.

                                 If it’s still within the threshold, it’s retained.                                                                                                                                                                                                                                                                                                                                             

This cycle repeats automatically—no developer effort needed.

 

Step-by-Step: Setting Up a TTL Index

Step 1: Insert a Document with a Timestamp

db.logs.insertOne({
  message: "User login",
  level: "INFO",
  createdAt: new Date()
});

Step 2: Create a TTL Index (e.g., 10 Days)

db.logs.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 864000 } // 10 days
);

Step 3: Verify the Index

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:

  • You want to delete logs from a specific sensor
  • Only some records need expiry based on a condition
  • You're working with time-series collections and need targeted cleanup
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.ttl

Sample 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?

  • Ensures that TTL deletions are happening as expected
  • Detects performance bottlenecks or misconfigurations
  • Helps in tuning the TTL monitor interval if needed

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 });
  • This sets the TTL monitor to run every 3600 seconds (1 hour).
  • Use with caution—expired documents will remain longer before deletion.
  • For permanent changes, add it to mongod.conf or use it in the startup command.

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:  
 

  • High write volume
  • Time-sensitive queries
  • Large data sets

Real-World Impact  
We applied TTL indexes in a microservice environment logging over 3 million events/month.  

Results:

  • 40% disk space savings
  • Reduced index bloat
  • No need for scheduled cleanup scripts
  • Cleaner collections, faster queries

When Not to Use TTL?   

TTL is not suitable if:  
 

  • You need soft-deletes or restore functionality
  • Data must be archived for compliance or auditing
  • Expiry conditions are dynamic or not based on a fixed timestamp

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.  
 

  • Easy to implement
  • Hands-free maintenance
  • Boosts performance  

So stop writing cleanup scripts. Let MongoDB clean up after itself.

Author Bio

Rexcily

Rexcily Rijo is a MongoDB Certified DBA at Mafiree, with deep expertise in MongoDB database administration, performance optimization, and scalable data solutions. He writes practical, hands-on technical content focused on MongoDB internals, best practices for database operations, TTL and index strategies, and real-world techniques that help engineers and DBAs manage and optimize modern document databases.

Leave a Comment

Related Blogs

MongoDB Transactions: A Comprehensive Guide to ACID Compliance

MongoDB ensures data consistency with single-document atomic operations and multi-document transactions. This guide explains how to implement transactions, their limitations, performance impacts, and best practices for production environments. It also highlights when to use distributed transactions and how expert consulting can help optimize performance.

  284 views
Top 10 MongoDB Operators Every Developer Should Know (With Examples)

Unlock MongoDB’s full potential! Discover the most powerful MongoDB query operators to supercharge your queries with practical examples every developer can use. #MongoDB #DeveloperTips

  2698 views
Reclaiming MongoDB Storage Space: A Journey to 50% Space Reduction

Efficiently Reclaim Disk Space in MongoDB: Strategies and Solutions for Optimal Performance.

  1988 views
Don't Let Hackers In: How to Secure and Harden Your MongoDB Database

Learn how to protect your MongoDB database with robust security practices, including user authentication, encryption, IP whitelisting, and input validation. Ensure your data remains safe and accessible in today's evolving threat landscape.

  3645 views
Seamless Data Transition: Exploring MongoDB Cluster To Cluster Sync

Achieve real-time data consistency with MongoDB Cluster-to-Cluster Sync. Discover how MongoSync enables seamless data synchronization for disaster recovery, global availability, and smooth migrations.

  5658 views

Subscribe for email updates

Get in touch with us

Highlights

More than 6000 Servers Monitored

Happy Clients

Certified DBAs

24 x 7 x 365 Support

PCI

Database Services

MySQL MongoDB PostgreSQL SQL Server Aerospike Clickhouse TiDB MariaDB Columnstore

Quick Links

Careers Blog Contact Privacy Policy Disclaimer Policy

Contacts

Linkedin Mafiree Facebook Mafiree Twitter Mafiree

Nagercoil Office

Miru IT Park, Vallankumaranvillai,

Nagercoil, Tamilnadu - 629 002.

Bangalore Office

Unit 303, Vanguard Rise,

5th Main, Konena Agrahara,

Old Airport Road, Bangalore - 560 017.

Call: +91 6383016411

Email: sales@mafiree.com


Copyright © - All Rights Reserved - Mafiree