snippetModerate
How can I update a single field in an array of embedded documents?
Viewed 0 times
canfieldupdatearrayembeddedsinglehowdocuments
Problem
I would like to update a field in an array of embedded documents.
My sample document is:
I'd like to change the value of
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".Solution
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 (
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',
}
}
)Code Snippets
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',
}
}
)Context
StackExchange Database Administrators Q#157149, answer score: 19
Revisions (0)
No revisions yet.