如果您的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();
});
});