Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FindIterable<Document> how to get total records in a result of a query

Tags:

java

mongodb

I was using mongo driver for java 2.x and passed to 3.1. DBCursor is deprecated and I had to use the FindIterable<Document> structure.

When I perform a query

FindIterable<Document> cursor=(mongo).getCollection().find(findArgs).limit(10).skip(0);

I would like to get the count of the total number of records in the resultset with the query find in only one Query.

How can I retrieve the count without performing another query? I'm not speaking of the 10 records in the limit but of the total number of records.

I want to perform one query to retrieve count and find. I don't want to execute find and count.

Thanks

like image 662
jeorfevre Avatar asked Nov 17 '15 15:11

jeorfevre


4 Answers

You can use this :

(mongo).getCollection().count(findArgs);
like image 114
user3693142 Avatar answered Nov 13 '22 13:11

user3693142


FindIterable is basically an iterator. Iterators do not know the total size of the elements they will return. The best way I have found to do this is to create a single "query map" but with two query operations (a find and a count).

Something like this (groovy):

Map query = [_id: [$in:idList]]

FindIterable userList = User.collection.find(query).skip(offset).limit(max)

Integer totalCount = User.collection.count(query)

I know that this was not what you where after, but I believe what you want is not possible.

Another way would be to use aggregation (mongodb version 3.4+), but not sure if that would be better for you. Here

like image 24
Eduardo Mayer Avatar answered Nov 13 '22 13:11

Eduardo Mayer


This is an old question. A typical answer is to use the count() method. However it's not always a preferred method considering performance.

To execute count() method, the MongoDB server has to iterate over all the documents that matches the filter. It will be extremely slow and uses lots of load if the total-matching document number is large, and the winning plan is not an optimal one.

A common strategy, is to projection the result to help MongoDB optimize winning plan. Thus, very likely, the winning plan is an optimal one. It will faster than pure count().

Then, using Iterable size method (e.g. the one from guava), the code looks like:

Iterable<?> it = table.find(filterBson).projection(new Document("_id", 1));
int count = Iterables.size(it);
like image 1
JieYuan Shen Avatar answered Nov 13 '22 12:11

JieYuan Shen


There is count method available. It's accepts Bson filter. So after getting the collection object, you can directly put the count function.

MongoCollection<Document> collection = db.getCollection(collectionName);
long totalFilteredRecords = collection.count("field","value");
like image 1
user1370393 Avatar answered Nov 13 '22 11:11

user1370393