在新的mongodb驱动程序MongoDB \ Driver \ Cursor中,MongoCursor :: hasNext的替代方法是什么?

时间:2016-11-08 12:10:53

标签: php mongodb mongodb-php

新的php mongodb驱动已删除hasNext方法。

http://php.net/manual/en/class.mongodb-driver-cursor.php

MongoDB\Driver\Cursor implements Traversable {

/* Methods */
    final private __construct ( void )
    final public MongoDB\Driver\CursorId getId ( void )
    final public MongoDB\Driver\Server getServer ( void )
    final public bool isDead ( void )
    final public void setTypeMap ( array $typemap )
    final public array toArray ( void )
}

我们正在尝试将mongodb升级到最新版本3.2和mongodb php驱动程序1.1。我们在代码中的某些地方使用了hasNext,我们需要重构。我尝试使用此https://secure.php.net/manual/en/class.mongodb-driver-cursor.php#118824

class MongodbCursor
{
    public static function hasNext(\MongoDB\Driver\Cursor $cursor)
    {
        $it = new \IteratorIterator($cursor);
        $it->rewind();
        return $it->valid();
    }
}

e.g。

 $cursor = some mongo query to get cursor

if (!MongodbCursor::hasNext($cursor)){

  //  since there is no data in above cursor, another query to get new cursor
  $cursor = 

}

foreach ($cursor as $item) {

}

它给出了以下错误,

Cursors cannot yield multiple iterators

1 个答案:

答案 0 :(得分:1)

您可以使用IteratorIterator方法检查游标是否为空。 例如:

$cursor = $collection->find(array('key'=> 'value'));
$it = new IteratorIterator($cursor);
$it->rewind();

if (!$it->current()){
    // Cursor is empty
    $cursor = $collection->find(array('anotherKey'=> 'anotherValue'));
    $it = new IteratorIterator($cursor);
    $it->rewind();
}
// Iterator all docs
while ($doc = $it->current()) {
    // Do something
    $it->next();
}

另见MongoDB PHP Library CRUD Tutorials