我想知道用Node批量插入Mongodb(尽管可以是任何其他数据库)的正确方法是什么.js

我已经编写了以下代码作为示例,尽管我相信它被定义为db.close()可以在所有异步集合之前运行.插入通话已完成.

MongoClient.connect('mongodb://127.0.0.1:27017/test', function (err, db) {
    var i, collection;
    if (err) {
        throw err;
    }
    collection = db.collection('entries');
    for (i = 0; i < entries.length; i++) {
        collection.insert(entries[i].entry);
    }
    db.close();
});

推荐答案

如果您的MongoDB服务器是2.6或更高版本,那么最好使用写入命令100,该命令允许在服务器上执行大容量插入操作,这些操作只是服务器上的抽象操作,以便轻松构建大容量操作,从而在大型集合上通过更新获得性能提升.

成批发送大容量插入操作会减少到服务器的通信量,因此通过不在单个语句中发送所有内容,而是将其分解为可管理的块,以实现服务器promise ,从而执行高效的有线事务.使用这种方法,在回调中等待响应的时间也更少.

这些批量生产主要有两种口味:

  • Ordered bulk operations.这些操作按顺序执行所有操作,并在第一次写入错误时出错.
  • Unordered bulk operations.这些操作并行执行所有操作,并汇总所有错误.无序的批量操作不能保证执行顺序.

注意,对于2.6以上的旧服务器,API将对操作进行下变频.但是,不可能100%下变频,因此可能存在一些边缘情况,无法正确报告正确的数字.

在您的情况下,可以成批执行批量API插入操作,如下所示:

For MongoDB 3.2+使用100

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
var entries = [ ... ] // a huge array containing the entry objects

var createNewEntries = function(db, entries, callback) {

    // Get the collection and bulk api artefacts
    var collection = db.collection('entries'),          
        bulkUpdateOps = [];    

    entries.forEach(function(doc) {
        bulkUpdateOps.push({ "insertOne": { "document": doc } });

        if (bulkUpdateOps.length === 1000) {
            collection.bulkWrite(bulkUpdateOps).then(function(r) {
                // do something with result
            });
            bulkUpdateOps = [];
        }
    })

    if (bulkUpdateOps.length > 0) {
        collection.bulkWrite(bulkUpdateOps).then(function(r) {
            // do something with result
        });
    }
};

For MongoDB <3.2

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/test';
var entries = [ ... ] // a huge array containing the entry objects

var createNewEntries = function(db, entries, callback) {

    // Get the collection and bulk api artefacts
    var collection = db.collection('entries'),          
        bulk = collection.initializeOrderedBulkOp(), // Initialize the Ordered Batch
        counter = 0;    

    // Execute the forEach method, triggers for each entry in the array
    entries.forEach(function(obj) {         

        bulk.insert(obj);           
        counter++;

        if (counter % 1000 == 0 ) {
            // Execute the operation
            bulk.execute(function(err, result) {  
                // re-initialise batch operation           
                bulk = collection.initializeOrderedBulkOp();
                callback();
            });
        }
    });             

    if (counter % 1000 != 0 ){
        bulk.execute(function(err, result) {
            // do something with result 
            callback();             
        }); 
    } 
};

调用100函数.

MongoClient.connect(url, function(err, db) {
    createNewEntries(db, entries, function() {
        db.close();
    });
});

Mongodb相关问答推荐

如何在Mongo中制作全覆盖索引

在服务器上部署后端时判断??=默认判断

MongoDB 聚合 - $project 和 $match 阶段未按预期工作

多键索引,性能问题

Mongoose 聚合和多级组

定期自动轮换 MongoDb 集合

有没有一种方法可以找到一个文档并通过 Go 更改 mongodb 中的 id/value 来克隆它

_id 和 $oid 的区别; mongo 数据库中的 $date 和 IsoDate

将 MongoDB 地理空间索引与 3d 数据结合使用

.NET 中的 Mongodb 单元测试

Spring Data MongoDB 中的独特之处

MongoDB 在 mongoengine 中使用 OR 子句

了解 Mongoose 中的关系和外键

Mongodb错误:The positional operator did not find the match needed from the query

Mongodb Atlas:管理员未授权执行命令

使用 $in 进行不区分大小写的搜索

错误:需要数据和盐参数

MongoError:failed to connect to server [localhost:27017] on first connect

Meteor 发布/订阅独特客户端集合的策略

无法从 mongodb 中删除集合