3

I know I can't use upsert and the positional operator together, but I am looking for away to append to array if some fields of the object I am inserting do not match some fields in an existing object within the array.

so if I have the existing document below, I would like to check for 'field' field's value and update/replace that subdocument if the fields match, and simply append to the array if they don't.

{
    myArray:[
         {
            field:'xyz'
         }       
    ]
}

Is there a good way to do this in node.js? I'm using the native driver.

4

1 回答 1

5

我认为您不能在单个查询中执行此操作。您可以在本机驱动程序中使用两个单独的查询来完成此操作。第一个查询将尝试更新数组中的字段。如果它没有在数组中找到匹配的文档,它会分派第二个查询以将文档附加到数组中。

db.collection('coll').update({_id: _id, "myArray": {field: "xyz"}}, {"$set": {"myArray.$": {field: "xyzt"}}}, {upsert: true}, function(err, res) {
    if (err && err.code == 16836) { // no document was matched
        db.collection('coll').update({_id: _id}, {"$push": {myArray: {field: "xyzt"}}}, function(err, res) {
            console.log("Inserted document in array");
        }); 
    }
    console.log("Updated document in array");
}); 
于 2013-09-20T20:13:38.610 回答