3

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?

Sander Toonen
  • 3,463
  • 35
  • 54
  • Is there a way to get the count result without having to get all the results from the Mongo server? All I need is the count. – solarc Dec 14 '18 at 19:39

2 Answers2

8

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";
}
  • Is this pulling all the data along with the query... or just counting the responses? My documents are large and I'm trying to avoid the entire set of documents from having to come across the wire just to count them. – lowcrawler Mar 05 '21 at 20:53
  • @lowcrawler only returns a number, in fact this code works the same as db.runCommand( { count: 'collection' } ) and return { "n" : 26, "ok" : 1 }. – Alexandr Prokopenko Mar 10 '21 at 10:51
1

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);
Chin Leung
  • 14,621
  • 3
  • 34
  • 58