NashTech Blog

Table of Contents

Both TTL (Time-To-Live) Indexes and Capped Collections are special features in MongoDB that help manage data lifecycle and storage efficiency, but they serve different purposes and operate differently. Let’s compare the two:

TTL Index (Time-To-Live Index)

TTL index is used to automatically delete documents after a specified amount of time.

Key Characteristics

Example

To create a TTL index on a createdAt field that deletes documents 1 hour (3600 seconds) after their creation:

db.<collectionName>.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

Use Cases

  • Session management (auto-expiring sessions)
  • Caching (stale data removal)
  • Logs and audits (keeping data only for a specific retention period)

Capped Collection

Capped collection is a fixed-size, circular collection that maintains the insertion order. Once the collection reaches its maximum size (either by number of documents or storage space), the oldest documents are automatically removed to make room for new ones.

Key Characteristics

  • Fixed Size: Defined with a maximum size (in bytes) and an optional maximum number of documents.
  • Circular Behavior: Operates in a circular fashion, where once the allocated space is full, the oldest documents are overwritten by new inserts.
  • High Performance: Capped collections are optimized for high-throughput inserts and reads, making them very efficient for write-heavy operations.
  • No Deletions: Documents can’t be deleted or removed individually (except through collection deletion). The removal happens automatically based on the collection size.

Example

To create a capped collection with a maximum size of 100KB and a limit of 1000 documents:

db.createCollection("<CollectionName>", { capped: true, size: 100 * 1024, max: 1000 });

Use Cases

  • Logs (e.g., application logs, audit trails)
  • Real-time data (e.g., IoT sensor data, metrics, and monitoring)
  • Message queues (temporary storage for fast-moving data)

Picture of nghiadinhtrong

nghiadinhtrong

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

Scroll to Top