I have a collection of student objects, I have this student document in a MongoDB collection, and want to update a teacher that belongs to one of the courses that this student has. For example I want to update the name of Danny which belongs to the Databases course.
{
"firstName": "John",
"lastName": "Wayne",
"age": 25,
"bbId": "johx0055",
"courses" : [
{
"name" : "Web development",
"teachers" : [
{
"firstName" : "Bob",
"lastName" : "Birch"
}
]
},
{
"name" : "Interface Design",
"teachers" : [
{
"firstName" : "Roxanna",
"lastName" : "Doe"
}
]
},
{
"name" : "Databases",
"teachers" : [
{
"firstName" : "Jack",
"lastName" : "X"
},
{
"firstName" : "Danny",
"lastName" : "Doe"
}
]
}
]
}
I am trying to update this in a nodejs environment. I tried with this query and this was the closest I got to a right solution:
db.collection('students').update({ 'bbId' : johx0055, 'courses.name' : 'Databases', 'courses.teachers.firstName' : 'Danny'}, { $set : { 'courses.$.teachers.0.firstName' : 'X' }}, (err, result) => {
if (err) {
console.log(err);
//console.log({ "status": "error", "type": "001 -> create student", "message": "Error when updating teacher" });
return;
}
console.log({ "status": "OK", "message": "Successfully updated teacher" });
})
But, as the 0 indicated, only updates the first element (Jack) in the teachers array