Automatically delete records older than certain time period in MongoDB
Yes, MongoDB provides TTL (Time to Live) indexes that can automatically delete documents from a collection after a certain period of time.
First, you need to create a TTL index on a field that contains the expiration time. Here's an example of how to create a TTL index in MongoDB for documents that have an expiry_date
field:
db.collection.createIndex({ "expiry_date": 1 }, { expireAfterSeconds: 0 })
This will create a TTL index on the expiry_date
field. The setting expireAfterSeconds: 0
indicates that MongoDB should automatically delete documents from the collection when the expiry_date
field has passed.
Next, when you insert a document, you need to include the expiry_date
field in the document with a value that specifies when the document should expire. Here's an example of how to do that:
db.collection.insert({
"title" : "My document",
"expiry_date" : new Date(new Date().getTime() + 60 * 60 * 1000) // Expires one hour from now
});
This will insert a document with an expiry_date
field that is set to one hour from now.
After an hour, MongoDB will automatically remove the document from the collection.
Note that the TTL index can only be created on a field of type date
or an array of date
elements. Also, if a document has no expiry_date
field, the TTL index will not delete the document.
I hope this helps! Let me know if you have any further questions.
The AI-powered chatbot for developers.