MongoDB query to update array object in index N?

MongoDBDatabaseBig Data Analytics

Use update() in MongoDB to update array object. The usage of dot notation is also required. Let us create a collection with documents −

> db.demo489.insertOne(
... {
...
...
...    details : [{
...       id : 101,
...       "Info1" : {
...          "StudentName" : "Chris"
...       },
...       "Info2" : {
...          "TeacherName" : "David"
...       }
...    },
...    {
...       id : 102,
...       "Info1" : {
...          "StudentName" : "Carol"
...       },
...       "Info2" : {
...          "TeacherName" : "Mike"
...       }
...    }
...  
... ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e8356e0b0f3fa88e22790ba")
}

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

> db.demo489.find();

This will produce the following output −

{ "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"), "details" : [ { "id" : 101, "Info1" : {
"StudentName" : "Chris" }, "Info2" : { "TeacherName" : "David" } }, { "id" : 102, "Info1" : {
"StudentName" : "Carol" }, "Info2" : { "TeacherName" : "Mike" } } ] }

Following is the query to update array object −

> db.demo489.update({"details.id":102},
...    {$set: {"details.$.Info1.StudentName":"Robert",
...       "details.$.Info2.TeacherName":"John",
...       "details.$.CountryName" : "US"
...
...    }
... })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

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

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

This will produce the following output −

{
   "_id" : ObjectId("5e8356e0b0f3fa88e22790ba"),
   "details" : [
      {
         "id" : 101,
         "Info1" : {
            "StudentName" : "Chris"
         },
         "Info2" : {
            "TeacherName" : "David"
         }
      },
      {
         "id" : 102,
         "Info1" : {
            "StudentName" : "Robert"
         },
         "Info2" : {
            "TeacherName" : "John"
         },
         "CountryName" : "US"
      }
   ]
}
raja
Published on 11-May-2020 10:03:38
Advertisements