Home > OS >  How to implement TTL for specific mongo documents
How to implement TTL for specific mongo documents

Time:09-28

To give you some context first, my service stores notifications temporary. There is a max TTL (predefined by the Administrator), however I want to allow the user to specify the custom TTL for each notification. Of course, this TTL needs to be always lower than the max TTL.

My question is, does mongo have a built-in TTL for each document? I know there is for the whole document kind, that is, every document (from the same collection) has the same TTL value. However here I want different TTL values for documents from the same collection.

PS: I could use, for example, a quartz job to implement this use case, I just want to avoid developing solutions that are already implemented.

CodePudding user response:

Yes, Mongo internally keeps expiration date per document and you can set manually date of expiration for each document.

It is described in Mongo's documentation here: https://docs.mongodb.com/manual/tutorial/expire-data/#expire-documents-at-a-specific-clock-time

Relevant example from documentation:

db.log_events.createIndex( { "expireAt": 1 }, { expireAfterSeconds: 0 } )
db.log_events.insert( {
   "expireAt": new Date('July 22, 2013 14:00:00'),
   "logEvent": 2,
   "logMessage": "Success!"
} )

And explanation for it:

MongoDB will automatically delete documents from the log_events collection when the documents' expireAt value is older than the number of seconds specified in expireAfterSeconds, i.e. 0 seconds older in this case. As such, the data expires at the specified expireAt value.

  • Related