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 or updateMany() for multiple documents.
  • The $set operator 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.

Updated on: 2026-03-15T01:56:27+05:30

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements