在NodeJS中将许多文件中的JSON对象插入MongoDB的最有效方法

问题描述 投票:1回答:1

我正在寻找将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');
        });
    });
});

在我的本地机器上平均需要20s(20074.834ms)。好吧,20多岁是好的,但我想改善这里的表现。

json node.js mongodb import stream
1个回答
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');
        });
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.