首页 文章

如果项不存在,则更新数组中的条目或添加到数组[重复]

提问于
浏览
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来推送数组,而且我已经弄乱了$(查询)运算符但没有成功 . 谢谢 .

1 回答

  • 2

    MongoDB doesn't support upserts to arrays以来,这可能很棘手 . 您可以尝试以下内容:

    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);
        }
    )
    

    Edit

    如果你不能使用 saveupdateupsert 选项替换上面发布的 if-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 }}
        )
    }
    

相关问题