使用mongoose在MongoDB中进行批量插入

17

我目前在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个回答

38

如果您使用的是最新的Mongoose版本4.4.X及更高版本,那么您可能希望在这里使用insertMany()方法,它在内部使用Model.collection.insertMany(),驱动程序可能会为您并行处理>= 1000个文档。

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

或者使用 Promise 来更好地处理错误

Collection1.insertMany(myData)
    .then(function(docs) {
         // do something with docs
    })
    .catch(function(err) {
        // error handling here
    });
它的工作原理是创建一堆文档,在并行上调用.validate(),然后在每个文档的toObject({ virtuals: false });结果上调用底层驱动程序的insertMany()。 虽然insertMany()不会触发pre-save钩子,但它具有更好的性能,因为它只需进行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
    });
}

嗨,我正在尝试使用bulk mongoose的方法添加大量数据(我有409,584个数据要添加),但我只添加了273,001个数据。你知道为什么吗? - John
你的MongoDB服务器版本是什么? - chridam
我使用的是MongoDB版本3.2.9和mongoose 4.7.2。如果我使用insertMany方法,会出现“FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory”的错误,因此我尝试使用bulk方法。 - John
我们能保留它们创建的顺序吗? - Aseer KT Miqdad

3
您可以将对象数组传递给mongoose模型的create函数。
var Collection1 = mongoose.model('Collection1');

Collection1.create(myData,function(err){
    if(err) ...
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接