How can I update a single field in an array of embedded documents?

The answer from Kalhara is correct if you know the position of the embedded document in your array, however there is an alternative approach that can be used to update the first matching array element without knowing the position.

Assuming you update with a single array in your query criteria, the positional operator ($) can be used to refer to the matching array element:

db.students.update(
    // Match criteria
    {
        first_name: 'AA',
        last_name: 'BB',
        'cours_reussis.name_school': 'EPFC'
    },

    // Update first matching array element using the positional operator ($)
    {
        $set: {
            'cours_reussis.$.name_school': 'ENSA',
        }
    }
)

Try this. It may need small modifications based on your other variables but I think this will work:

db.students.update(
   { first_name: 'AA' },
   { $set:
      {
        "cours_reussis.0.name_school": 'ENSA'
      }
   }
)

cours_reussis is an array. The 0 is the array index.

For your reference: $set

Tags:

Mongodb