How to get cursor result count using the MongoDB PHP extension

邮差的信 提交于 2019-12-13 01:34:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!