Mongo Native TTL

Turns out MongoDB supports a native TTL mechanism, natively removing documents at or after a certain amount of time, similarly to Redis’s auto-expiry. Here’s an example usage flow:

> db.foo.insert({time: new Date(), name: "Jones"})
> db.foo.find()
{ "_id" : ObjectId("53ce96f03fdf121aa2e36622"), "time" : ISODate("2014-07-22T16:53:04.001Z"), "name" : "Jones" }
> db.foo.ensureIndex( { "time": 1 }, { expireAfterSeconds: 5 } )
> db.foo.find()
{ "_id" : ObjectId("53ce96f03fdf121aa2e36622"), "time" : ISODate("2014-07-22T16:53:04.001Z"), "name" : "Jones" } //still there, less than 5 seconds have passed
> //wait 5 seconds
> db.foo.find()
> //empty

Mongo Awesomeness FTW. 

Advertisements