For updating collections and documents we can use any of these methods:
The update() method modifies one or many documents (update parameters)
db.lights.update(
{ room: "Bedroom" },
{ status: "On" }
)
This operation searches the 'lights' collection for a document where room
is Bedroom (1st parameter). It then updates the matching documents status
property to On (2nd parameter) and returns a WriteResult object that looks like this:
{ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }
The UpdateOne() method modifies ONE document (update parameters)
db.countries.update(
{ country: "Sweden" },
{ capital: "Stockholm" }
)
This operation searches the 'countries' collection for a document where country
is Sweden (1st parameter). It then updates the matching documents property capital
to Stockholm (2nd parameter) and returns a WriteResult object that looks like this:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
The UpdateMany() method modifies multible documents (update parameters)
db.food.updateMany(
{ sold: { $lt: 10 } },
{ $set: { sold: 55 } }
)
This operation updates all documents (in a 'food' collection) where sold
is lesser than 10 *(1st parameter) by setting sold
to 55. It then returns a WriteResult object that looks like this:
{ "acknowledged" : true, "matchedCount" : a, "modifiedCount" : b }
a = Number of matched documents
b = Number of modified documents
Replaces the first matching document (replacement document)
This example collection called countries contains 3 documents:
{ "_id" : 1, "country" : "Sweden" }
{ "_id" : 2, "country" : "Norway" }
{ "_id" : 3, "country" : "Spain" }
The following operation replaces the document { country: "Spain" }
with document { country: "Finland" }
db.countries.replaceOne(
{ country: "Spain" },
{ country: "Finland" }
)
And returns:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
The example collection countries now contains:
{ "_id" : 1, "country" : "Sweden" }
{ "_id" : 2, "country" : "Norway" }
{ "_id" : 3, "country" : "Finland" }