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版本
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 }); |
它的工作方式是创建一堆文档,并行调用它们,然后在每个文档的
尽管
对于支持MongoDB Server
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) ... }); |