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());
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.
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.
The aggregation query takes ~80ms while the find query takes 0 or 1ms.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With