使用不同的值更新mongoDB中的许多文档

cho*_*hou 9 mongodb nosql node.js mongodb-query

我试图更新mongoDB中的两个文件,具有两个不同的值.我用两个不同的回调制作它,但是只用一个请求就可以做到吗?

我的解决方案

 mongo.financeCollection.update(
    { 'reference': 10 },
    { $push:    
        { history: history1 }
    }, function (err){
        if (err){
            callback (err);
        }
        else {
            mongo.financeCollection.update(
                { 'reference': 20 },
                { $push:
                    { history: history2 }
                }, function (err){
                    if (err){
                        callback(err);
                    }
                    else {
                        callback(null);
                    }     
            });
       }
  });
Run Code Online (Sandbox Code Playgroud)

对不起,如果这是一个愚蠢的问题,但我只想优化我的代码!

chr*_*dam 9

最好使用bulkWriteAPI 进行此更新。考虑上述两个文档的以下示例:

var bulkUpdateOps = [
    {
        "updateOne": {
            "filter": { "reference": 10 },
            "update": { "$push": { "history": history1 } }
        }
    },
    {
        "updateOne": {
            "filter": { "reference": 20 },
            "update": { "$push": { "history": history2 } }
        }
    }
];

mongo.financeCollection.bulkWrite(bulkUpdateOps, 
    {"ordered": true, "w": 1}, function(err, result) {
        // do something with result
        callback(err); 
    }
Run Code Online (Sandbox Code Playgroud)

{"ordered": true, "w": 1}提供的文件将在服务器上连续更新保证,在订单,因此如果发生错误,所有剩余的更新中止。该{"w": 1}选项确定写关注点为1,即请求确认写操作已传播到独立mongod或副本集中的主对象。


对于MongoDB >= 2.6<= 3.0,请使用Bulk Opeartions API,如下所示:

var bulkUpdateOps = mongo.financeCollection.initializeOrderedBulkOp();
bulkUpdateOps
    .find({ "reference": 10 })
    .updateOne({
        "$push": { "history": history1 }
    });
bulkUpdateOps
    .find({ "reference": 20 })
    .updateOne({
        "$push": { "history": history2 }
    });

bulk.execute(function(err, result){
    bulkUpdateOps = mongo.financeCollection.initializeOrderedBulkOp();
    // do something with result
    callback(err);
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,`bulkWrite()`仅适用于MongoDB版本`&gt; = 3.2`,我已经用较早版本的替代方法更新了答案。 (2认同)