Hiprup

What are Capped Collections?

Capped collections are fixed-size collections that act like a circular buffer — once full, new inserts overwrite the oldest documents. Insertion order is preserved.

  • Fixed size — defined at creation; size in bytes, optional max document count.

  • High-throughput inserts — very fast; documents stored in insertion order on disk.

  • Auto-aging — oldest documents removed when full; no explicit deletes needed.

  • Common uses — logs, recent events, in-memory queue replacement.

  • Limitations — can't shard, can't shrink, can't delete individual documents.

  • Modern alternativeTTL indexes for time-based expiry; capped collections fit special use cases.

// Create capped collection
db.createCollection('logs', {
  capped: true,
  size: 10485760,  // 10MB max total size
  max: 5000        // 5000 documents max
});

// Insert (oldest auto-deleted when full)
db.logs.insertOne({ level: 'INFO', message: 'User logged in', timestamp: new Date() });

// Check if collection is capped
db.logs.isCapped(); // true

// Tailable cursor (real-time — like tail -f)
const cursor = db.logs.find().tailable();
// Cursor waits for new documents — like watching a live log stream

// Cannot delete from capped collections
// db.logs.deleteOne({}); // Error!
// Can drop the entire collection: db.logs.drop();

Capped collections have fixed size and document count limits. When full, the oldest document is removed to make room for new ones (FIFO).

Tailable cursors stay open and receive new documents in real-time (like Unix tail -f). Cannot delete individual documents — only the entire collection can be dropped.

Capped = fixed-size FIFO (oldest auto-removed). Use for: logs, caching, event streaming. Tailable cursors for real-time reading.

Cannot delete individual docs. Know size and max options. This is a very commonly asked MongoDB feature.

What are Capped Collections? | Hiprup