将项添加到作为子文档的数组

时间:2015-02-17 12:11:50

标签: mongodb

我在“学科”系列中有这个文件:

{
    "_id" : ObjectId("54db5298a59d60df0018525c"),
    "disciplineId" : 61,
    "title" : "Pipes",
    "mainCategories" : [ 
        {
            "title" : "Shut valves",
            "_id" : ObjectId("54db5298a59d60df0018527a"),
            "subCategories" : [ 
                {                        
                    "_id" : ObjectId("54db5298a59d60df0018527c"),
                    "title" : "Two-part valves",
                    "typeComponents" : []
                }, 
                {
                    "_id" : ObjectId("54db5298a59d60df0018527b"),
                    "title" : "Three-part valves",
                    "typeComponents" : []
                }
       }
   ]

我需要一个将项添加到typeComponents的查询。某种程度上update可能$push。我被卡住了。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

好问题。 MongoDB目前不能在更新中使用两个引用。我不知道如何用你的架构来做...但你真的需要那个架构吗?

如果您知道类别名称,则可以对文档进行建模,如下所示:

db.test.insert({
    "_id" : ObjectId("54db5298a59d60df0018525c"),
    "disciplineId" : 61,
    "title" : "Pipes",
    "mainCategories" : {
        "Shut_valves" : {
            "attribute1": "value1",
            "attribute2": "value2",
            "subCategories" : [ 
                {                        
                    "title" : "Two-part valves",
                    "typeComponents" : []
                }, 
                {
                    "title" : "Three-part valves",
                    "typeComponents" : []
                }
            ]
        }
    }
})

您可以使用以下命令轻松更新typeComponents数组:

db.test.update(
{"mainCategories.Shut_valves.subCategories.title":"Two-part valves"},
{$push:{"mainCategories.Shut_valves.subCategories.$.typeComponents": "hello"}})