因为 MongoDB\Driver\Cursor 实现 Traversable 接口,您只需使用 foreach
遍历结果集。
<?php
$manager = new MongoDB\Driver\Manager();
/* 插入一些文档,以便我们的查询返回信息 */
$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 = new MongoDB\Driver\Query( [] );
/* 查询 "test" 数据库的 "asteroids" 集合 */
$cursor = $manager->executeQuery("test.asteroids", $query);
/* $cursor 现在包含一个包装结果集的对象。使用
* foreach() 迭代所有结果 */
foreach($cursor as $document) {
print_r($document);
}
?>
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
}