Intellipaat 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

3 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 (107k 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

] );

0 votes
by (1.2k points)

For the mentioned concern, what we need to do is to find the total count while limiting the number of results thus obtained. Since, the code provided is of older version of MongoDB, hence I’m sharing the answer based on the current MongoDB. So, for this concern we can use $facet. This will allows you to perform multiple operation in the same aggregation pipeline. Using this we can get total count of records while limiting the number of results in one single query.

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...