2

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.

Thomas Leduc
  • 1,092
  • 1
  • 20
  • 44
  • The apparently "old" issue is looking for a count of all things before you apply the limit. This has meant and "still" means that in order to "count" everything, you would need to stuff all the content into an array in a single document, then unwind that to continue. Clearly that is not practical. Getting total counts for paging has been and always will be obtained by running two queries. Unless your data storage natively returns facet results with counts where you don't need to think about it, then that is how it is done. The duplicate I am marking sums this up. – Blakes Seven Feb 11 '16 at 20:15

0 Answers0