我需要读取数千行的日志文件并将每行写入Mongo数据库。我正在使用节点流读取文件。我正在使用'split'npm软件包将文件分成'行'。由于网络的考虑,MongoDB的写入将比读取的日志文件花费更多的时间。Node.js流写入MongoDB - 关注性能
我的核心代码如下所示:
var readableStream = fs.createReadStream(filename);
readableStream
.pipe(split()) // This splits the data into 'lines'
.on('data', function (chunk) {
chunkCount++;
slowAsyncFunctionToWriteLogEntryToDatabase(chunk); // This will take ages
})
.on('end', function() {
// resolve the promise which bounds this process
defer.resolve({v:3,chunkCount: chunkCount})
});
我需要担心的MongoDB系统将写入次数敲定排队?据推测,节点管道背压机制不会知道大量数据库写入正在排队?有什么方法可以“减慢”可读流,以便它在读取日志文件中的下一行之前等待每个MongoDB插入完成?我是否不必要地担心?
我想你可以读取整个日志文件,然后用db.collection.insertMany()在一个db调用中插入所有文档。这将是更快 – felix