Capped Collections — MongoDB Technical Interview Questions & Answers

Fixed-size collections that overwrite oldest documents.

Capped Collections

  • Simple meaning: A capped collection has a max size. When full, oldest documents are overwritten (like a ring buffer). Good for logs.
  • How to use: db.createCollection("logs", { capped: true, size: 1048576, max: 5000 }). Inserts stay in order.
  • You cannot shard a capped collection. Updates that grow documents can fail.
  • Common mistake: using capped for student records you must not lose.
  • Interview tip: Fixed size, insertion order, logs/cache — not primary student data.

Technical Interview Tip: Capped = ring buffer. Size in bytes.

Code Examples for Capped Collections

Capped Collections — working example

db.createCollection("logs", { capped: true, size: 1048576, max: 5000 })
db.logs.insertOne({ level: "info", msg: "app started", at: new Date() })
db.logs.find().sort({ $natural: -1 }).limit(5)

Capped collections are fixed-size and overwrite oldest documents in insertion order.

How to Explain Capped Collections to an Interviewer

What is a capped collection?

Fixed-size collection that overwrites oldest documents