Deleting specific documents after 7 days

I have made a TTL index on my Schema using:

Schema.index({ expire: 1 }, { expireAfterSeconds: 604800 })

When I want documents to be deleted after the 7 days I use:

Schema.updateMany(query, { $set: { expire: Date.now() } })

Is this the correct way? Is there an easier way to delete specific documents after 7 days?
When I want a document to expire do I need to set the TTL index value to a date or could I use a different value?

Hi @mental_N_A,

The ttl index is a good way to expire documents gradually like you mentioned.

You can have the expire time set to seconds to live only and you can extend it via collMod command.

There is a trick where you can set the expireAfterSeconds to 0 and than once the time specified on your field (eg. expire) is crossed the document is eligible for deletion immediately.

So you can write each document with expire of now + 7 days , during document creation, and no need to bulk update.

Let me know if that helps.

Thanks
Pavel

1 Like