TTL indexes help automatically remove old data from your database after a set time. This keeps your data fresh and saves space without manual cleanup.
0
0
TTL indexes for auto-expiry in MongoDB
Introduction
You want to delete user sessions after they expire.
You need to remove temporary logs older than a day.
You want to clear cached data automatically after some time.
You want to keep only recent sensor readings and discard old ones.
You want to auto-delete expired coupons or offers.
Syntax
MongoDB
db.collection.createIndex({ <field>: 1 }, { expireAfterSeconds: <seconds> })The field must be a date type.
expireAfterSeconds sets how many seconds after the date the document expires.
Examples
This removes documents 1 hour after the
createdAt date.MongoDB
db.sessions.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 3600 })This deletes log entries 24 hours after their
timestamp.MongoDB
db.logs.createIndex({ "timestamp": 1 }, { expireAfterSeconds: 86400 })Sample Program
This example creates a TTL index that deletes documents 10 seconds after their createdAt time. It inserts one document and shows it immediately.
MongoDB
use mydb // Create a TTL index on 'createdAt' field to expire documents after 10 seconds db.tempData.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 10 }) // Insert a document with current date db.tempData.insertOne({ "name": "test", "createdAt": new Date() }) // Query documents immediately printjson(db.tempData.find().toArray())
OutputSuccess
Important Notes
TTL cleanup runs in the background every 60 seconds, so documents may not disappear exactly at the expiration time.
TTL indexes only work on fields with BSON date type.
You cannot update the TTL value without dropping and recreating the index.
Summary
TTL indexes automatically delete documents after a set time.
They help keep data storage clean without manual work.
Use a date field and expireAfterSeconds option to set expiry.