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
- Expiration: Documents expire based on a date field or timestamp. When the specified time is reached, MongoDB automatically deletes the document.
- Index Type: TTL is a special type of single-field index.
- Granularity: The background process that removes expired documents runs every 60 seconds, so documents are deleted in a “lazy” fashion (i.e., within a minute after expiration).
- Data Retention: Great for use cases where you want to store data temporarily, like caching, session tokens, or audit logs with expiration dates.
- Automatic Deletion: The deletion is performed automatically in the background and doesn’t require additional application logic.
- Performance Impact: TTL indexes can slightly impact performance due to the overhead of periodically checking for expired documents.
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)