PHP 7.0.6 Released

The MongoDB\Driver\Cursor class

(mongodb >=1.0.0)

Introduction

The MongoDB\Driver\Cursor class encapsulates the results of a MongoDB command or query and may be returned by MongoDB\Driver\Manager::executeCommand() or MongoDB\Driver\Manager::executeQuery(), respectively.

Class synopsis

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 )
}

Table of Contents

User Contributed Notes

max-p at max-p dot me
2 months ago
As one might notice, this class does not implement a hasNext() or next() method as opposed to the now deprecated Mongo driver.

If, for any reason, you need to pull data from the cursor procedurally or otherwise need to override the behavior of foreach while iterating on the cursor, the SPL \IteratorIterator class can be used. When doing so, it is important to rewind the iterator before using it, otherwise you won't get any data back.

<?php
$cursor
= $collection->find();
$it = new \IteratorIterator($cursor);
$it->rewind(); // Very important

while($doc = $it->current()) {
   
var_dump($doc);
   
$it->next();
}
?>

I used this trick to build a backward compatibility wrapper emulating the old Mongo driver in order to upgrade an older codebase.
mikemartin2016 at gmail dot com
2 months ago
I noticed that  ->sort is missing from the cursor.  Seems like the old driver has more functionality.

[red.: The way how cursors are created is different between the drivers. In the old driver, the cursor would not be created until after the first rewind() call on the iterator.

In the new driver the cursor already exists. Because sort (and limit and skip) parameters need to be send to the server, they can not be called after the cursor already has been created.

You can use sort (and limit and skip) with the new driver as well, by specifying them as options to the Query as shown in this example: http://php.net/manual/en/mongodb-driver-query.construct.php#refsect1-mongodb-driver-query.construct-examples]
To Top