我需要从nodejs在mongodb中插入一个大的对象数组(大约150-200万)。我如何改进我的插入?
这是我的代码:
var sizeOfArray = arrayOfObjects.length; //sizeOfArray about 1.5-2 millions
for(var i = 0; i < sizeOfResult; ++i) {
  newKey = {
    field_1: result[i][1],
    field_2: result[i][2],
    field_3: result[i][3]
  };
  collection.insert(newKey, function(err, data) {
    if (err) {
      log.error('Error insert: ' + err);
    }
  });
}发布于 2014-05-29 15:55:48
您可以使用bulk插入。
批量操作有两种类型:
所以你可以这样做:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://myserver:27017/test", function(err, db) {
    // Get the collection
    var col = db.collection('myColl');
    // Initialize the Ordered Batch
    // You can use initializeUnorderedBulkOp to initialize Unordered Batch
    var batch = col.initializeOrderedBulkOp();
    for (var i = 0; i < sizeOfResult; ++i) {
      var newKey = {
          field_1: result[i][1],
          field_2: result[i][2],
          field_3: result[i][3]
      };
      batch.insert(newKey);
    }
    // Execute the operations
    batch.execute(function(err, result) {
      console.dir(err);
      console.dir(result);
      db.close();
    });
});发布于 2020-02-07 06:17:58
对于3.2以上的版本,已经引入了insertMany,它仅在幕后使用bulkWrite进行批量插入。
var sizeOfArray = arrayOfObjects.length;for(var i= 0;i< sizeOfResult;++i) { newKey ={ field_1: resulti,field_2: resulti,field_3: resulti };} collection.insertMany(newKey,{ ordered: false }).then((res) => {console.log(“插入的记录数:”+ res.insertedCount);})
https://stackoverflow.com/questions/23928267
复制相似问题