Problem Statement
What happens to documents when a TTL (Time To Live) index expires them?
Explanation
TTL indexes automatically delete documents after a specified period of time. A background thread runs every 60 seconds to check for and remove expired documents. This is useful for data that should only exist temporarily, such as session information, logs, or cached data.
You create a TTL index on a date field and specify the expiration time in seconds. Documents are deleted when the indexed date field plus the expiration time is less than the current time.
Code Solution
SolutionRead Only
// Create TTL index - expire after 1 hour
db.sessions.createIndex(
{ createdAt: 1 },
{ expireAfterSeconds: 3600 }
)
// Insert document
db.sessions.insertOne({
userId: 123,
token: "abc123",
createdAt: new Date()
})
// Document automatically deleted 1 hour after createdAt
// TTL index for logs - expire after 30 days
db.logs.createIndex(
{ timestamp: 1 },
{ expireAfterSeconds: 2592000 }
)