我有一个包含对象的数组,对于每个对象,我需要查找是否存在某个键,然后它应该更新或插入。我已经通过 for 循环完成了此操作,但问题是我有大约 20L 的数据,需要每天早上使用 cron 调度程序运行。
我的问题是:我可以使用其他方式,例如将此数组传递给方法以获得更好的性能吗?
我的方法:
const arr = [{id: 1, pre: 10, post: 15 , name: 'egg'},{id: 2, pre: 10, post: 15 , name: 'egg 2'},{id: 3, pre: 10, post: 15 , name: 'egg 3'},{id: 4, pre: 10, post: 15 , name: 'egg 4'}]
for(x = 0; x < arr.length ; x++) {
await processed_.findByIdAndUpdate({id: arr[x].id}, { $set: arr[x] }, {upsert: true, new: true})
}
感谢您的建议。
bulkWrite
来提高代码的性能。 bulkWrite
允许您在单个请求中发送多个更新或插入操作,从而减少发送到数据库的请求数量。示例代码看起来像(未经测试的代码,但你明白了):
const arr = [
{id: 1, pre: 10, post: 15, name: 'egg'},
{id: 2, pre: 10, post: 15, name: 'egg 2'},
{id: 3, pre: 10, post: 15, name: 'egg 3'},
{id: 4, pre: 10, post: 15, name: 'egg 4'},
// ... others
];
const bulkOps = arr.map(doc => ({
updateOne: {
filter: {id: doc.id},
update: {$set: doc},
upsert: true
}
}));
await processed_.bulkWrite(bulkOps);
注意(来自您可能想查看的文档):
每组的操作数量不能超过数据库的maxWriteBatchSize的值。 maxWriteBatchSize 的默认值为 100,000。该值显示在 hello.maxWriteBatchSize 字段中。