website/versioned_docs/version-v2.5/guides/ttl-indexes.mdx
import CodeBlock from '@theme/CodeBlock' import CreateTTLIndexRequest from '!!raw-loader!./ttl-indexes/1-create-ttl-index.request.js' import InsertTTLDataRequest from '!!raw-loader!./ttl-indexes/2-insert-ttl-data.request.js'
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.
:::note
:::
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.
<CodeBlock language="js">{CreateTTLIndexRequest}</CodeBlock>
Let's insert a document into the books collection:
<CodeBlock language="js">{InsertTTLDataRequest}</CodeBlock>
After 60 seconds, the document will be deleted in the next cleanup operation.