How to find and modify a value in a nested array?

MongoDBDatabaseBig Data Analytics

To find and modify a value in a nested array, you can use update command. Let us first create a collection with documents

> db.findAndModifyAValueInNestedArrayDemo.insertOne( { "CompanyName" :
"Amazon", "DeveloperDetails" : [ { "ProjectName" : "Online Book
Store", "TeamSize" : "5" }, { "ProjectName" : "Library
Management System", "TeamSize" : "7" }, { "ProjectName" :
"Online Banking Application", "TeamSize" : "15" } ] } );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5ca275226304881c5ce84b9f")
}

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

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

This will produce the following output

{
   "_id" : ObjectId("5ca275226304881c5ce84b9f"),
   "CompanyName" : "Amazon",
   "DeveloperDetails" : [
      {
         "ProjectName" : "Online Book Store",
         "TeamSize" : "5"
      },
      {
         "ProjectName" : "Library Management System",
         "TeamSize" : "7"
      },
      {
         "ProjectName" : "Online Banking Application",
         "TeamSize" : "15"
      }
   ]
}

Following is the query to find and modify a value in a nested array. We are modifying the TeamSize to 20 for ProjectName: "Online Banking Application"

> db.findAndModifyAValueInNestedArrayDemo.update( { DeveloperDetails: { $elemMatch: {
ProjectName: "Online Banking Application" } } }, { $set: { 'DeveloperDetails.$.TeamSize':
'20' } } );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Let us check the document is modified with value 20 or not

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

This will produce the following output

{
   "_id" : ObjectId("5ca275226304881c5ce84b9f"),
   "CompanyName" : "Amazon",
   "DeveloperDetails" : [
      {
         "ProjectName" : "Online Book Store",
         "TeamSize" : "5"
      },
      {
         "ProjectName" : "Library Management System",
         "TeamSize" : "7"
      },
      {
         "ProjectName" : "Online Banking Application",
         "TeamSize" : "20"
      }
   ]
}
raja
Published on 12-Apr-2019 10:52:54
Advertisements