0
0
MongoDBquery~3 mins

Why TTL indexes for auto-expiry in MongoDB? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your database could clean itself automatically, so you never worry about old data piling up?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
db.sessions.find({createdAt: {$lt: new Date(Date.now() - 3600000)}}).forEach(doc => db.sessions.remove({_id: doc._id}))
After
db.sessions.createIndex({createdAt: 1}, {expireAfterSeconds: 3600})
What It Enables

It lets your database self-manage temporary data, saving time and avoiding mistakes.

Real Life Example

A chat app uses TTL indexes to automatically delete messages older than 24 hours, keeping conversations fresh and storage small.

Key Takeaways

Manual cleanup is slow and error-prone.

TTL indexes automate data expiration.

This keeps your database efficient and tidy without extra effort.