5

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".

3

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

12

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',
        }
    }
)
  • 1
    Thank you very much Stennie Unfortunately it does not work. It gives me this message WriteResult({ "nMatched" : 0, "nUpserted" : 0, "nModified" : 0, "writeError" : { "code" : 16837, "errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: cours_reussis.$.nom_ecole" } }) Sorry for my english i use google to translate – zouhair Dec 5 '16 at 13:36
  • @zouhair The WriiteResult indicates that a matching document was not found, so you need to adjust your criteria. My update statement works for your sample document as included in the question description, but you'll have to modify to suit your current data. It looks like perhaps you need to change name_school in the update statement to nom_ecole to match your actual data, – Stennie Dec 5 '16 at 19:28
  • this should be marked as the right answer – HIRA THAKUR Aug 27 '18 at 14:11
0

You can use this to update the first matching array element without knowing the index:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.