Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

I have used aggregation for fetching records from mongodb.

$result = $collection->aggregate(array( 

array('$match' => $document), 

array('$group' => array('_id' => '$book_id', 'date' => 

array('$max' => '$book_viewed'), 'views' => 

array('$sum' => 1))), 

array('$sort' => $sort), 

array('$skip' => $skip), 

array('$limit' => $limit), 

));

If I execute this query without limit then 10 records will be fetched. But I want to keep limit as 2. So I would like to get the total records to count. How can I do with aggregation? Please advise me. Thanks

2 Answers

0 votes
by (106k points)

To get total records to count in MongoDB you can use below-mentioned code which finds total count in the collection.

db.collection.aggregate( [ 

{ $match : { score : { $gt : 70, $lte : 90 } } }, 

{ $group: { _id: null, count: { $sum: 1 } } } 

] );

0 votes
by (108k points)

Use this to find total count in the collection.

db.collection.aggregate( [

{ $match : { score : { $gt : 70, $lte : 90 } } },

{ $group: { _id: null, count: { $sum: -1 } } }//-1 for descending

] );

Related questions

Browse Categories

...