关于javascript:使用mongoose在MongoDB中批量插入

Bulk insert in MongoDB using mongoose

我目前在Mongodb中有一个集合,说" Collection1"。
我有以下需要插入到MongoDB中的对象数组。我正在使用Mongoose API。现在,我将遍历数组并将每个数组插入mongo。
目前还可以,但是当数据太大时会出现问题。
我需要一种无需重复将数据批量插入MongoDB的方法。
我不确定该怎么做。我在猫鼬中找不到批量选择。

我的下面的代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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文档。

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

或使用Promises进行更好的错误处理

1
2
3
4
5
6
7
Collection1.insertMany(myData)
    .then(function(docs) {
         // do something with docs
    })
    .catch(function(err) {
        // error handling here
    });

它的工作方式是创建一堆文档,并行调用它们,然后在每个文档的toObject({ virtuals: false });结果上调用基础驱动程序的insertMany()
尽管insertMany()不会触发预保存的钩子,但是它具有更好的性能,因为它仅使服务器往返1次,而不是每个文档往返1次。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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
2
3
4
5
var Collection1 = mongoose.model('Collection1');

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