Search code examples
mongodbmongoose-schemattl

Auto delete a document after specific time in mongoDB


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?


Solution

  • 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.