How to get count before limit in the Mongo aggregation pipeline
Starting in Mongo 3.4
, the $facet
aggregation stage allows processing multiple aggregation pipelines within a single stage on the same set of input documents:
// { "status" : "A", "v" : 3 }
// { "status" : "B", "v" : 14 }
// { "status" : "A", "v" : 7 }
// { "status" : "A", "v" : 5 }
db.collection.aggregate(
{ $match: { status: "A"} },
{ $facet: {
count: [{ $count: "count" }],
sample: [{ $limit: 2 }]
}}
)
// {
// "count" : [ { "count" : 3 } ],
// "sample" : [ { "status" : "A", "v" : 3 }, { "status" : "A", "v" : 7 } ]
// }
This:
starts by
match
ing documents whosestatus
isA
.and then produces via a
$facet
stage two fields that out of two distinct aggregation pipelines:$count
that simply provides the number of documents resulting from the preceding$match
stage.sample
that is a$limit
ed extract of documents resulting from the preceding$match
stage.
Unfortunately, right now you have to make two calls, one call with the $limit operator for your results followed by a second call for the count. You could use the aggregation framework without the $limit operator and with a $group operator to calculate a count or as wdberkeley points out you can pass your criteria to .count() to get a count instead of using the aggregation framework if you are using a single match stage.
See MongoDB - Aggregation Framework (Total Count).