PHP Velho Oeste 2024

使用游标获取所有文档

要获得集合中的所有文档,我们需要 MongoCollection::find() 方法。 find() 方法返回一个 MongoCursor 对象,允许我们遍历整个结果集合来读取文档。要查询所有的文档并显示它们,使用:

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

$cursor $collection->find();
foreach ( 
$cursor as $id => $value )
{
    echo 
"$id: ";
    
var_dump$value );
}
?>
这样会输出整个集合中的101个文档。 $id 是集合的 _id 字段(被转换成字符串), $value 是文档本身。

参见

MongoCollection::find() 方法的文档中有关于查询的详细信息。

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