0

Below is the query to get data by limit offset to paginate in laravel. How can i get total Count of returned result can anyone help.

i tried $result->count() but it gives below error: Call to undefined method MongoDB\Driver\Cursor::count()

    $db = mongoConnection('bulk');
    $option['projection'] = self::$fields;
    $newPage = $page - 1;
    $skip = $newPage*$limit;
    $option['skip'] =  $skip;
    $option['limit']=$limit;
    $option['sort']['cpc'] = -1;
    $option['allowDiskUse'] = true;
    $query = new MongoDB\Driver\Query($conditionArray, $option);
    $result = $db->executeQuery(env('MONGODBNAME','').'.jobs', $query);
  • No Not solved yet can you write syntax of how can i use aggregate and $count with above code because i have tried by $option['aggregate'] = ['$count'=>1]; but not working – Sejal Gauswami Jul 08 '22 at 10:08
  • have you tried `$query.count()` it should work I guess as you only want total number of results count normally it is of the form `db.collection.find( { a: 5, b: 5 } ).count()` but I assume your $query should be fine for it. – bhucho Jul 08 '22 at 17:32
  • No its not working it gives error -- count() expects at least 1 argument, 0 given – Sejal Gauswami Jul 11 '22 at 10:52
  • your mongo version less than 4.0 ? like 3.2 – bhucho Jul 11 '22 at 12:37
  • you can try out [this](https://stackoverflow.com/a/49483919/9471283) answer if your mongo version is more than 3.4 – bhucho Jul 11 '22 at 12:45

1 Answers1

0

So I think a few years ago they deleted the count() method from MongoDB driver, since then I have used the toArray() and counting that, so you will have to do the following

$result->toArray();
count($result);

You can store that in a variable or whatever you need.

dz0nika
  • 882
  • 1
  • 5
  • 16
  • It gives count of only 10 records which is limit given. if total count let say 40 then it returns only count 10 – Sejal Gauswami Jul 04 '22 at 11:57
  • Well you query 10 results how do you except to get all the db results on the same query, if you want that remove the limit. – dz0nika Jul 05 '22 at 08:22
  • Actually i need count on list page where it will get records by limit & offset and pagination is added so i need total count. But i don't find any way to implement it using MongoDB\Driver\Query. Anyway i will use laravel query with pagination. Thanks for the reply – Sejal Gauswami Jul 05 '22 at 10:42