chou
chou

Reputation: 263

Update many documents in mongoDB with different values

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!

Upvotes: 16

Views: 9697

Answers (1)

chridam
chridam

Reputation: 103335

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

Upvotes: 20

Related Questions