用不同的值更新mongoDB中的许多文档 [英] Update many documents in mongoDB with different values

查看:71
本文介绍了用不同的值更新mongoDB中的许多文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用两个不同的值更新mongoDB中的两个文档.我通过两个不同的回调实现了此功能,但是仅用一个请求就可以做到吗?

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?

我的解决方案:

 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!

推荐答案

最好使用

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

{"ordered": true, "w": 1}确保按提供的顺序在服务器上依次更新文档,因此,如果发生错误,则所有其他更新都将中止. {"w": 1}选项确定写关注点为1,即请求确认写操作已传播到独立mongod或副本集中的主对象.

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.

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

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

这篇关于用不同的值更新mongoDB中的许多文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆