I've seen many questions about the total count after a mongoDB aggregation with a limit but they're old ones and I need an update on that.
The goal is to get documents paginated in only one query with a count.
in this aggregation, we need :
- a match with a regexp,
- the total count of documents matching the regexp,
- a limitation of 10 documents
- a skip of the n first documents.
Many answers say that we can't have a total count after a limit in aggregation but with the new feature of $sum
in $project
, I wonder if it's possible to do that ?
[
{
'$match': {content: {'$regex': 'a string to search', '$options': 'i'}}
},
{
'$project': {
'article': '$$ROOT',
'blog': '$blog',
'views': '$views',
'created_at': '$created_at'
}
},
{ '$skip': 20 },
{ '$limit': 10 }
]
with a count : { $sum : 1 }
. Another thing is if I group by null, I lost all documents.
Does Mongo 3.2 can resolve this issue ?
-- EDIT
I do some heavy stuff in the $match
(like $regexp
) and I have to count the total result according to this match. I use $limit
and not limit()
otherwise, I had just to make a count()
after. Even if it sound like overkill query, I think the gain is real if I do just one query. Is there any way at all ? At least I want to try and see if it's more or less efficient.