问题
The mongo PHP extension is deprecated in favour of the mongodb extension. This extension is used together with the mongo-php-library.
In the old extension one could get the result count from the cursor using MongoCursor::count(). However, the new cursor MongoDB\Driver\Cursor has no such method. What is the new way of getting the number of results from after performing a query against MongoDB?
回答1:
I use this code.
$query = ["hello" => "world"];
$command = new MongoDB\Driver\Command(["count" => "collection", "query" => $query]);
try {
$result = $mongo->executeCommand("mydb", $command);
$res = current($result->toArray());
$count = $res->n;
echo $count;
} catch (MongoDB\Driver\Exception\Exception $e) {
echo $e->getMessage(), "\n";
}
回答2:
You can do it like this
Model::count(array($whereClause));
The $whereClause
would be your search criteria basically.
Otherwise, if your query returns an array, you could do
$data = Model::find(array($whereClause));
$total = count($data);
来源:https://stackoverflow.com/questions/36726069/how-to-get-cursor-result-count-using-the-mongodb-php-extension