迭代一个大的MongoDB集合而不会耗尽内存


Iterating over a big MongoDB collection without running out of memory

我有一个很大的Mongo集合,我想遍历一下所以我这样做:

$cursor = $mongo->my_big_collection->find([]);
foreach ($cursor as $doc)
    do_something();

但是我最终用光了内存。我希望游标在处理完每个文档后释放内存。为什么不是这样呢?我试着在循环结束时调用unset($doc),但没有帮助。

现在我必须做这样的事情来解决这个问题(通过批处理文档并在每个批处理之后调用游标上的unset()):

for ($skip = 0; true; $skip += 1000)
{
    $cursor = $mongo->my_big_collection->find()->skip($skip)->limit(1000);
    if (!$cursor->hasNext())
        break;
    foreach ($cursor as $doc)
        do_something();
    unset($cursor);
}

这看起来很尴尬。迭代器的全部意义就在于不必这样做。有没有更好的办法?

我正在使用hhvm 3.12与mongofill。

谢谢你的帮助。

MongoCursor.php

/**
 * Advances the cursor to the next result
 *
 * @return void - NULL.
 */
public function next()
{
    $this->doQuery();
    $this->fetchMoreDocumentsIfNeeded(); // <<< add documents to $this->documents
    $this->currKey++;
}
/**
 * Return the next object to which this cursor points, and advance the
 * cursor
 *
 * @return array - Returns the next object.
 */
public function getNext()
{
    $this->next();
    return $this->current();
}

当您遍历游标时,它将在游标中存储所有文档$this->documents。没有什么清楚的文件收集。你可以尝试实现一个迭代,删除$this->documents的文档后,他们可能?