menu
Time to Live (TTL) is a feature in MongoDB that allows you to automatically expire documents after a specified amount of time. This is useful for scenarios where you want to keep data for a limited duration, such as temporary data, session data, or cache entries.

How TTL works:
  1. Index creation: To enable TTL for a collection, you create an index on a field that represents the expiration time. This field must be of type Date.
  2. Expiration time setting: When creating the index, you specify the TTL value in seconds.
  3. Document expiration: MongoDB periodically scans the collection and deletes documents whose expiration time has passed.

Example:
db.sessions.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 3600 });
This creates an index on the expiresAt field and sets the TTL to 1 hour (3600 seconds). Any documents in the sessions collection with an expiresAt value that is older than 1 hour will be automatically deleted.

Use cases for TTL:
  • Session management: Store session data with a TTL to automatically expire inactive sessions.
  • Temporary data: Keep temporary data for a limited time, such as cached results or temporary files.
  • Data retention policies: Implement data retention policies by setting appropriate TTL values for different types of data.