Docs Menu
Docs Home
/ / /
PHP Library Manual
/

Access Data From a Cursor

On this page

  • Overview
  • Access Cursor Contents Iteratively
  • Retrieve Documents Individually
  • Retrieve All Documents
  • Tailable Cursors
  • Additional Information

In this guide, you can learn how to access data from a cursor by using the MongoDB PHP Library.

A cursor is a mechanism that returns the results of a read operation in iterable batches. Cursors reduce both memory consumption and the number of server requests by holding only a subset of documents at any given time, rather than returning all documents at once.

Whenever the MongoDB PHP Library performs a read operation by using the MongoDB\Collection::find() method, it returns the matching documents in a MongoDB\Driver\Cursor instance.

The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your PHP application, instantiate a MongoDB\Client that connects to an Atlas cluster and assign the following value to your $collection variable:

$collection = $client->sample_restaurants->restaurants;

To learn how to create a free MongoDB Atlas cluster and load the sample datasets, see the Get Started with Atlas guide.

The MongoDB\Driver\Cursor class implements the Iterator interface, so you can use a foreach loop to iterate through its contents.

The following example uses the MongoDB\Collection::find() method to retrieve all documents in which the name field value is 'Dunkin' Donuts'. It then prints each document from the cursor returned by the find() method:

$cursor = $collection->find(['name' => 'Dunkin\' Donuts']);
foreach ($cursor as $doc) {
echo json_encode($doc), PHP_EOL;
}
{"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40379573"}
{"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40363098"}
{"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40395071"}
...

To retrieve an individual document from a cursor, call the current() method on a MongoDB\Driver\Cursor instance. This method returns the document that the cursor initially points to. You can continue to advance the cursor by calling the next() method, which instructs the cursor to point to the next retrieved document.

The following example finds all documents in which the name field value is 'Dunkin' Donuts'. Then, it prints the first retrieved document by calling the current() method on a cursor:

$cursor = $collection->find(['name' => 'Dunkin\' Donuts']);
$cursor->rewind();
echo json_encode($cursor->current());
{"_id":{"$oid":"..."},..."name":"Dunkin' Donuts","restaurant_id":"40379573"}

Warning

If the number and size of documents returned by your query exceeds available application memory, your program will crash. If you expect a large result set, access your cursor iteratively.

To retrieve all documents from a cursor, convert the cursor into an array by using either of the following methods:

  • MongoDB\\Driver\\Cursor::toArray(): Call on a MongoDB\Driver\Cursor object

  • iterator_to_array(): Pass a MongoDB\Driver\Cursor object as a parameter

The following example calls the toArray() method on a cursor to store its results in an array:

$cursor = $collection->find(['name' => 'Dunkin\' Donuts']);
$array_results = $cursor->toArray();

When querying on a capped collection, you can use a tailable cursor that remains open after the client exhausts the results in a cursor. To create a tailable cursor, set the cursorType option to MongoDB\Operation\Find::TAILABLE in an array. Then, pass the array as an options parameter to the MongoDB\Collection::find() method.

For example, you can create a capped collection called vegetables that stores documents representing vegetables, as shown in the following code:

$db = $client->db;
$db->createCollection(
'vegetables',
['capped' => true, 'size' => 1024 * 1024]
);
$vegetables = [
['name' => 'cauliflower'],
['name' => 'zucchini']
];
$collection = $db->vegetables;
$result = $collection->insertMany($vegetables);

The following code uses a tailable cursor to retrieve all documents in the vegetables collection. After the cursor is exhausted, it remains open until retrieving three documents:

$cursor = $collection->find([], ['cursorType' => MongoDB\Operation\Find::TAILABLE]);
$cursor->rewind();
$docs_found = 0;
while ($docs_found < 3) {
if ($cursor->valid()) {
$doc = $cursor->current();
echo json_encode($doc), PHP_EOL;
$docs_found++;
}
$cursor->next();
}
{"_id":{"$oid":"..."},"name":"cauliflower"}
{"_id":{"$oid":"..."},"name":"zucchini"}

If you insert another document into the vegetables collection, the preceding code prints the new document and closes the while loop.

To learn more about tailable cursors, see Tailable Cursors in the MongoDB Server manual.

To learn more about read operations, see the Retrieve Data guide.

To learn more about cursors, see the following pages in the extension API documentation:

To learn more about the find() method, see the API documentation for MongoDB\Collection::find().

Back

Specify Fields to Return