Q18: What is a Time-To-Live (TTL) Index and how is it used?
A TTL index is a single-field index on a Date field that automatically removes documents from a collection after a specified duration (in seconds). A background thread wakes up every 60 seconds to purge expired documents. Ideal for sessions, verification OTPs, and temporary logs.
Creating a TTL Index in Mongoose
const sessionSchema = new mongoose.Schema({
userId: String,
createdAt: {
type: Date,
default: Date.now,
expires: 3600 // Automatically deletes document after 1 hour (3600s)
}
});Configures automatic document deletion 3600 seconds after creation time.
Key Takeaways
Automatically purges documents based on date fields.
Must be created on single date-type fields.
Knowledge Check
How often does the MongoDB background thread run to delete expired TTL index documents?