gpt4 book ai didi

javascript - 将 100 万个对象发送到 Mongo DB,而不会耗尽内存

转载 作者:太空宇宙 更新时间:2023-11-04 02:56:52 24 4
gpt4 key购买 nike

为了简单起见,我在这里使用了 for 循环来创建一个包含 100 万个对象的数组。

我想将数组中的每个对象发布到 mongo db。

我的内存总是不够用。

我知道我可以增加内存分配,但这不是我想要的解决方案。我也不想使用 mongo 的批量方法,原因超出了本示例的范围。

我知道必须有某种方法来发布这些对象,这意味着每次迭代都会释放内存(收集垃圾?) - 谁能告诉我它是什么?

谢谢!

此处当前代码供引用(这会导致分配错误):

var results = [];

for(var i = 1; i < 1000001; i++){

results.push({"num":i});

}

async = require("async");
var mongodb = require('mongodb');

var MongoClient = mongodb.MongoClient;
var mongoUrl = 'mongodb://root@localhost:27017/results';

MongoClient.connect(mongoUrl, function (err, db) {

var collection = db.collection('results');

// 1st para in async.each() is the array of items
async.each(results,
// 2nd param is the function that each item is passed to
function(item, callback){
// Call an asynchronous function, often a save() to DB
collection.insert(item, function (err, result) {
if(err) console.log(err);
console.log(item);
callback();
});
},
// 3rd param is the function to call when everything's done
function(err){
// All tasks are done now
db.close();
}
);
});

最佳答案

async.each() 并行运行插入,因此它基本上启动了 1000000 个并发插入操作。

您可能希望通过使用 async.eachLimit() 将其限制为 100。

关于javascript - 将 100 万个对象发送到 Mongo DB,而不会耗尽内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40786554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com