Using a Cursor to Get All of the Documents

In order to get all the documents in the collection, we will use MongoCollection::find(). The find() method returns a MongoCursor object which allows us to iterate over the set of documents that matched our query. So to query all of the documents and print them out:

<?php
$connection 
= new MongoClient();
$collection $connection->database->collectionName;

$cursor $collection->find();
foreach ( 
$cursor as $id => $value )
{
    echo 
"$id: ";
    
var_dump$value );
}
?>
and that should print all 101 documents in the collection. $id is the _id field of a document (cast to a string) and $value is the document itself.

See Also

The API documentation on MongoCollection::find() contains more information about finding data.

add a note add a note

User Contributed Notes 1 note

up
0
mike at brenden dot com
9 years ago
Instead of running while() or foreach() over a Mongo cursor, get all results from cursor into array:

$curs = $Mdb->tbl->find();
$arrOut = iterator_to_array( $curs, false );  // false uses numeric index.
return $arrOut;
To Top