Push deeply nested array

I am trying to figure out how I can insert 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 have to use $ when pushing a nested array like:

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?

+3


source to share


1 answer


Based on my research and understanding, it is currently not possible to do this in mongodb in a single operation. According to this JIRA ticket, this is desirable for an upcoming mongodb release.

Here's a tedious way to do what you're trying to do in the shell:



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)

      

+3


source







All Articles