TTL Indexes
TTL Indexes: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 46 of 100
TTL Indexes
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Indexing & Performance
What is this?
A TTL (time-to-live) index deletes documents automatically after a delay based on a date field. MongoDB’s background thread removes expired docs.
Why should you care?
Sessions, OTPs, password-reset tokens, and temporary uploads should disappear without a custom cron at first.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.sessions.insertOne({
userId: ObjectId(),
token: "abc",
createdAt: new Date()
})
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 })
db.sessions.find()
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- createdAt is a real Date.
- The TTL index expires documents 3600 seconds after createdAt.
- The delete is not instant to the second — a background job runs periodically.
Practice next
- Create sessions with createdAt: new Date().
- Create TTL index with a short expireAfterSeconds (e.g. 60) for a test.
- Wait and confirm documents disappear.
- Use expireAfterSeconds: 0 with a absolute expireAt date field pattern.
- Partial filter TTL only for type: "otp".
Remember
TTL indexes auto-delete old documents. Need a BSON date field. Perfect for sessions and OTPs.
OTP collection cleanup
Login OTPs expire in 5 minutes via TTL on createdAt.
Outcome: No leftover codes clutter the database.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!