如何查询和更新嵌套数组

时间:2014-08-28 12:12:37

标签: mongodb

我正在建立一个课程系统。每门课程都有多个部分,每个部分都有多个步骤。我的数据结构如下:

{
    "_id" : "Mtz4DMTwMMKWTWbzE",
    "slug" : "how-to-be-awesome",
    "title" : "How to be awesome",
    "description" : "In 4 easy lessons.",
    "createdAt" : ISODate("2014-08-25T13:33:24.675Z"),
    "sections" : [ 
        {
            "title" : "Be cool",
            "description" : "Title says it all really",
            "steps" : [ 
                {
                    "title" : "Wear sunglasses",
                    "description" : "Always works."
                }, 
                {
                    "title" : "Be funny",
                    "description" : "Make an occasional joke. But no lame ones."
                }
            ]
        }
    ]
}

这在添加步骤时起作用;

Course._collection.update( { _id: course._id, sections: section }, {
    "$push": {
        "sections.$.steps": step
    }
})

但我无法弄清楚如何更新步骤。我尝试为这些步骤提供ID并按照这样做,但它不起作用apparently because it's two arrays deep,并且您在查询中不能有两个位置($)。我试过这样的事情:

Course._collection.update( { _id: course._id, 'sections.steps._id': step._id }, {
    "$set": {
        "sections.steps.$.title": "test updated title"
    }
})

但是这给出了以下错误:

  

无法使用字符串字段名称附加到数组:步骤

有办法做到这一点吗?或者我的架构设计是否已关闭?

谢谢!

0 个答案:

没有答案