2016-11-08 4 views
0

Le nouveau pilote php mongodb a supprimé la méthode hasNext.ce qui est une alternative à MongoCursor :: hasNext dans le nouveau pilote 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) 
} 

Nous essayons de mettre à niveau MongoDB à la dernière version 3.2 et pilote mongodb php 1.1. Nous avons utilisé hasNext à certains endroits du code que nous devons refactoriser. J'ai essayé d'utiliser ceci 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(); 
    } 
} 

par exemple.

$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) { 

} 

Il donne ci-dessous erreur,

Cursors cannot yield multiple iterators 

Répondre

0

Vous pouvez utiliser la méthode IteratorIterator pour vérifier si le curseur est vide. Par exemple:

$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(); 
} 

Voir aussi MongoDB PHP Library CRUD Tutorials

+0

$ cursor-> toArray() est-il efficace? Il va chercher tous les documents et convertir en tableau? – vishal

+0

Vous ne savez pas pourquoi la liste déroulante. La réponse a été éditée il y a longtemps pour ne pas utiliser toArray. –