Working with Capped Collections
1. Creating Capped Collection
| Parameter | Description |
|---|---|
| capped | Must be true |
| size | Max bytes (rounded up to 256 multiple) |
| max | Max document count (optional) |
db.createCollection("logs", { capped: true, size: 5_000_000, max: 10_000 });
2. Setting Maximum Size
| Aspect | Detail |
|---|---|
| Units | Bytes |
| Minimum | 4096 bytes |
| Rounding | Up to nearest 256-byte boundary |
| Resize | db.runCommand({collMod: "logs", cappedSize: 8_000_000}) (6.0+) |
3. Setting Maximum Document Count
| Aspect | Detail |
|---|---|
| Option | max at creation |
| Resize | collMod: { cappedMax: 50_000 } (6.0+) |
| Precedence | Whichever limit (size OR max) is reached first triggers eviction |
4. Understanding FIFO Behavior
| Behavior | Detail |
|---|---|
| Order | Insertion order preserved on disk |
| Eviction | Oldest documents removed first when full |
| Natural sort | find().sort({$natural: 1}) = insertion order |
| Reverse natural | sort({$natural: -1}) = newest first |
5. Using Tailable Cursors with Capped Collections
| Cursor Option | Effect |
|---|---|
| tailable: true | Cursor stays open after reaching end |
| awaitData: true | Block briefly for new docs (with tailable) |
| noCursorTimeout | Prevent server-side idle timeout |
const cursor = db.logs.find().addOption(DBQuery.Option.tailable).addOption(DBQuery.Option.awaitData);
while (cursor.hasNext()) printjson(cursor.next());
6. Converting Regular to Capped
| Command | Notes |
|---|---|
db.runCommand({convertToCapped: "logs", size: 1_000_000}) | Blocks; drops indexes (except _id) |
| Pre-7.0 | Use cloneCollectionAsCapped to a new name |
7. Understanding Capped Collection Limitations
| Limitation | Detail |
|---|---|
| No sharding | Cannot shard a capped collection |
| Update size | Updates that grow doc size fail (pre-4.2 worse) |
| No deleteMany | Cannot manually delete documents |
| No TTL index | Capped+TTL not supported |
8. Using Capped Collections for Logging
| Use Case | Why Capped Fits |
|---|---|
| Application logs | Bounded disk, automatic rotation |
| Audit trail (short retention) | FIFO trimming |
| Real-time event tail | Tailable cursor pattern |
| Cache of latest N events | O(1) eviction |
9. Querying Capped Collections
| Operation | Behavior |
|---|---|
| find() | Returns in insertion order by default |
| sort({$natural: -1}) | Newest first |
| Indexes | Supported but only _id by default |
10. Monitoring Capped Collection Size
| Field | From | Description |
|---|---|---|
| capped | db.coll.stats() | true |
| maxSize | stats | Configured max bytes |
| size | stats | Current used bytes |
| count | stats | Current doc count |
| max | stats | Max doc count |