遍历由于太大而无法加载的整个 mongo 数据库的方法?

awi*_*ley 2 database mongodb node.js

我必须为我公司的一位客户做一些数据处理。他们有一个大约有 4.7GB 数据的数据库。我需要为使用 mongo 文档和外部引用的两个属性计算的每个文档添加一个字段。

我的问题是,我不能执行 collection.find() 因为 Node.js 内存不足。遍历整个集合的最佳方法是什么,而该集合太大而无法通过单个调用来加载?

cod*_*onk 5

是的,有办法。Mongo 旨在处理大型数据集。

您可能正在耗尽内存,不是因为db.collection.find(),而是因为您试图用类似db.collection.find().toArray().

对大于内存的结果集进行操作的正确方法是使用游标。以下是您在 mongo 控制台中的操作方法:

var outsidevars = {
   "z": 5
};

var manipulator = function(document,outsidevars) {
    var newfield = document.x + document.y + outsidevars.z;
    document.newField = newfield;
    return document;
};

var cursor = db.collection.find();

while (cursor.hasNext()) {
    // load only one document from the resultset into memory
    var thisdoc = cursor.next();
    var newnoc = manipulator(thisdoc,outsidevars);
    d.collection.update({"_id": thisdoc['_id']},newdoc);
};
Run Code Online (Sandbox Code Playgroud)