将新元素添加到Mongo Document

时间:2013-12-10 11:31:51

标签: mongodb

我想插入数组元素,其中Title是'Cities',但它不会插入或插入新数组而不是Links.Link。任何想法我做错了什么。我尝试过push和$ addToSet

{
    "Component" : [
        {
            "Title" : "regions",
            "Links" : {
                "Link" : [

                    {
                        "Text" : "Tyrol",
                        "Url" : "/1xf-en700p/cheap-holidays-tyrol",
                        "Title" : "Cheap holidays Tyrol"
                    },
                    {
                        "Text" : "Browse Regions ",
                        "Url" : "/1xf-en6ujz-10ts/cheap-holidays-austria/regions",
                        "Title" : "Cheap holidays Austria",
                        "Style" : "BrowseForMore"
                    }
                ]
            }
        },
        {

            "Title" : "cities",
            "Links" : {
                "Link" : [
                    {
                        "Text" : "Maria Saal",
                        "Url" : "/1xf-enu4dl/cheap-holidays-maria-saal",
                        "Title" : "Cheap holidays Maria Saal"
                    },
                    {
                        "Text" : "Nessendorf",
                        "Url" : "/1xf-enwvu8/cheap-holidays-nessendorf",
                        "Title" : "Cheap holidays Nessendorf"
                    },

                ]
            }
        },

    ],
    "Id" : "125570",

}

with 

var pd = { Text: 'test',Url: 'test',Title: 'test' };
db.PopularDestinationsUk.update
( 
    {
         Id: '125570'
        ,'Component.Title': 'cities'}

    }
    ,
    { 
        $push: 
        {
            'Component.Link.$.Links { Text: 'NEW',Url: 'NEW',Title: 'NEW' }}}
        }
    }
)

但它没有插入正确的地方

1 个答案:

答案 0 :(得分:1)

按如下方式更新您的查询:

db.PopularDestinationsUk.update({Id: "125570", "Component.Title" : "cities"}, {$push : {"Component.$.Links.Link" : {Text: 'NEW',Url: 'NEW',Title: 'NEW'}}})