node.js - $addToSet 和更新插入

标签 node.js mongodb upsert

我知道我不能同时使用 upsert 和位置运算符,但如果我插入的对象的某些字段与数组中现有对象的某些字段不匹配,我正在寻找追加到数组的方法。

所以如果我有下面的现有文档,我想检查“字段”字段的值并在字段匹配时更新/替换该子文档,如果不匹配则简单地附加到数组。

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

有没有在 node.js 中执行此操作的好方法?我正在使用 native 驱动程序。

最佳答案

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

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

关于node.js - $addToSet 和更新插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18344376/

相关文章:

javascript - 由于另一个服务注入(inject),服务无法找到依赖项

mongodb - W : Failed to fetch http://repo. mongodb.org/apt/ubuntu/dists/freya/mongodb-org/3.0/multiverse/binary-amd64/Packages 404 Not Found

mongodb - 在 MongoDB 中更新文档时的条件更新插入(插入)

javascript - 如何计算网页上的唯一访问者

angularjs - "Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource."

javascript - 设置 Mongoose 文档的排序顺序

sql-server - SQL Server 中单行 MERGE/upsert 的语法

node.js - Mongoose 中的多文档更新插入

node.js - Passport.js - 将 {user : req. user} 隐式传递给模板?

node.js - 学习 NodeJS 和 MongoDB Docker 组合