0

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?

Het Delwadiya
  • 83
  • 1
  • 10
  • Have you checked out the [TTL index](https://www.mongodb.com/docs/manual/core/index-ttl/)? – ray Apr 07 '22 at 12:46
  • I have checked but it doesn't have the option of dynamic expiration time setting. we have to set expiration time in schema only. – Het Delwadiya Apr 07 '22 at 12:56
  • Does this answer your question? [Delete MongoDB document at specific time](https://stackoverflow.com/questions/38472125/delete-mongodb-document-at-specific-time) – Blue Robin Jun 01 '23 at 00:12
  • Yes, I have already found out the solution on internet and posted the same for others as answer. Thanks! – Het Delwadiya Jun 03 '23 at 08:44

2 Answers2

1

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.

Het Delwadiya
  • 83
  • 1
  • 10
-1

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.

zeehyt
  • 193
  • 7