2

I was reading the API documentation (and was experimenting a bit), but it seems that cursor.count() no longer exists, so I was wondering if it was possible to get a count of your aggregate. This is because I would like to know how many documents there are in total, while still limiting and skipping results. I'm currently using $facet to facilitate this, but unsure if there's a better method.

{
    $facet: 
    {
        "results": 
        [
            {
                "$skip": 
                    start
            },
            {
                "$limit": 
                    finish
            },
        ],
        "total": 
        [
            {
                "$count": 
                    "total" 
            },
        ]
    }
}
A. L
  • 11,695
  • 23
  • 85
  • 163
  • To be clear: you want the total count of the entire collection, not just the count of the skip-limit result (which has a natural upper bound of the limit)? – Buzz Moschetti Jan 02 '19 at 01:52
  • @BuzzMoschetti I want the count of the entire filtered aggregation for pagination purposes. – A. L Jan 02 '19 at 01:53
  • OK, so there may be a `{$match: expr}` before the `$facet`. Your approach will correctly produce the count of the filtered agg plus skip-limit subset. – Buzz Moschetti Jan 02 '19 at 01:59
  • i was just wondering if there was an inbuilt cursor way. Just curious about performance. – A. L Jan 02 '19 at 02:36
  • 1
    There will be no performance issue either you use simple `.find()` query with the `skip() and limit()` cursor method or in the above `facet()` aggregation. May be the `$facet` will take some milliseconds more but that time will be negligible. – Ashh Jan 02 '19 at 04:14

1 Answers1

0

Using $facet for this use case is fine, both for style and performance. It should be noted, though, that this is essentially two queries in one, albeit server-side optimized. Getting the full count of the filtered material (or no filter at all if no initial $match) takes time regardless of the $skip/$limit setup. If the $match produces a relatively small amount of material, then $count will be fast. The dynamics involved are very similar to those in the regular SQL world, e.g. Run a query with a LIMIT/OFFSET and also get the total number of rows

Buzz Moschetti
  • 7,057
  • 3
  • 23
  • 33