Search code examples
mongodbcountlimitaggregation-framework

How to get count before limit in the Mongo aggregation pipeline


In the following query:

db.orders.aggregate([{ $match : { status: "A"}, { $limit: 5} }]);

How can I get the count of documents after the $match but before the $limit is applied?

I still want to return an array of 5 documents. But if I use $group it seems that it would not preserve the array of documents. Can this be done in one call, or do I have to make two calls?


Solution

  • 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).