Working with Capped Collections

1. Creating Capped Collection

ParameterDescription
cappedMust be true
sizeMax bytes (rounded up to 256 multiple)
maxMax document count (optional)
db.createCollection("logs", { capped: true, size: 5_000_000, max: 10_000 });

2. Setting Maximum Size

AspectDetail
UnitsBytes
Minimum4096 bytes
RoundingUp to nearest 256-byte boundary
Resizedb.runCommand({collMod: "logs", cappedSize: 8_000_000}) (6.0+)

3. Setting Maximum Document Count

AspectDetail
Optionmax at creation
ResizecollMod: { cappedMax: 50_000 } (6.0+)
PrecedenceWhichever limit (size OR max) is reached first triggers eviction

4. Understanding FIFO Behavior

BehaviorDetail
OrderInsertion order preserved on disk
EvictionOldest documents removed first when full
Natural sortfind().sort({$natural: 1}) = insertion order
Reverse naturalsort({$natural: -1}) = newest first

5. Using Tailable Cursors with Capped Collections

Cursor OptionEffect
tailable: trueCursor stays open after reaching end
awaitData: trueBlock briefly for new docs (with tailable)
noCursorTimeoutPrevent 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

CommandNotes
db.runCommand({convertToCapped: "logs", size: 1_000_000})Blocks; drops indexes (except _id)
Pre-7.0Use cloneCollectionAsCapped to a new name

7. Understanding Capped Collection Limitations

LimitationDetail
No shardingCannot shard a capped collection
Update sizeUpdates that grow doc size fail (pre-4.2 worse)
No deleteManyCannot manually delete documents
No TTL indexCapped+TTL not supported

8. Using Capped Collections for Logging

Use CaseWhy Capped Fits
Application logsBounded disk, automatic rotation
Audit trail (short retention)FIFO trimming
Real-time event tailTailable cursor pattern
Cache of latest N eventsO(1) eviction

9. Querying Capped Collections

OperationBehavior
find()Returns in insertion order by default
sort({$natural: -1})Newest first
IndexesSupported but only _id by default

10. Monitoring Capped Collection Size

FieldFromDescription
cappeddb.coll.stats()true
maxSizestatsConfigured max bytes
sizestatsCurrent used bytes
countstatsCurrent doc count
maxstatsMax doc count