将10,000个JSON文件(总共30GB)插入MongoDB的最佳方法

它不看我用Python来结合所有的JSON文件是方便的,组合的文件将是30G。

我正在使用mongoDB和nodejs。 我如何填充示例JSON的方式是:

var data = require('./data1.json') var populateDB = function() { db.collection('temp', function(err, collection) { collection.insert(data, {safe:true}, function(err, result) {}); }); }; 

这只会添加一个json文件。 我应该如何使用这里的10000多个json文件填充集合? 任何build议,高度赞赏!

最简单的方法是编写一个处理一个JSON文件的节点程序,然后在shell中多次运行它:

 for i in *.json; do node program.js $i; done 

你的节点程序只需要访问process.argv的名字,而不是硬编码,但逻辑将是相同的。

如果你想在节点上做所有事情,那么你将不得不阅读目录,获取所有的.json文件,按顺序读取它们中的每一个,然后运行一个类似于你发布的代码。 如果这是一个单一的任务,那么你甚至可以使用“同步”function来简化你的代码,如果它是一个连续的任务,一次做一件事,你不关心并行添加数据。

像这样的东西会工作

npm i glob-fs mongodb async --save

 const async = require('async'); const fs = require('fs'); const glob = require('glob-fs')({ gitignore: true }); const MongoClient = require('mongodb').MongoClient; const files = './files/data*.json'; const collection = 'test'; const url = 'mongodb://localhost:27017/test'; // Connect to db MongoClient.connect(url, function (err, db) { if (err) { console.log(err); } // Get the collection const col = db.collection(collection); glob.readdirPromise(files) .then(function (f) { return async.eachSeries(f, (item, callback) => { fs.readFile(item, 'utf8', function (err, data) { if (err) { return console.log(err); } // Insert into mongo col.insertMany(JSON.parse(data)).then((r) => { console.log(r); return callback(r); }).catch(function (fail) { console.log(fail) }); }); }, err => { console.log(err); }); }) .then(err => { if (err) { db.close(); } }) .catch(err => { console.log(err); }); });