MongoDB TTL Indexes and Capped Collections
On this page
Data that should expire on its own
Login sessions, password-reset tokens, rate-limit records, debug logs: data that's useless after a while. Without cleanup, these collections grow forever, slowing backups and wasting disk. A nightly delete job works, until it's forgotten, or its big deletes slow the database. MongoDB has two built-in ways to bound data.
TTL indexes: deleting documents by age
A TTL index is a single-field index on a date field with expireAfterSeconds:
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 1800 }) // 30 minutes after createdAtA background TTL monitor wakes up periodically (every 60 seconds by default, ttlMonitorSleepSecs) and deletes documents whose date plus expireAfterSeconds has passed.
To give each document its own expiry time, set expireAfterSeconds: 0 and store the exact expiry moment:
db.resetTokens.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
db.resetTokens.insertOne({ token: "...", userId: 42, expiresAt: new Date(Date.now() + 15 * 60 * 1000) })What to know
- Not instant. A document can live up to a minute or more past expiry, longer under heavy load. If an expired token must never be accepted, also check
expiresAtin the query:{ token, expiresAt: { $gt: new Date() } }. - The field must be a
Date(or an array of dates; the earliest counts). Documents without the field, or with a string, are never deleted. - Single field only, and not on
_id. - Deletes cost like normal deletes: a TTL index expiring millions of documents at once creates load and replication traffic. Spread expiry times out where you can.
- Change the expiry later with
collMod, without rebuilding the index.
Capped collections: fixed size, oldest out
A capped collection has a fixed maximum size (and optionally a document count). When full, new inserts overwrite the oldest documents, in insertion order:
db.createCollection("recentEvents", { capped: true, size: 100 * 1024 * 1024, max: 100000 })Properties: insertion order is preserved, writes are fast, and tailable cursors can follow new documents as they arrive, like tail -f. Restrictions: you can't delete individual documents, and updates mustn't grow a document.
TTL index vs capped collection vs time series
| Need | Use |
|---|---|
| Delete data after a time span | TTL index |
| Per-document expiry (tokens, invites) | TTL with expireAfterSeconds: 0 |
| Keep "the last N MB" of logs or events | Capped collection |
| Follow new inserts in real time | Change streams (Day 19); capped collection with a tailable cursor for simple cases |
| Time-stamped measurements | Time series collection, which has its own expireAfterSeconds |
Change streams have largely replaced tailable cursors for reacting to new data, and time series collections replaced capped collections for metrics. TTL indexes remain the everyday tool.
Check yourself
Not necessarily. The TTL monitor runs about every 60 seconds and deletion can lag under load; check expiry in queries if it must be exact.
The indexed field isn't a BSON Date in those documents, for example it's stored as a string or a number, and the TTL monitor ignores documents without a date there. Store the field as a real date, and documents will start expiring.
Store the exact moment it should expire in a date field, such as expiresAt, and create a TTL index on it with expireAfterSeconds: 0. Each document then expires at its own time instead of a fixed age after creation.
You can't delete individual documents, and updates can't grow a document. It suits logs and recent-event buffers where the oldest entries should simply fall off.
No. Deletion can lag by a minute or more, so also check the expiry time in your code when a token is used, and treat the TTL index as cleanup.