Update many documents in mongoDB with different values

浪子不回头ぞ 提交于 2020-01-30 04:28:09

问题


I am trying to update two documents in mongoDB, with two different values. I made it with two different callbacks, but is it possible to do it with only one request?

My solution:

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

Sorry if it is a stupid question but I just want to optimize my code!


回答1:


Best to do this update using the bulkWrite API. Consider the following example for the above two documents:

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

The {"ordered": true, "w": 1} ensures that the documents will be updated on the server serially, in the order provided and thus if an error occurs all remaining updates are aborted. The {"w": 1} option determines the write concern with 1 being a request acknowledgement that the write operation has propagated to the standalone mongod or the primary in a replica set.


For MongoDB >= 2.6 and <= 3.0, use the Bulk Opeartions API as follows:

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


来源:https://stackoverflow.com/questions/37023520/update-many-documents-in-mongodb-with-different-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!