What if your database could clean itself automatically, so you never worry about old data piling up?
Why TTL indexes for auto-expiry in MongoDB? - Purpose & Use Cases
Imagine you have a huge collection of temporary data, like user sessions or event logs, and you need to delete old entries regularly to keep your database clean.
Doing this by hand means writing scripts to find and remove expired data every day.
Manually deleting old data is slow and easy to forget.
If you miss a day, your database grows too big and slows down.
Also, running deletion scripts can cause errors or accidentally remove the wrong data.
TTL indexes automatically remove documents after a set time.
You just set the expiration time once, and MongoDB cleans up expired data for you without extra work.
db.sessions.find({createdAt: {$lt: new Date(Date.now() - 3600000)}}).forEach(doc => db.sessions.remove({_id: doc._id}))db.sessions.createIndex({createdAt: 1}, {expireAfterSeconds: 3600})It lets your database self-manage temporary data, saving time and avoiding mistakes.
A chat app uses TTL indexes to automatically delete messages older than 24 hours, keeping conversations fresh and storage small.
Manual cleanup is slow and error-prone.
TTL indexes automate data expiration.
This keeps your database efficient and tidy without extra effort.