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".
4 Answers 4
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
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',
}
}
)
-
1Thank 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 translatezouhair– zouhair2016年12月05日 13:36:20 +00:00Commented Dec 5, 2016 at 13:36 -
1@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 tonom_ecole
to match your actual data,Stennie– Stennie2016年12月05日 19:28:11 +00:00Commented Dec 5, 2016 at 19:28 -
1this should be marked as the right answerHIRA THAKUR– HIRA THAKUR2018年08月27日 14:11:28 +00:00Commented Aug 27, 2018 at 14:11
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'
}
}
)
You can use this to update the array element with some conditions and without knowing the index:
db.getCollection('profiles').update(
{
'userId':'4360a380-1540-45d9-b902-200f2d346263',
'skills.name':'css'
},
{
$set: {'skills.$.proficiencyLevel': 5}
},
{
multi: true
}
)