Answers for "mongodb find and update array item by id"

10

mongodb update field inside array

Consider the following document in the students collection whose grades element value is an array of embedded documents:

{
  _id: 4,
  grades: [
     { grade: 80, mean: 75, std: 8 },
     { grade: 85, mean: 90, std: 5 },
     { grade: 85, mean: 85, std: 8 }
  ]
}

Use the positional $ operator to update the std field of the first array element that matches the grade equal to 85 condition:

IMPORTANT
---------
You must include the array field as part of the query document.

db.students.updateOne(
   { _id: 4, "grades.grade": 85 },
   { $set: { "grades.$.std" : 6 } }
)
After the operation, the document has the following updated values:

{
   "_id" : 4,
   "grades" : [
      { "grade" : 80, "mean" : 75, "std" : 8 },
      { "grade" : 85, "mean" : 90, "std" : 6 },
      { "grade" : 85, "mean" : 85, "std" : 8 }
   ]
}
Posted by: Guest on December-15-2020
1

mongodb find and update array item by id

db.myCollection.update({"_id" : 1, "lb.id" : 2},{$set : {"lb.$.sc" : 17}})
Posted by: Guest on May-28-2021

Browse Popular Code Answers by Language