Update key value where different key equals some value in MongoDB?


Let us create a collection with documents −

> db.demo196.insertOne(
...   {
...
...      "Id" : "101",
...      "details" : [
...         {
...            "FirstName" : "Chris",
...            "LastName" : "Brown",
...            "Score" : 45
...         },
...         {
...            "FirstName" : "David",
...            "LastName" : "Miller",
...            "Score" : 87
...         },
...         {
...            "FirstName" : "John",
...            "LastName" : "Doe",
...            "Score" : 56
...         }
...      ]
...   }
...);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e3af6b103d395bdc21346d7")
}

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

>  db.demo196.find();

This will produce the following output −

{
   "_id" : ObjectId("5e3af6b103d395bdc21346d7"), "Id" : "101", "details" : [
      { "FirstName" : "Chris", "LastName" : "Brown", "Score" : 45 },
      { "FirstName" : "David", "LastName" : "Miller", "Score" : 87 },
      { "FirstName" : "John", "LastName" : "Doe", "Score" : 56 }
   ]
}

Following is the query to update key value where different key equals some value −

> db.demo196.update({"details":{"$elemMatch":{"FirstName" : "David", "LastName" : "Miller"}}},
...                      {"$set":{"details.$.Score":98}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo196.find();

This will produce the following output −

{
   "_id" : ObjectId("5e3af6b103d395bdc21346d7"), "Id" : "101", "details" : [
      { "FirstName" : "Chris", "LastName" : "Brown", "Score" : 45 },
      { "FirstName" : "David", "LastName" : "Miller", "Score" : 98 },
      { "FirstName" : "John", "LastName" : "Doe", "Score" : 56 }
   ]
}

Updated on: 27-Mar-2020

391 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements