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