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
How to update a single field in a capped collection in MongoDB?
To update a single field in a capped collection in MongoDB, use the updateOne() or updateMany() method with the $set operator. Capped collections allow field updates but do not permit operations that would increase document size.
Syntax
db.collection.updateOne(
{ "field": "matchValue" },
{ $set: { "field": "newValue" } }
);
Create Sample Capped Collection
First, create a capped collection with size and document limits ?
db.createCollection("Demo112", { capped : true, size : 14, max : 3 } );
{ "ok" : 1 }
Insert Sample Data
db.demo112.insertMany([
{"Name":"Chris"},
{"Name":"David"},
{"Name":"David"}
]);
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5e2ef47a9fd5fd66da21447e"),
ObjectId("5e2ef47e9fd5fd66da21447f"),
ObjectId("5e2ef4919fd5fd66da214480")
]
}
Display all documents ?
db.demo112.find();
{ "_id" : ObjectId("5e2ef47a9fd5fd66da21447e"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2ef47e9fd5fd66da21447f"), "Name" : "David" }
{ "_id" : ObjectId("5e2ef4919fd5fd66da214480"), "Name" : "David" }
Update Multiple Documents
Update all documents with Name "David" to "Robert" ?
db.demo112.updateMany(
{Name:"David"},
{$set:{Name: "Robert"}}
);
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
Verify the update results ?
db.demo112.find();
{ "_id" : ObjectId("5e2ef47a9fd5fd66da21447e"), "Name" : "Chris" }
{ "_id" : ObjectId("5e2ef47e9fd5fd66da21447f"), "Name" : "Robert" }
{ "_id" : ObjectId("5e2ef4919fd5fd66da214480"), "Name" : "Robert" }
Key Points
- Capped collections support field updates but not operations that increase document size.
- Use
updateOne()for single document updates orupdateMany()for multiple documents. - The
$setoperator modifies field values without changing document structure.
Conclusion
Updating fields in capped collections works like regular collections using $set. The key restriction is that updates cannot increase the document size beyond the original allocation.
Advertisements
