$ lexprog.com

// notes from an old coder -- php, databases, and the occasional rant

[February 29, 2024] MongoDB

MongoDB TTL Collections: Auto-Expiring Data

MongoDB TTL Collections: Auto-Expiring Data

────────────────────────────────────────────────────────

MongoDB TTL Collections: Auto-Expiring Data

Tip: TTL Index

$collection->createIndex(
    ['created_at' => 1],
    ['expireAfterSeconds' => 86400]
);

Documents are automatically deleted 24 hours after created_at.

Gotcha: TTL Runs Every 60 Seconds

MongoDB's background task runs every 60 seconds. Expiration is not instant.

Tip: Expire at Specific Time

$document = [
    'data' => 'session data',
    'expiresAt' => new MongoDB\BSON\UTCDateTime(strtotime('+1 hour') * 1000),
];
$collection->createIndex(['expiresAt' => 1], ['expireAfterSeconds' => 0]);

Each document has its own expiration time.

Gotcha: TTL Only Works on Date Fields

The indexed field must be a BSON Date type. Strings and numbers don't work.

Tip: TTL for Cache Cleanup

$collection->createIndex(['cached_at' => 1], ['expireAfterSeconds' => 3600]);

Auto-cleans cache entries older than 1 hour.

Gotcha: TTL and Replica Sets

TTL works on replica sets. Secondary nodes don't delete — only the primary does.

Tip: Embed or Reference? The 80/20 Rule

If you always access data together, embed it. If you access it independently, reference it. The 16MB document size limit is the hard boundary — stay under 1MB for most documents.

Tip: Index Your Query Patterns, Not All Fields

Creating indexes on every field wastes RAM. Use explain() to find in-memory sorts and collection scans. Index only what your actual queries filter on.

Gotcha: No Transaction Rollback for Index Builds

Building an index on a large collection can take hours. If it fails midway, the partial index is silently discarded. Plan index builds during maintenance windows.

Senior Insight

TTL indexes in MongoDB are a set-and-forget way to expire old data. I've used them for session management, temporary tokens, and log rotation. The critical detail: MongoDB checks TTL indexes every 60 seconds, so data can persist up to 60 seconds past its expiration time. For security-sensitive data (like password reset tokens), I add an application-level filter to check expiration time explicitly, using the TTL index only as cleanup.

Source: MongoDB Developer Center (https://www.mongodb.com/developer/), MongoDB Engineering Blog (https://www.mongodb.com/blog/channel/engineering-blog), Studio 3T Blog (https://studio3t.com/blog/)

────────────────────────────────────────────────────────
<-- back to posts