Reputation: 23
How do I add TTL (Time to Live) to a specific document in Mongo DB (Mongo database)? I made a document (tabke called task) and I want to make an expiry date such that when this date comes, the task is automatically deleted.
Thank you in advacnce
Upvotes: 1
Views: 3752
Reputation: 4078
As per the documentation, you need a ttl
index
For example, the following operation creates an index on the log_events collection’s createdAt field and specifies the expireAfterSeconds value of 3600 to set the expiration time to be one hour after the time specified by createdAt.
db.log_events.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
When adding documents to the log_events collection, set the createdAt field to the current time:
db.log_events.insert( {
"createdAt": new Date(),
"logEvent": 2,
"logMessage": "Success!"
} )
Upvotes: 5