arrays - 插入深层嵌套数组

标签 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":"math"},{$push:{"departments.$.courses":x}})

但是当试图访问更深的数组时它会抛出一个错误。 如何添加新类(class)?还是新生?

最佳答案

根据我的研究和理解,目前无法在 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)

关于arrays - 插入深层嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27709993/

相关文章:

php - 使用 Kartik FileInput 小部件保存多个图像文件

php - 如何根据编号设置我的行跨度值。查询中的结果并根据其集合 ID 更改值(如果它是组或集合)?

ruby - 确定给定的 IP 地址是否在网络数组中

ruby-on-rails - 使用 Mongoid 查询语法与 Activerecord

node.js - Mongoose 可选的搜索查询参数?

mongodb - 使用 mongoose 在 mLab 上进行全文搜索 : MongoError: text index required for $text query

c - C 中二维数组的错误初始化

python - 垂直连接两个 NumPy 数组

java - 根据奇怪的协议(protocol)将整数放入字节数组

javascript - MongoDB:尚未为模型 "User"注册架构