在MongoDB中插入10000个JSON文件(总共30GB)的最佳方法

2024-10-01 02:29:27 发布

您现在位置:Python中文网/ 问答频道 /正文

在我看来,使用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文件?如有任何建议,我们将不胜感激!在


Tags: 文件方法json示例dbdatavarmongodb
2条回答

像这样的东西会有用的

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);
    });
});

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

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

您的Node程序只需要从process.argv访问名称,而不是硬编码,但逻辑是相同的。在

如果要在node中执行所有操作,则必须读取目录,获取所有.json文件,按顺序读取每个文件,然后运行与您发布的类似的代码。如果这是一个一次性的任务,那么你甚至可以不用使用“Sync”函数来简化代码,如果这是一个一次只做一件事情的连续任务,而且你不在乎并行添加数据。在

相关问题 更多 >