Question: How do you implement TTL (Time-To-Live) caching in MongoDB?

Answer

TTL (Time-To-Live) indexes in MongoDB are a powerful feature used for automatically removing documents from a collection after a certain amount of time or at a specific clock time. This is particularly useful for caching purposes, where data only needs to be stored temporarily.

Creating a TTL Index

To set up a TTL index, you must use the createIndex() method on a collection, specifying an expiration time in seconds for documents. The field you index should either be a Date type for expiration after a certain amount of time or contain a specific future expiry date.

Example: Expiring Documents After a Set Duration

This example shows how to create a TTL index that automatically deletes documents 24 hours after their creation:

db.sessions.createIndex({ \"createdAt\": 1 }, { expireAfterSeconds: 86400 })

Here, sessions is the name of the collection, and createdAt is the field that holds the document's creation timestamp. The documents in this collection will expire and be deleted 24 hours (86400 seconds) after the value of their createdAt field.

Example: Setting Specific Expiry Times

If you want documents to expire at a specific clock time rather than after a relative duration, store the exact expiry time in the field you're indexing. In this case, you do not specify the expireAfterSeconds option when creating the index:

db.events.createIndex({ \"expireAt\": 1 }, { expireAfterSeconds: 0 })

For this index, each document in the events collection should have an expireAt field with a Date value indicating when it should expire. MongoDB will automatically delete these documents at the specified time.

Considerations

  • The TTL mechanism runs every 60 seconds, so document deletions may not occur exactly at the expiration time but shortly after.
  • Only fields containing BSON Date types or arrays containing Date types can be indexed with TTL.
  • While primarily used for caching, TTL indexes are also handy for any scenario requiring automatic document expiration, such as session management or temporary data storage.

In summary, MongoDB's TTL indexes offer a convenient way to manage temporary data by automatically expiring documents based on time criteria. By utilizing these indexes, developers can efficiently implement caching mechanisms within their applications.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.