更新/插入mongoDB文档的嵌套字符串化数组中的元素

时间:2015-11-02 19:19:44

标签: json mongodb meteor

我的收藏品有这样的结构:

{
    "_id" : "7ZEc8dkbs4tLwhW24",
    "title" : "title",
    "json" :

        {
            \"cells\":[
                {
                    \"type\":\"model\",
                    \"size\":{\"width\":100,\"height\":40},
                    \"id\":\"11dc3b6f-2f61-473c-90d7-08f16e7d277a\",
                    \"attrs\":{
                        \"text\":{\"text\":\"content\"},
                        \"a\":{\"xlink:href\":\"http://website.com\",\"xlink:show\":\"replace\",\"cursor\":\"pointer\"}
                    }
                }
            ]
        }
}

现在我需要在我的meteor应用程序中插入/更新字段json.cells.attrs.a。我得到的所有信息都是_id(文档ID)和id(单元格中元素的id)。如果a不存在,则应创建该元素。

我的尝试不正确,因为查询没有查找elemID来获取cells-array中的正确元素:

var linkObject = {"xlink:href":"http://newURL.com","xlink:show":"replace","cursor":"pointer"};
var docID = '7ZEc8dkbs4tLwhW24';
var elemID = '11dc3b6f-2f61-473c-90d7-08f16e7d277a'; // How to search for this 'id'?

var result = Collection.findOne({ _id: docID });
var json = JSON.parse(result.json);

// find id = elemID in 'json'
// add/update 'a'

// update json in mongoDB document

1 个答案:

答案 0 :(得分:1)

在您的代码中,您只是在查询中添加docID条件。您必须将elemID添加到查询条件中。然后,您可以使用dot.notation$(Positional Operator)来更新a对象的attrs属性。你可以这样做:

Collection.update(
    {"_id" : docID , "json.cells.id" : elemID },
    {$set: { "json.cells.$.attrs.a" : linkObject}}
}
如果字段不存在,

$set将创建字段。如果您不知道阵列位置,可以使用$ Positional Operator

相关问题