Mongodb PHP cursor does not fill array

Viewed 15

I have a find method in PHP which calls Mongodb, iterates over the cursor and should fill result array which will return. It looks like:

public function find($collection, $where, $select = [], $options = [])
{
    $result = [];

    if( $select ) foreach ( $select as $col) $options['projection'][$col] = 1;  // Need projection in format: ['id' => 1, 'name' => 1, ...]

    /** @var Cursor $cursor */
    $cursor = $this->mongoDb->{$collection}->find($where, $options);
    $cursor->setTypeMap(['root' => 'array', 'document' => 'array', 'array' => 'array']);
    //$result = $cursor->toArray();    $result = $cursor;

    $i = 0;
    foreach ($cursor as $doc) {
        if(++$i < 5) Debugger::log($doc);
        $doc = $this->parseDocument($doc);
        $result[] = $doc;
    }

    Debugger::log($result);

    return $result;
}

The problem is that $result is empty although there are documents in result. It seems $result array is returned before cursor can fill it. It does not make any sense. I can not use $cursor->toArray() cause it has timeout error. Can somebody tell me plase how to fix it or how to fix timeout error with toArray(). Collection has above 170mils. documents so timeout is quite problem.

Thank you very much.

0 Answers
Related