node.js - 从nodejs在mongodb中插入一大堆对象

标签 node.js mongodb bigdata

我需要从 nodejs 在 mongodb 中插入一大堆对象(大约 1.5-2 百万)。如何改进我的插入?

这是我的代码:

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

最佳答案

您可以使用 bulk插入。

批量操作有两种类型:

  1. Ordered bulk operations. These operations execute all the operation in order and error out on the first write error.
  2. Unordered bulk operations. These operations execute all the operations in parallel and aggregates up all the errors. Unordered bulk operations do not guarantee order of execution.

所以你可以这样做:

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();
    });
});

关于node.js - 从nodejs在mongodb中插入一大堆对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23928267/

相关文章:

php - 使用 PHP 将 MySQL 转换为 Mongodb 时出现编码问题

javascript - NodeJS - 使用 mongoose 解析大型集合

algorithm - 如何对大文件进行排序(不适合 RAM)

javascript - 如何测试限速HTTP请求功能?

node.js - JSON.parse 从 JSON 返回 [object]

c++ - 从 Local<String> 计算一行中的 UTF8 字符

mongodb - 从Hive向MongoDB转储数据时出错

java - Spring mongodb查询包含嵌套数组的嵌套数组

hadoop - spark-shell 无法连接到远程主机

javascript - NodeJS 使用 supertest 测试 HTTPS 服务器