[英]Most efficient way to insert JSON objects from many files to MongoDB in NodeJS
我正在尋找將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多歲是好的,但是我想在這里提高性能。
這個代碼還沒有完全優化,在這里我不做任何錯誤處理,但是它可以減少插入的時間。(您的主要瓶頸)
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'); }); }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.