Update object at specific Array Index in MongoDB?


To update object at specific array index, use update() in MongoDB. Let us first create a collection with documents −

> db.updateObjectDemo.insertOne(
...   {
...       id : 101,
...       "StudentDetails":
...       [
...          [
...             {
...                "StudentName": "John"
...             },
...             { "StudentName": "Chris" }
...          ],
...          [ { "StudentName": "Carol" },
...          { "StudentName": "David" } ]
...       ]
...   }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ccdcd9b685b30d09a7111e0")
}

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

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

This will produce the following output −

{
   "_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
   "id" : 101,
   "StudentDetails" : [
      [
         {
            "StudentName" : "John"
         },
         {
            "StudentName" : "Chris"
         }
      ],
      [
         {
            "StudentName" : "Carol"
         },
         {
            "StudentName" : "David"
         }
      ]
   ]
}

Following is the query to update object at specific array index in MongoDB −

> db.updateObjectDemo.update({"id":101},{$set:{"StudentDetails.1.1.StudentName":"Mike"}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the object at specific index [1,1]. The value “David” has been updated or not −

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

This will produce the following output −

{
   "_id" : ObjectId("5ccdcd9b685b30d09a7111e0"),
   "id" : 101,
   "StudentDetails" : [
      [
         {
            "StudentName" : "John"
         },
         {
            "StudentName" : "Chris"
         }
      ],
      [
         {
            "StudentName" : "Carol"
         },
         {
            "StudentName" : "Mike"
         }
      ]
   ]
}

Updated on: 30-Jul-2019

464 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements