我正在寻找将JSON对象从文件导入MongoDB集合的最有效方法。
文件看起来像这样:
[ { ... }, { ... } ]
每个文件大约有200个对象,有100个文件,所以总计20.000个对象。我尝试了很多方法,很多图书馆......
我目前的工作示例是:
const fs = require('fs');
const JSONStream = require('JSONStream');
const es = require('event-stream');
const MongoClient = require('mongodb').MongoClient;
const glob = require('glob');
const url = 'mongodb://localhost:27017/inventory';
console.time('import');
MongoClient.connect(url, function(err, database) {
const db = database.db('inventory');
const collection = db.collection('storage');
let importer = [];
glob('../data/*.json', function (error, files) {
files.forEach(function (filename) {
importer.push(new Promise(function (resolve) {
fs.createReadStream(filename).pipe(JSONStream.parse('*')).pipe(es.map(function (document) {
collection.insertOne(document).then(resolve);
}));
}));
});
Promise.all(importer).then(function () {
console.timeEnd('import');
});
});
});
我的本地计算机平均需要20秒(20074.834毫秒)。好吧,20多岁是好的,但我想改善这里的表现。
答案 0 :(得分:0)
这段代码没有完全优化,我不在这里做任何错误处理,但它假设减少插入的时间。(你的主要瓶颈)
const fs = require('fs');
const JSONStream = require('JSONStream');
const es = require('event-stream');
const MongoClient = require('mongodb').MongoClient;
const glob = require('glob');
const url = 'mongodb://localhost:27017/inventory';
console.time('import');
MongoClient.connect(url, function(err, database) {
const db = database.db('inventory');
const collection = db.collection('storage');
let importer = [];
glob('../data/*.json', function (error, files) {
files.forEach(function (filename) {
const documents = JSON.parse(fs.readFileSync(filename, 'utf8'));
importer.push(collection.insertMany(documents),{w:0,ordered:false});
});
});
Promise.all(importer).then(function () {
console.timeEnd('import');
});
});
});