How to update a single field in a capped collection in MongoDB?



To update, you need to use update() for the field whose collection is set with capped: true. Let us create a collection with documents −

> db.createCollection("Demo112", { capped : true, size : 14, max : 3 } ); { "ok" : 1 } > db.demo112.insertOne({"Name":"Chris"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e2ef47a9fd5fd66da21447e") } > db.demo112.insertOne({"Name":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e2ef47e9fd5fd66da21447f") } > db.demo112.insertOne({"Name":"David"}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e2ef4919fd5fd66da214480") }

Display all documents from a collection with the help of find() method −

> db.demo112.find();

This will produce the following output −

{ "_id" : ObjectId("5e2ef47a9fd5fd66da21447e"), "Name" : "Chris" } { "_id" : ObjectId("5e2ef47e9fd5fd66da21447f"), "Name" : "David" } { "_id" : ObjectId("5e2ef4919fd5fd66da214480"), "Name" : "David" }

Following is the query to update a single field in a capped collection −

> db.demo112.update( ...    {Name:"David"}, ...    {$set:{Name: "Robert"}}, ...    {multi:true} ... ) WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 })

Display all documents from a collection with the help of find() method −

> db.demo112.find();

This will produce the following output −

{ "_id" : ObjectId("5e2ef47a9fd5fd66da21447e"), "Name" : "Chris" } { "_id" : ObjectId("5e2ef47e9fd5fd66da21447f"), "Name" : "Robert" } { "_id" : ObjectId("5e2ef4919fd5fd66da214480"), "Name" : "Robert" }
Updated on: 2020-03-30T12:01:40+05:30

305 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements