I want to delete a document after a specified amount of time. Like if the user selects 24 hours then it should be auto-deleted after 24 hours. I heard about TTL in mongo but in that, I have to specify a time in the schema and it will be the same for all documents.
Is there any way to dynamically set the expiration time for every document?
CodePudding user response:
There is no system to support this per se, one suggestion is that you add a Date attribute to each document you want to delete and maintain a job that checks documents that have this attribute/if the attribute value has passed the current time, if so, delete the document.
CodePudding user response:
We can add a field like expireAt and it will contain the Date of expiration. Now add a TTL index like this-
db.dbname.createIndex({expireAt:1},{expireAfterSeconds:0})
Now just add expireAt field in every document with the expiration Date. It will auto-remove when the current time reaches the expiration date.