Updating

suggest change

For updating collections and documents we can use any of these methods:

Methods


Update()

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. The second argument has no update operator, so it replaces the matching document. It does not merely set status. Use $set to change one field and leave the others. update() without { multi: true } changes one document. The shell returns a WriteResult like this:

{ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }

UpdateOne

The UpdateOne() method modifies ONE document (update parameters)

db.countries.updateOne(
   { country: "Sweden" },
   { $set: { capital: "Stockholm" } }
)

This operation searches the countries collection for a document where country is Sweden and sets capital to Stockholm. The result shape below is the driver's result, not the shell WriteResult:

{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }

UpdateMany

The UpdateMany() method modifies multiple documents (update parameters)

db.food.updateMany(
   { sold: { $lt: 10 } },
   { $set: { sold: 55 } }
)

This operation updates all documents (in a ‘food’ collection) where sold is less than 10 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

ReplaceOne

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" }

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents