【问题标题】:Update many documents in mongoDB with different values用不同的值更新 mongoDB 中的许多文档
【发布时间】:2016-08-29 15:26:00
【问题描述】:

我正在尝试使用两个不同的值更新 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);
                    }     
            });
       }
  });

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

【问题讨论】:

    标签: node.js mongodb mongodb-query nosql


    【解决方案1】:

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

    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 或主节点的请求确认。


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

    【讨论】:

    • 真的非常感谢!但不幸的是 Object # 没有方法 'bulkWrite' ,我使用的是 mongo 3.0.11,这是原因吗?
    • 是的,bulkWrite() 仅适用于 MongoDB 版本>= 3.2,我已经用早期版本的替代方法更新了我的答案。
    • ordered: true 是 mongodb 中的默认行为,所以你可以省略它
    猜你喜欢
    • 2020-11-19
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2020-07-11
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多