Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

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: 2019-07-30T22:30:26+05:30

594 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements