I'm trying to figure out how can I push a new item into a deeply nested array in mongodb. Take this structure for example:
{
name : "high school",
departments : [
{
name : "math",
courses : [
{
name : "algebra",
lessons: [
{
name: "algebra 1a",
students: [
{
name: "Dave",
id : "123456"
},
{
name: "alex",
id: "987654"
}
]
}
]
}
]
}
]
}
I know that I should use $ when pushing into a nested array, like this:
db.schools.update({"departments.name":"math"},{$push:{"departments.$.courses":x}})
But when trying to access a deeper array it throws an error. How can I add a new lesson? or a new student?
Based on my research and understanding, this is not currently possible to do within mongodb in a single operation. According to this JIRA ticket, it is desired for an upcoming version of mongodb.
Here is a tedious way of doing in the shell what you are attempting to accomplish:
var school = db.schools.findOne({name: "high school"}) //assuming unique
school.departments.forEach(function(department) {
if(department.name === "math") {
department.courses.forEach(function(course) {
if(course.name === "algebra") {
course.lessons.forEach(function(lesson) {
if(lesson.name === "algebra 1a") {
lesson.students.push({name: "Jon", id: "43953"});
}
});
}
});
}
})
db.schools.save(school)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With