1

I'm performing a simple request to my MongoDB in php. It looks like this:

$result = $this->myMongoClient->myCollection->find([
    'param_1' => $param_1,
    'param_2' => $param_2,
]);

This returns a MongoDB\Driver\Cursor object. I need the count of returned entrys from the database.

I've googeld a while and found this. But with this function dose not exists on the object returend by MongoDB (Call to undefined method MongoDB\Driver\Cursor::count())

$result->count()

Which is the commun way to count the number of results?

Markus
  • 1,909
  • 4
  • 26
  • 54

2 Answers2

1

I have found a solution, but don't know if it is recommendable or not.

count($result->toArray());
Markus
  • 1,909
  • 4
  • 26
  • 54
0

I don't know if you are using the MongoDB PHP Library, but if you are you can just use the following

$result = $this->myMongoClient->myCollection->countDocuments($where);

https://docs.mongodb.com/php-library/master/reference/method/MongoDBCollection-countDocuments/index.html

Trevor Geene
  • 479
  • 3
  • 12
  • Yes i'm using the offical php library. With this solution I have to send two requests to the database one to get the documents and one to count them. Am I right? – Markus May 13 '19 at 21:26
  • Yes, this method would require you to make 2 separate calls to the database if you wanted both a document count and the documents themselves. – Trevor Geene May 13 '19 at 21:30