MongoDB\Driver\Manager::executeCommand() and
MongoDB\Driver\Manager::executeQuery() both return
their result(s) as a MongoDB\Driver\Cursor object.
This object can be used to iterate over the result set of the command or
query.
Because MongoDB\Driver\Cursor implements the
Traversable interface, you can simply
iterate over the result set with
foreach
.
<?php
$manager = new MongoDB\Driver\Manager();
/* Insert some documents so that our query returns information */
$bulkWrite = new MongoDB\Driver\BulkWrite;
$bulkWrite->insert(['name' => 'Ceres', 'size' => 946, 'distance' => 2.766]);
$bulkWrite->insert(['name' => 'Vesta', 'size' => 525, 'distance' => 2.362]);
$manager->executeBulkWrite("test.asteroids", $bulkWrite);
/* Query for all the items in the collection */
$query = new MongoDB\Driver\Query( [] );
/* Query the "asteroids" collection of the "test" database */
$cursor = $manager->executeQuery("test.asteroids", $query);
/* $cursor now contains an object that wraps around the result set. Use
* foreach() to iterate over all the result */
foreach($cursor as $document) {
print_r($document);
}
?>
Das oben gezeigte Beispiel erzeugt
eine ähnliche Ausgabe wie:
stdClass Object
(
[_id] => MongoDB\BSON\ObjectId Object
(
[oid] => 5a4cff2f122d3321565d8cc2
)
[name] => Ceres
[size] => 946
[distance] => 2.766
)
stdClass Object
(
[_id] => MongoDB\BSON\ObjectId Object
(
[oid] => 5a4cff2f122d3321565d8cc3
)
[name] => Vesta
[size] => 525
[distance] => 2.362
}