3

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?

1 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.