How to get the score to the 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 collections before applying the limit? I still want the call to return an array of 5 documents. If I use $ group, it seems that it will not save the array of documents. Can this be done in one call, or do I need to make two calls?

+7
count mongodb limit aggregation-framework
source share
2 answers

Unfortunately, right now you need to make two calls, one call with the $ limit operator for your results, followed by a second call for the account. You can use the aggregation structure without the $ limit operator and with the $ group operator to calculate the counter or, as indicated in wdberkeley, you can pass your criteria to .count () to get the score instead of using the aggregation structure if you use one stage of the match.

See MongoDB - Aggregation Structure (Total) .

+3
source share

Another option is to limit the results at the application level, rather than in the Mongo query. Then you can get a count of the full result, and you do not need to make two calls.

For example, in Python you would do:

 data = db.orders.aggregate([{ "$match" : { "status": "A"} }])['result'] count = len(data) data = data[skip:skip+limit] 

If you have a complex shared call on a large dataset, this is significantly faster than making two calls.

-one
source share

All Articles