Problem Statement
What is a key characteristic of capped collections in MongoDB?
Explanation
Capped collections are fixed-size collections that maintain insertion order and automatically overwrite the oldest documents when the size limit is reached. They work like circular buffers, making them ideal for logging, caching, or storing recent data.
Capped collections provide high-throughput insert and retrieval operations because documents are stored in insertion order on disk. However, you cannot delete documents from capped collections, and updates cannot increase document size.
Code Solution
SolutionRead Only
// Create capped collection - max 100MB
db.createCollection("logs", {
capped: true,
size: 100000000 // 100MB in bytes
})
// With max document count
db.createCollection("recentActivity", {
capped: true,
size: 10000000, // 10MB
max: 5000 // Max 5000 documents
})
// Query in insertion order
db.logs.find().sort({ $natural: 1 })
// Query in reverse insertion order
db.logs.find().sort({ $natural: -1 })