首页 文章

使用mongoose在MongoDB中批量插入

提问于
浏览
10

我目前在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);
  }

2 回答

  • 24

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

    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
        });
    }
    
  • 1

    你可以将一组对象传递给mongoose模型创建函数

    var Collection1 = mongoose.model('Collection1');
    
    Collection1.create(myData,function(err){
        if(err) ...
    });
    

相关问题