【问题标题】:How to make MongoDB update perform faster?如何使 MongoDB 更新执行得更快?
【发布时间】:2020-04-23 10:39:22
【问题描述】:

我正在尝试将超过 20 万条记录导入 mongodb。如果数据库中存在数据,我们应该更新它,否则插入它。所以我可以在 10 到 15 分钟内插入。但是,当我迭代时,更新 200k 条记录需要 2 个多小时。

 For(){
   If(some validation){
     Var res = await getdatamongo();
      If(res.length > 1){

          Var ress = update(model,query,set)

     }
     Else{
         Insertdata.push(res1)

     }
   }
   }

 Bulkinstmongo(model,Insertdata);

如何让更新更快。

【问题讨论】:

标签: node.js mongodb


【解决方案1】:

这里可以提供帮助的是: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");
}

【讨论】:

    【解决方案2】:

    如果getdatamongo() 正在对数据库进行查询,请确保该查询已正确编入索引。否则随着数据集的增长,您的查询性能将会下降。

    【讨论】:

      猜你喜欢
      • 2016-09-09
      • 2012-01-10
      • 1970-01-01
      • 1970-01-01
      • 2012-03-08
      • 2014-03-20
      • 1970-01-01
      • 2019-11-18
      • 2014-11-28
      相关资源
      最近更新 更多