Reputation: 213
I want to auto delete documents from a collection
in mongodb based on a ttl
. I have gone through other answers and figured out the following way:
db.collection.createIndex( { "createdAt": 1 }, { expireAfterSeconds: 3600 } )
This will delete the documents after expireAfterSeconds
interval from createdAt
field.
However, the problem with above is that it is not document specific. In the above scenario, all documents will be deleted after 3600
time from creation. However, in my case, each document in the collection needs to be deleted at different time intervals. So, each document need to have its own ttl
. How can I achieve this?
Upvotes: 21
Views: 30406
Reputation: 1598
You have to add an new filed to to you collection like: expiresAt
, and fill the document expiration date for each document individually. This field is independent from createdAt
.
After create an index for new field:
db.collection.createIndex( { "expiresAt": 1 }, { expireAfterSeconds: 0 } )
Upvotes: 1
Reputation: 2173
The TTL index will remove all the documents that are older than the indexed field + the expireAfterSeconds
values.
Take the following example (using mongosh).
Start by creating 10 documents that have a "expiresAt" field that will be within 10 minutes of now
.
for (let i = 0; i < 10; i ++) {
let expiresAt = new Date();
expiresAt.setMinutes(expiresAt.getMinutes() + Math.round(Math.random() * 10));
db.ttl.insertOne({expiresAt})
}
If you create your TTL index
db.ttl.createIndex( { "expiresAt": 1 }, { expireAfterSeconds: 1 } );
If you wait 5 minutes, (statistically ;) ) half of your documents should have been deleted. If you waited another 5 minutes, all of them should be gone. However if you update the expiresAt
field.
let newExpiresAt = new Date();
newExpiresAt.setMinutes(newExpiresAt.getMinutes() + 10);
db.ttl.updateMany({}, {expiresAt: newExpiresAt})
Your documents won't expire for another 10 minutes.
More on the TTL indexes in the docs
Upvotes: 1