2016-11-08 80 views
0

新的php mongodb驅動程序已經移除了hasNext方法。在新的mongodb驅動程序MongoDB Driver Cursor中,MongoCursor :: 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(); 
    } 
} 

例如

$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->指定者()是高效?它會獲取所有文件並轉換爲數組? – vishal

+0

不知道爲什麼downvote。答案在很久以前被編輯過,不用toArray。 –