To update partial number of documents, set multi to true. Let us create a collection with documents −
> db.demo312.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce16f8647eb59e56204a") } > db.demo312.insertOne({"FirstName":"Bob"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce19f8647eb59e56204b") } > db.demo312.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce1cf8647eb59e56204c") } > db.demo312.insertOne({"FirstName":"David"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce20f8647eb59e56204d") } > db.demo312.insertOne({"FirstName":"Robert"}); { "acknowledged" : true, "insertedId" : ObjectId("5e50ce22f8647eb59e56204e") }
Display all documents from a collection with the help of find() method −
> db.demo312.find();
This will produce the following output −
{ "_id" : ObjectId("5e50ce16f8647eb59e56204a"), "FirstName" : "Robert" } { "_id" : ObjectId("5e50ce19f8647eb59e56204b"), "FirstName" : "Bob" } { "_id" : ObjectId("5e50ce1cf8647eb59e56204c"), "FirstName" : "Robert" } { "_id" : ObjectId("5e50ce20f8647eb59e56204d"), "FirstName" : "David" } { "_id" : ObjectId("5e50ce22f8647eb59e56204e"), "FirstName" : "Robert" }
Following is the query to update partial number of documents
> db.demo312.update({"FirstName":"Robert"},{$set:{"FirstName":"Sam"}},{multi:true}); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
Display all documents from a collection with the help of find() method −
> db.demo312.find();
This will produce the following output −
{ "_id" : ObjectId("5e50ce16f8647eb59e56204a"), "FirstName" : "Sam" } { "_id" : ObjectId("5e50ce19f8647eb59e56204b"), "FirstName" : "Bob" } { "_id" : ObjectId("5e50ce1cf8647eb59e56204c"), "FirstName" : "Sam" } { "_id" : ObjectId("5e50ce20f8647eb59e56204d"), "FirstName" : "David" } { "_id" : ObjectId("5e50ce22f8647eb59e56204e"), "FirstName" : "Sam" }