2016-11-08 6 views
0

Новый драйвер php mongodb удален hasNext метод.Что такое альтернатива MongoCursor :: hasNext в новом драйвере mongodb MongoDB Driver Cursor?

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

Вы можете использовать метод 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

+0

$ cursor-> ToArray() это эффективным? Он будет извлекать все документы и преобразовывать их в массив? – vishal

+0

Не знаете, почему нисходящий. Ответ был отредактирован давно, чтобы не использовать toArray. –

 Смежные вопросы

  • Нет связанных вопросов^_^