Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb get count without repeating find

Tags:

count

mongodb

When performing a query in MongoDb, I need to obtain a total count of all matches, along with the documents themselves as a limited/paged subset.

I can achieve the goal with two queries, but I do not see how to do this with one query. I am hoping there is a mongo feature that is, in some sense, equivalent to SQL_CALC_FOUND_ROWS, as it seems like overkill to have to run the query twice. Any help would be great. Thanks!

EDIT: Here is Java code to do the above.

     DBCursor cursor = collection.find(searchQuery).limit(10);
     System.out.println("total objects = " + cursor.count());
like image 515
adamSpline Avatar asked Jun 05 '12 01:06

adamSpline


People also ask

How do I count unique values in MongoDB?

To count the unique values, use "distinct()" rather than "find()", and "length" rather than "count()". The first argument for "distinct" is the field for which to aggregate distinct values, the second is the conditional statement that specifies which rows to select.

How do you prevent duplicates in MongoDB?

While you cannot prevent entries with duplicated data. You can query/aggregate the data in such a way that replicated data is ignored. On the same $group stage you could pick up the max, min, avg etc for a given entry.

Which is faster in find and aggregate in MongoDB?

The aggregation query takes ~80ms while the find query takes 0 or 1ms.


1 Answers

I'm not sure which language you're using, but you can typically call a count method on the cursor that's the result of a find query and then use that same cursor to obtain the documents themselves.

like image 72
JohnnyHK Avatar answered Oct 02 '22 10:10

JohnnyHK