Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

push into deeply nested array

Tags:

arrays

mongodb

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?

like image 544
Tzvika Mordoch Avatar asked Jun 19 '26 09:06

Tzvika Mordoch


1 Answers

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)
like image 109
NoOutlet Avatar answered Jun 21 '26 22:06

NoOutlet