0

我有一个结构如下所示的集合

{ "_id" : "MHBk8q96vpuRYrAdn", 
    "circles" : { 
        "guests" : 3, 
        "properties" : [      
            {       
                "position" : {  "x" : 146, "y" : 70.5207970},  
                "name" : "circle-1" 
            },
            {       
                "position" : {  "x" : 200, "y" : 85},  
                "name" : "circle-2" 
            }  
        ], 
        "tables" : 1 
    } 
}

如果 circles.properties.position 按名称存在,我需要能够更新它的位置,或者如果不存在,则添加一个新条目。例如,更新“circle-1”的位置,因为它存在,但是为“circle-3”添加一个带有名称和位置的新数组项。有可能实现这一目标吗?到目前为止,我只能使用 $push 推送到数组上,并且我搞砸了 $(query) 运算符,但没有成功。谢谢。

4

1 回答 1

2

由于MongoDB 不支持对数组进行更新插入,因此可能会很棘手。您可以尝试以下方法:

var query = {};
new_circle = { "position" : {  "x" : -1, "y" : -1}, "name" : "circle-1" };

db.foo.find(query).forEach(
    function(doc) {

        // Find index of 'circle-1'
        i = doc.circles.properties.map(
            function(el) { if (el.name == 'circle-1') return 1; else return -1;}
        ).indexOf(1);

        // Update if circle-1 in circles-properties 
        if (i != -1) {
            doc.circles.properties[i] = new_circle;
        }

        // If not push new
        else {
            doc.circles.properties.push(new_circle);
        }

        db.foo.save(doc);
    }
)

编辑

如果你不能使用save和选项替换update上面发布的块,这样的东西应该可以解决问题:upsertif-else

if (i != -1) {
    db.foo.update(
        {"_id" : doc._id, "circles.properties.name": "circle-1"},
        {$set: {"circles.properties.$.position": new_circle.position}}
}

else {
    db.foo.update(
        {"_id" : doc._id},
        {$push: {"properties": new_circle }}
    )
}
于 2013-11-03T19:27:18.240 回答