Data self-expiration

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:

  • We cannot create a TTL index on a capped collection because MongoDB will not be able to remove documents from the collection.
  • A TTL index cannot have a field that is part of another index.
  • The field of the index should be a Date or array of a Date type.
  • Despite having the background thread in every replica set node, which removes the documents when we have a TTL index, it will only remove them from the primary one. The replication process will delete the documents from the secondary nodes of the replica set.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.168