数据库
首页 > 数据库> > javascript – 使用mongoose在MongoDB中批量插入

javascript – 使用mongoose在MongoDB中批量插入

作者:互联网

我目前在Mongodb有一个集合说“Collection1”.
我有以下需要插入MongoDB的对象数组.我正在使用Mongoose API.现在,我正在迭代数组并将它们中的每一个插入到mongo中.
现在这没问题,但是当数据太大时会出现问题.
我需要一种将数据批量插入MongoDB而无需重复的方法.
我不知道该怎么做.我在Mongoose找不到批量选项.

我的代码如下

myData = [Obj1,Obj2,Obj3.......]

myData.forEach(function(ele){
      //console.log(ele)
     saveToMongo(ele);
    });
function saveToMongo(obj){
    (new Collection1(obj)).save(function (err, response) {
          if (err) {
             // console.log('Error while inserting: ' + obj.name + " " +err);
          } else {
            // console.log('Data successfully inserted');
          }
      });

      return Collection1(obj);
  }

解决方法:

如果你使用最新的Mongoose版本4.4.X和更高版本,你可能想在这里使用insertMany()方法,它本质上使用了Model.collection.insertMany()并且驱动程序可以为你处理并行化> = 1000个文档.

myData = [Obj1, Obj2, Obj3.......];
Collection1.insertMany(myData, function(error, docs) {});

或使用Promises更好地处理错误

Collection1.insertMany(myData)
    .then(function(docs) {
         // do something with docs
    })
    .catch(function(err) {
        // error handling here
    });

它的工作原理是创建一堆文档,并行调用它们的.validate(),然后根据toObject({virtuals:false})的结果调用底层驱动程序的insertMany();每个文件.
虽然insertMany()不触发预保存挂钩,但它具有更好的性能,因为它只对服务器进行1次往返,而不是每个文档1次.

对于支持MongoDB Server> = 2.6.x的Mongoose版本~3.8.8,~3.8.22,4.x,你可以使用Bulk API如下

var bulk = Collection1.collection.initializeOrderedBulkOp(),
    counter = 0;

myData.forEach(function(doc) {
    bulk.insert(doc);

    counter++;
    if (counter % 500 == 0) {
        bulk.execute(function(err, r) {
           // do something with the result
           bulk = Collection1.collection.initializeOrderedBulkOp();
           counter = 0;
        });
    }
});

// Catch any docs in the queue under or over the 500's
if (counter > 0) {
    bulk.execute(function(err,result) {
       // do something with the result here
    });
}

标签:javascript,mongodb,node-js,mongoose,bulkinsert
来源: https://codeday.me/bug/20191001/1839009.html