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


Use $elemMatch fir this with $set

Let us first create a collection with documents −

> dbkeyValueDemoinsertOne(
   {
      "_id" : new ObjectId(),
      "CustomerDetails" : [
         {
            "Name" : "Chris",
            "Age" :24,
         },
         {
            "Name" : "Robert",
            "Age" :29,
         },
         {
            "Name" : "David",
            "Age" :35,
         }
      ]
   }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cefcf36ef71edecf6a1f6bf")
}

Following is the query to display all documents from a collection with the help of find() method −

> dbkeyValueDemofind()pretty();

Output

{
   "_id" : ObjectId("5cefcf36ef71edecf6a1f6bf"),
   "CustomerDetails" : [
      {
         "Name" : "Chris",
         "Age" : 24
      },
      {
         "Name" : "Robert",
         "Age" : 29
      },
      {
         "Name" : "David",
         "Age" : 35
      }
   ]
}

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

> dbkeyValueDemoupdate(
   {"CustomerDetails":{"$elemMatch":{"Name":"David"}}},
   {"$set":{"CustomerDetails$Age":56}});
   WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }
)

Let us check the document once again −

> dbkeyValueDemofind()pretty();

Output

{
   "_id" : ObjectId("5cefcf36ef71edecf6a1f6bf"),
   "CustomerDetails" : [
      {
         "Name" : "Chris",
         "Age" : 24
      },
      {
         "Name" : "Robert",
         "Age" : 29
      },
      {
         "Name" : "David",
         "Age" : 56
      }
   ]
}
raja
Published on 14-Jun-2019 14:36:33
Advertisements