Php 在不耗尽内存的情况下迭代大型MongoDB集合
我有一个很大的Mongo集合,我想迭代一下,所以我会这样做:Php 在不耗尽内存的情况下迭代大型MongoDB集合,php,mongodb,hhvm,Php,Mongodb,Hhvm,我有一个很大的Mongo集合,我想迭代一下,所以我会这样做: $cursor = $mongo->my_big_collection->find([]); foreach ($cursor as $doc) do_something(); 但我最终还是记忆犹新。我希望光标在处理每个文档后释放内存。为什么不是这样? 在循环结束时,我尝试调用unset($doc),但没有效果 现在我必须这样做才能解决这个问题(按批处理文档,并在每批处理后在光标上调用unset()): 这似乎
$cursor = $mongo->my_big_collection->find([]);
foreach ($cursor as $doc)
do_something();
但我最终还是记忆犹新。我希望光标在处理每个文档后释放内存。为什么不是这样?
在循环结束时,我尝试调用unset($doc)
,但没有效果
现在我必须这样做才能解决这个问题(按批处理文档,并在每批处理后在光标上调用unset()
):
这似乎很尴尬。迭代器的关键是不必这样做。有更好的办法吗
我使用的是HHVM3.12
感谢您的帮助。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();
}
/**
*将光标前进到下一个结果
*
*@returnvoid-NULL。
*/
公共职能下一步()
{
$this->doQuery();
$this->fetchMoreDocumentsIfNeeded();//currKey++;
}
/**
*返回此光标指向的下一个对象,并前进
*光标
*
*@return数组-返回下一个对象。
*/
公共函数getNext()
{
$this->next();
返回$this->current();
}
当您遍历游标时,它将在游标中存储所有文档$this->documents
。
这本文件集没有任何内容。
您可以尝试实现一个迭代,在获得
$this->documents
的文档后删除这些文档 这看起来也是一个您应该直接在GitHub上向mongofill报告的问题:)
/**
* 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();
}