推入深层嵌套数组

时间:2014-12-30 17:40:37

标签: arrays mongodb

我正在试图弄清楚如何将新项目推送到mongodb中的深层嵌套数组中。 以此结构为例:

{
    name : "high school",
    departments : [
    {
        name : "math",
        courses : [
        {
            name : "algebra",
            lessons: [
            {
                name: "algebra 1a",
                students: [
                {
                    name: "Dave",
                    id : "123456"
                },
                {
                    name: "alex",
                    id: "987654"
                }
                ]

            }
            ]
        }
        ]
    }
    ]
}

我知道在推入嵌套数组时我应该使用$,如下所示:

  

db.schools.update({ “departments.name”: “数学”},{$推:{ “部门$课程。”:X}})

但是当尝试访问更深的数组时,它会抛出错误。 如何添加新课程?还是新生?

1 个答案:

答案 0 :(得分:3)

根据我的研究和理解,目前mongodb在单一操作中无法做到这一点。 According to this JIRA ticket, it is desired for an upcoming version of mongodb.

这是一种在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)