SunshinePHP Developer Conference 2015

The MongoCursor class

(PECL mongo >=0.9.0)

Introduction

A cursor is used to iterate through the results of a database query. For example, to query the database and see all results, you could do:

Example #1 MongoCursor basic usage

<?php

$cursor 
$collection->find();
var_dump(iterator_to_array($cursor));

?>

You don't generally create cursors using the MongoCursor constructor, you get a new cursor by calling MongoCollection::find() (as shown above).

Suppose that, in the example above, $collection was a 50GB collection. We certainly wouldn't want to load that into memory all at once, which is what a cursor is for: allowing the client to access the collection in dribs and drabs.

If we have a large result set, we can iterate through it, loading a few megabytes of results into memory at a time. For example, we could do:

Example #2 Iterating over MongoCursor

<?php

$cursor 
$collection->find();

foreach (
$cursor as $doc) {
    
// do something to each document
}

?>
This will go through each document in the collection, loading and garbage collecting documents as needed.

Note that this means that a cursor does not "contain" the database results, it just manages them. Thus, if you print a cursor (with, say, var_dump() or print_r()), you'll just get the cursor object, not your documents. To get the documents themselves, you can use one of the methods shown above.

Cursor Stages

A MongoCursor has two "life stages": pre- and post- query. When a cursor is created, it has not yet contacted the database, so it is in its pre-query state. In this state, the client can further specify what they want the query to do, including adding limits, skips, sorts, and more advanced options.

When the client attempts to get a result (by calling MongoCursor::next(), directly or indirectly), the cursor moves into the post-query stage. At this point, the query has been executed by the database and cannot be modified anymore.

Example #3 Adding options to MongoCursor

<?php

$cursor 
$collection->find()->limit(10);

// database has not yet been queried, so more search options can be added
$cursor $cursor->sort(array("a" => 1));

var_dump($cursor->getNext());
// now database has been queried and more options cannot be added

// so this will throw an exception:
$cursor->skip(4);
?>

Class synopsis

MongoCursor implements Iterator {
/* Static Fields */
static boolean $slaveOkay = FALSE ;
static integer $timeout = 30000 ;
/* Methods */
public MongoCursor addOption ( string $key , mixed $value )
public MongoCursor awaitData ([ bool $wait = true ] )
public MongoCursor batchSize ( int $batchSize )
public __construct ( MongoClient $connection , string $ns [, array $query = array() [, array $fields = array() ]] )
public int count ([ bool $foundOnly = FALSE ] )
public array current ( void )
public bool dead ( void )
protected void doQuery ( void )
public array explain ( void )
public MongoCursor fields ( array $f )
public array getNext ( void )
public array getReadPreference ( void )
public bool hasNext ( void )
public MongoCursor hint ( mixed $index )
public MongoCursor immortal ([ bool $liveForever = true ] )
public array info ( void )
public string key ( void )
public MongoCursor limit ( int $num )
public MongoCursor maxTimeMS ( int $ms )
public void next ( void )
public MongoCursor partial ([ bool $okay = true ] )
public void reset ( void )
public void rewind ( void )
public MongoCursor setFlag ( int $flag [, bool $set = true ] )
public MongoCursor setReadPreference ( string $read_preference [, array $tags ] )
public MongoCursor skip ( int $num )
public MongoCursor slaveOkay ([ bool $okay = true ] )
public MongoCursor snapshot ( void )
public MongoCursor sort ( array $fields )
public MongoCursor tailable ([ bool $tail = true ] )
public MongoCursor timeout ( int $ms )
public bool valid ( void )
}

Static Variables

slaveOkay

If the query should have the "slaveOkay" flag set, which allows reads on the secondary (secondaries are, by default, just for backup and not queried). Can be overridden with MongoCursor::slaveOkay().

This functionality is deprecated. Please use Read Preferences instead.

timeout

Set timeout in milliseconds for all database responses. Use -1 to wait forever. Can be overridden with MongoCursor::timeout(). This does not cause the MongoDB server to cancel the operation; it only instructs the driver to stop waiting for a response and throw a MongoCursorTimeoutException after a set time.

See Also

MongoDB core docs on » cursors.

Table of Contents

add a note add a note

User Contributed Notes 2 notes

up
2
adrian dot zurek at netmedia dot com dot pl
2 years ago
One *VERY* important note, if You do:
$cursor = $collection->find(array(), array('_id' => 0)); // ommit '_id' field in result

then:
var_dump(iterator_to_array($cursor));

will return only *ONE* document, not all!
up
-1
Adil Baig @ AiDezigns
3 years ago
If you want to know whether a cursor returned any results it is faster to use 'hasNext()' than 'count'
To Top