As you already saw in Chapter 4, Indexing, MongoDB offers us an index type that helps us to remove data from a collection after a certain amount of time in seconds, or by a specific date.
Indeed, the TTL is a background thread that executes on a mongod instance that looks for documents with date typed fields on the index, and removes them.
Consider a customers
collection with the following document:
{ "_id" : ObjectId("5498da405d0ffdd8a07a87ba"), "username" : "customer1", "email" : "[email protected]", "password" : "b1c5098d0c6074db325b0b9dddb068e1", "accountConfirmationExpireAt" : ISODate("2015-01-11T20:27:02.138Z") }
To expire the documents in this collection after 360 seconds, we should create the following index:
db.customers.createIndex( {accountConfirmationExpireAt: 1}, {expireAfterSeconds: 3600} )
To expire the documents at exactly 2015-01-11 20:27:02, we should create the following index:
db.customers.createIndex( {accountConfirmationExpireAt: 1}, {expireAfterSeconds: 0} )
When using the TTL function, we must take extra care and keep the following points in mind:
3.147.89.30