这里可以提供帮助的是:BulkWriteNodeJS driver Documentation,它为客户端提供了批量执行写入操作的能力。如果操作顺序无关紧要,可以提供选项{ordered:false} 以进一步提高性能。
例子:
const col = db.collection("collection_name");
let bulkWriteOps = [];
for (let i = 0, l = res.length; i < l; ++i) {
const updateOp = {
updateOne: { filter: { a: 2 }, update: { $set: { a: 5 } }, upsert: true },
};
bulkWriteOps.push(updateOp);
}
const result = await col.bulkWrite(bulkWriteOps, { ordered: false });
如果更新或写入操作的大小非常大,要在 javascript (Nodejs) 中采用更多面向性能的方法是使用分块和承诺。
我们的想法是按照定义的大小对操作进行分块,并在它们到达时立即将它们发送到 mongodb。并且由于 BulkWite 操作返回一个承诺,Promise.all(..) 可用于达到一切都已完成的阶段。
例子:
const col = db.collection("collection_name");
let bulkWriteOps = [];
let promises = [];
for (let i = 0, l = res.length; i < l; ++i) {
const updateOp = {
updateOne: { filter: { a: 2 }, update: { $set: { a: 5 } }, upsert: true },
};
bulkWriteOps.push(updateOp);
/*chunking the operations into 10000 and sending them to mongodb*/
if (bulkWriteOps.length === 10000) {
const p = collection.bulkWrite(bulkWriteOps,{ ordered: false });
promises.push(p);
bulkWriteOps = [];
}
}
/*sending the rest of left operations to mongodb*/
if (bulkWriteOps.length > 0) {
const p = col.bulkWrite(bulkWriteOps,{ ordered: false });
promises.push(p);
}
/*NOTE: Promise.all rejects if any of the promise by mongodb query rejects*/
try {
await Promise.all(promises);
/*everything finished*/
} catch (error) {
console.error("one or more of the mongodb query operations rejected");
}