mongodb – CRUD Operation – Update of embedded documents.

For the following schema:

{name: 'Tom', age: 28, marks: [50, 60, 70]}

Update Tom’s marks to 55 where marks are 50 (Use the positional operator $):

db.people.update({name: "Tom", marks: 50}, {"$set": {"marks.$": 55}})

For the following schema:

{name: 'Tom', age: 28, marks: [{subject: "English", marks: 90},{subject: "Maths", marks: 100}, {subject: "Computes", marks: 20}]}

Update Tom’s English marks to 85 :

db.people.update({name: "Tom", "marks.subject": "English"},{"$set":{"marks.$.marks": 85}})

Explaining above example:

By using {name: "Tom", "marks.subject": "English"} you will get the position of the object in the marks array, where subject is English. In "marks.$.marks", $ is used to update in that position of the marks array

Update Values in an Array

The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.

Consider a collection students with the following documents:

{ "_id" : 1, "grades" : [ 80, 85, 90 ] }
{ "_id" : 2, "grades" : [ 88, 90, 92 ] }
{ "_id" : 3, "grades" : [ 85, 100, 90 ] }

To update 80 to 82 in the grades array in the first document, use the positional $ operator if you do not know the position of the element in the array:

db.students.update(
   { _id: 1, grades: 80 },
   { $set: { "grades.$" : 82 } }
)

if you want to reproduce, please indicate the source:
mongodb – CRUD Operation – Update of embedded documents. - CodeDay