Rudraksh Dixit
Rudraksh Dixit

Reputation: 131

MongoDB/Moongoose set TTL for a specific document

I am trying to create an API using Express js, where the user can add data and give a specific time(after which the data will be deleted from the DB automatically) when he wants to delete that specific record. How can I achieve this, using TTL for a specific record and not for a whole collection?

Upvotes: 0

Views: 69

Answers (1)

Wernfried Domscheit
Wernfried Domscheit

Reputation: 59436

Insert a document like this:

db.collection.insertOne({to_be_deleted_at: ISODate("2020-09-30T00:00:00")})

and create a TTL Index for it:

db.collection.createIndex({ to_be_deleted_at: 1 }, { expireAfterSeconds: 0 })

Then such document will be removed at 2020-09-30 00:00:00

Upvotes: 1

Related Questions