node.js - 用不同的值更新 mongoDB 中的许多文档

标签 node.js mongodb mongodb-query nosql

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

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

最佳答案

最好使用 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 或副本集中主 Node 的请求确认。


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

关于node.js - 用不同的值更新 mongoDB 中的许多文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37023520/

相关文章:

mongodb - 如何将 Golang big.Int 存储到 MongoDB 中

node.js - 在一个 mongoose 查询中从 2 个独立的 Mongo 文档获取信息

mongodb - 通过 mongodb 中的聚合和 $facet 在每个文档中添加一个新字段

mongodb - 根据条件进行分组和计数

javascript - Coinbase API 返回 "product not found"以获得有效的产品 ID

javascript - Sails.lift() 和 Sails.load() 之间的区别

node.js - Autodesk Forge API a-401 错误

Node.js 对端口号的限制

c# - MongoDB C# 2.x 驱动程序 ElemMatch 与字典

MongoDB:如何在嵌套数组中查找特定值,如果找到则仅显示该数组而不是全部?