Oleg Oleg - 1 month ago 6
PHP Question

mongo count(*) with php but without sending all result array

I am writing my scripts in PHP and I try to convert SQL

SELECT COUNT(*) AS Rank
FROM user
WHERE user.lvl > $user_level


query to Mongo.

I found only one decision:

$nosql = array(
'lvl' => array('$gt' => $user_level)
);
$result = $collection->find($nosql);
$length = count(iterator_to_array($result));



  1. get all objects which satisfy the condition

  2. And count them in PHP



It is possible to get count of needed objects without sending all array?

Answer

mongodb can count result like this you didn't need to use count(iterator_to_array($result));

$nosql = array(
 'lvl' => array('$gt' => $user_level)
);    
$result = $collection->find($nosql);
$length = $result->count();