使用nodejs在mongodb中插入最多数量的记录

inserting max num of records in mongodb using nodejs in less time

本文关键字:记录 插入 nodejs mongodb 使用      更新时间:2023-09-26

我正在做一项小任务,需要读取节点中的一个大文件(即1.3GB),并将每一行划分为一条记录,以便在更短的时间内将每条记录插入mongodb集合。请用代码向我推荐,并提前表示感谢。

您可能希望在不将数据缓冲到内存中的情况下读取这么多数据。

假设您正在处理JSON数据,我认为这可能是一种可行的方法:

var LineByLineReader = require('line-by-line');
var fileHandler = new LineByLineReader('path/to/file', { encoding:'utf8', skipEmptyLines: true });
var entries = [];
var bulkSize = 100000; // tweak as needed
fileHandler.on('error', function (err) {
  // process errors here
});
fileHandler.on('line', function (line) {
  entries.push(JSON.parse(line));
  if (entries.length === bulkSize) {
     // pause handler and write data
     fileHandler.pause();
     YourCollection.insertMany(entries)
     .then(() => { 
       entries = [];
       fileHandler.resume();
     })
  }
});
fileHandler.on('end', function () {
  YourCollection.insertMany(entries)
  .then(() => {
    // everything's done, do your stuff here
  });
});

line-by-line模块似乎有点bug,将来可能会被弃用,因此您可能希望使用逐行而不是