Time-To-Live (TTL) indexes
TTL (Time-To-Live) indexes are useful when you need documents to be deleted automatically after a certain time. It's ideal for temporary records, logs, or session data that you don't want to keep indefinitely. Unlike most indexes that focus on query performance, TTL indexes serve a different purpose by ensuring outdated data is deleted periodically and efficiently.
They are single-field indexes and not allowed as multi-field/compound indexes.
- Documents inserted before the index was created may not be affected until an insert or update operation occurs. It is recommended to create the TTL index before inserting documents.
- The cleanup of expired documents is a background operation that runs every 60 seconds, so deletion may not be immediate.
Creating a TTL index
A TTL index is created using the createIndex
command with the field you want to index and the expireAfterSeconds
option set to the number of seconds before a document expires.
The field must have a Date
type.
For example, let's create a TTL index for the reservation.date
field in a books
collection.
db.runCommand({
createIndexes: 'books',
indexes: [
{
key: { 'reservation.date': 1 },
name: 'reservation_ttl',
expireAfterSeconds: 60
}
]
})
Let's insert a document into the books
collection:
db.runCommand({
insert: 'books',
documents: [
{
title: 'The Great Gatsby',
author: 'F. Scott Fitzgerald',
reservation: {
user: 'Ethan Smith',
date: ISODate('2025-03-15T11:00:00Z')
}
}
]
})
After 60 seconds, the document will be deleted in the next cleanup operation.