Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Invoke convertToCapped and convert an existing collection to capped in MongoDB
To convert an existing collection to capped in MongoDB, use the convertToCapped command with runCommand(). A capped collection has a fixed size and automatically removes old documents when the size limit is reached.
Syntax
db.runCommand({
convertToCapped: "collectionName",
size: sizeInBytes
});
Sample Data
Let us create a regular collection with some documents ?
db.demo260.insertMany([
{"Name": "Chris"},
{"Name": "Bob"},
{"Name": "David"}
]);
{
"acknowledged": true,
"insertedIds": [
ObjectId("5e47b1181627c0c63e7dba9b"),
ObjectId("5e47b11c1627c0c63e7dba9c"),
ObjectId("5e47b11f1627c0c63e7dba9d")
]
}
Display Documents Before Conversion
db.demo260.find();
{ "_id": ObjectId("5e47b1181627c0c63e7dba9b"), "Name": "Chris" }
{ "_id": ObjectId("5e47b11c1627c0c63e7dba9c"), "Name": "Bob" }
{ "_id": ObjectId("5e47b11f1627c0c63e7dba9d"), "Name": "David" }
Convert to Capped Collection
Now convert the existing collection to capped with a size of 8345 bytes ?
db.runCommand({
convertToCapped: "demo260",
size: 8345
});
{ "ok": 1 }
Verify Conversion
Check the collection stats to confirm it is now capped ?
db.demo260.stats();
The key fields in the output show the capped status ?
{
"ns": "test.demo260",
"size": 112,
"count": 3,
"avgObjSize": 37,
"storageSize": 16384,
"capped": true,
"max": -1,
"maxSize": 8448,
"ok": 1
}
Key Points
-
capped: trueconfirms the collection is now capped -
maxSizeshows the maximum storage size in bytes -
max: -1indicates no document count limit (only size limit) - The operation preserves all existing data during conversion
Conclusion
Use db.runCommand({convertToCapped: "collectionName", size: bytes}) to convert any existing collection to capped. The converted collection will maintain FIFO behavior and automatically remove old documents when size limits are exceeded.
Advertisements
