我正在尝试弄清楚如何将新项目推送到 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/