How to update array of subdocuments in MongoDB?

MongoDBDatabaseBig Data Analytics

To update, use update() along with $set. Let us create a collection with documents −

>db.demo134.insertOne({"EmployeeId":101,"EmployeeDetails":[{"EmployeeName":"Chris","EmployeeAge":27},{"EmployeeName":"Bob","EmployeeAge":28}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e319b2f68e7f832db1a7f7c")
}
>db.demo134.insertOne({"EmployeeId":102,"EmployeeDetails":[{"EmployeeName":"David","EmployeeAge":24},{"EmployeeName":"Carol","EmployeeAge":29}]});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e319b4468e7f832db1a7f7d")
}

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

> db.demo134.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"),
   "EmployeeId" : 101,
   "EmployeeDetails" : [
      {
         "EmployeeName" : "Chris",
         "EmployeeAge" : 27
      },
      {
         "EmployeeName" : "Bob",
         "EmployeeAge" : 28
      }
   ]
}
{
   "_id" : ObjectId("5e319b4468e7f832db1a7f7d"),
   "EmployeeId" : 102,
   "EmployeeDetails" : [
      {
         "EmployeeName" : "David",
         "EmployeeAge" : 24
      },
      {
         "EmployeeName" : "Carol",
         "EmployeeAge" : 29
      }
   ]
}

Following is the query to update array of subdocuments in MongoDB −

> db.demo134.update(
...    {
...       "EmployeeId":101,
...       "EmployeeDetails.EmployeeName":"Chris"
...    },
...    {
...       $set: {
...          "EmployeeDetails.$.EmployeeName" : "Robert"
...       }
...    }
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

> db.demo134.find().pretty();

This will produce the following output −

{
   "_id" : ObjectId("5e319b2f68e7f832db1a7f7c"),
   "EmployeeId" : 101,
   "EmployeeDetails" : [
      {
         "EmployeeName" : "Robert",
         "EmployeeAge" : 27
      },
      {
         "EmployeeName" : "Bob",
         "EmployeeAge" : 28
      }
   ]
}
{
   "_id" : ObjectId("5e319b4468e7f832db1a7f7d"),
   "EmployeeId" : 102,
   "EmployeeDetails" : [
      {
         "EmployeeName" : "David",
         "EmployeeAge" : 24
      },
      {
         "EmployeeName" : "Carol",
         "EmployeeAge" : 29
      }
   ]
}
raja
Published on 31-Mar-2020 12:03:51
Advertisements