MongoDB – Updating a Single Field in an Array of Embedded Documents

mongodb

I would like to update a field in an array of embedded documents.

My sample document is:

db.students.insert(
    {
        first_name:'AA',
        last_name:'BB',
        cours_reussis:[{intitule:'PAI',note:0,name_school:'EPFC'}]
    }
)

I'd like to change the value of name_school to "ENSA" instead of "EPFC".

Best Answer

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