Ahsath
Ahsath

Reputation: 443

Is it possible to expire a MongoDB document based on a field in it?

For example, lets say that I have a collection called credits with this document schema:

{
    "_id": ObjectId(...),
    credits: 600
}

When the field credits get to 0 I will like to expire the document a.k.a delete it automatically using TTL index?

Upvotes: 0

Views: 847

Answers (1)

R2D2
R2D2

Reputation: 10727

After mongodb 3.2 , TTL index can be created with conditional delete using PartialFilterExpression following way:

db.credits.createIndex( { due_date: 1 },   { expireAfterSeconds: 1, partialFilterExpression: { credits:0  } } );

example how it works:

mongos> db.credits.find() // few documents inserted for the test
{ "_id" : ObjectId("5ffb62ac3deba4c4323818e0"), "doc" : 1, "credits" : 10, "due_date" : ISODate("2021-01-10T20:25:16.208Z") }
{ "_id" : ObjectId("5ffb62bf3deba4c4323818e2"), "doc" : 3, "credits" : 20, "due_date" : ISODate("2021-01-10T20:25:35.449Z") }
{ "_id" : ObjectId("5ffb63813deba4c4323818e4"), "doc" : 2, "credits" : 0, "due_date" : ISODate("2021-01-10T20:28:49.241Z") }

mongos> db.credits.find()   //  2 minutes after 20:28h
{ "_id" : ObjectId("5ffb62ac3deba4c4323818e0"), "doc" : 1, "credits" : 10, "due_date" : ISODate("2021-01-10T20:25:16.208Z") }
{ "_id" : ObjectId("5ffb62bf3deba4c4323818e2"), "doc" : 3, "credits" : 20, "due_date" : ISODate("2021-01-10T20:25:35.449Z") }

mongos>

( The mongod process will remove documents 1 sec after the due_date is reached only when the credits is 0 , note that removal may not be very accurate since the removal process is checking every 60 sec by default )

Upvotes: 1

Related Questions