0
0
MongoDBquery~5 mins

Capped collections for fixed-size data in MongoDB

Choose your learning style9 modes available
Introduction
Capped collections keep data in a fixed size. They automatically remove old data when full, like a rolling log.
Storing logs that only need recent entries.
Keeping a fixed number of recent messages in a chat app.
Tracking sensor data where only the latest readings matter.
Caching temporary data that should not grow endlessly.
Syntax
MongoDB
db.createCollection(name, { capped: true, size: maxSizeInBytes, max: maxDocuments })
The 'size' option sets the maximum storage size in bytes.
The optional 'max' limits the number of documents stored.
Examples
Creates a capped collection named 'logs' with a max size of 100,000 bytes.
MongoDB
db.createCollection('logs', { capped: true, size: 100000 })
Creates a capped collection 'messages' with max 50,000 bytes and max 1000 documents.
MongoDB
db.createCollection('messages', { capped: true, size: 50000, max: 1000 })
Sample Program
This creates a capped collection 'recentEvents' with max 5 documents. After inserting 6, the oldest is removed automatically.
MongoDB
db.createCollection('recentEvents', { capped: true, size: 10240, max: 5 })

// Insert 6 documents
for (let i = 1; i <= 6; i++) {
  db.recentEvents.insertOne({ eventNumber: i, description: `Event ${i}` })
}

// Retrieve all documents
printjson(db.recentEvents.find().toArray())
OutputSuccess
Important Notes
Capped collections maintain insertion order and do not allow document deletion or updates that increase size.
They are very fast for inserts and reads because of their fixed size and structure.
Once created, you cannot convert a normal collection to capped; you must create a new capped collection.
Summary
Capped collections store data with a fixed size limit.
Old data is removed automatically when space runs out.
Useful for logs, caches, and recent data storage.