新的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
答案 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();
}