Update Arrays Element in MongoDB: Updating single element in Array data type in MongoDB using the shell.

I have 2 documents in MongoDB like below

/* 1 */
{
  "_id" : ObjectId("5b594b462fe5553ce8071c27"),
  "grades" : [100, 200, 300]
}

/* 2 */
{
  "_id" : ObjectId("5b594b712fe5553ce8071c28"),
  "grades" : [400, 500, 100]
}

 

now I want to update the grades value of 100 to 1000. Below is the Query for updating a single element in Array.

db.dummy_collection.update(
   { "grades": 100 },
   { $set: { "grades.$" : 1000 }   },
   {
     multi: true
   }
);

 

In the above Query, dummy_collection is the Collection name and it will replace 100 to 1000  from all documents in Collection

if we want to Update element in a nested array

 

/* 1 */ 
{ "_id" : ObjectId("5b594b462fe5553ce8071c27"), 
"allGrades" : { "grade" : [90,75, 60 ] }
},
 /* 2 */
 { "_id" : ObjectId("5b594b712fe5553ce8071c28"),
 "allGrades" : { "grade" : [95,75, 90 ] }
 }

Now I want to update the 75 in grade array below will be the query

 

db.dummy_collection.update(
   { "allGrades.grade": 75},
   { $set: { "allGrades.grade.$" : 80 }   },
   {
     multi: true
   }
);

In the above Query, by using dotted Notation  we are mentioning the MongoDB to update the array which is under allGrades where grade array value is 75 to 80

Also Read: How to Rename/Modify JSON field keys in Mongo Document

Update Arrays Element in MongoDB

Leave a Reply

Your email address will not be published. Required fields are marked *