Wednesday, February 5, 2014

TTL (Time to Live) Indexes in MongoDB

Time To Live or TTL indexes are special kind of indexes which remove the expired documents (rows) from collection (tables) after a fix time. MongoDB provide this feature by which you can create Index which will take care of removing documents (row) after a certain time is passed in the background.

To create a TTL Index the syntax is following:

db.collectionname.ensureIndex ({fieldname:1 OR -1},{expireAfterSeconds: timeinseconds})

For example to create TTL index on empCalendar collection (table) on CreatedOn filed we can write following command. With this, we have created an Index which will start removing all the documents (row) where value in CreatedOn filed will be less than the (current time + 5 minute).

db.empCalendar.ensureIndex({"CreatedOn":1},{expireAfterSeconds: 300})

I created this Index on 4th Feb. As you can see in the below screen we have two documents where value of CreatedOn field is in future. MongoDB will delete all the documents except the two where CreatedOn value is a future date after 5 minutes.

Only two records were left in the Collection (table) after 5 minute.

With TTL Index we can also set a fix time or fix clock after which each of the document will be removed from the Collection.

To understand this let us take an example. We have following data in empCalendar collection.

As you can see each of the documents has their own CreatedOn field which holds a date and time. To create a TTL Index which will remove each of the document in this collection after date and time in CreatedOn is passed, we can issue below command.

db.empCalendar.ensureIndex({"CreatedOn":1},{expireAfterSeconds:0})

There are certain limitations with TTL Index

  • TTL Index can be created on field which stored date values
  • TTL Index cannot be created on multiple fields
  • If a field already has an existing index, TTL index cannot be created on that.
  • The _Id() field does not support TTL Indexes.


Popular Posts

Blog Archive

Real Time Web Analytics