Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB - Aggregation Framework (Total Count)

When running a normal "find" query on MongoDB I can get the total result count (regardless of limit) by running "count" on the returned cursor. So, even if I limit to result set to 10 (for example) I can still know that the total number of results was 53 (again, for example).

If I understand it correctly, the aggregation framework, however, doesn't return a cursor but simply the results. And so, if I used the $limit pipeline operator, how can I know the total number of results regardless of said limit?

I guess I could run the aggregation twice (once to count the results via $group, and once with $limit for the actual limited results), but this seems inefficient.

An alternative approach could be to attach the total number of results to the documents (via $group) prior to the $limit operation, but this also seems inefficient as this number will be attached to every document (instead of just returned once for the set).

Am I missing something here? Any ideas? Thanks!

For example, if this is the query:

db.article.aggregate(
    { $group : {
        _id : "$author",
        posts : { $sum : 1 }
    }},
    { $sort : { posts: -1 } },
    { $limit : 5 }
);

How would I know how many results are available (before $limit)? The result isn't a cursor, so I can't just run count on it.

like image 390
Assaf Hershko Avatar asked Jul 20 '13 23:07

Assaf Hershko


People also ask

Can we use count with aggregate function in MongoDB?

The MongoDB $count operator allows us to pass a document to the next phase of the aggregation pipeline that contains a count of the documents. There a couple of important things to note about this syntax: First, we invoke the $count operator and then specify the string.

Where is total count in MongoDB?

count() method is used to return the count of documents that would match a find() query. The db. collection. count() method does not perform the find() operation but instead counts and returns the number of results that match a query.

How do I count the number of documents in MongoDB?

n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB® C++ interface connection. n = count( conn , collection ,Query= mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.


1 Answers

$facets aggregation operation can be used for Mongo versions >= 3.4. This allows to fork at a particular stage of a pipeline in multiple sub-pipelines allowing in this case to build one sub pipeline to count the number of documents and another one for sorting, skipping, limiting.

This allows to avoid making same stages multiple times in multiple requests.

like image 177
Hugo LEFEBVRE Avatar answered Sep 30 '22 15:09

Hugo LEFEBVRE