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
You can use this :
(mongo).getCollection().count(findArgs);
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
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);
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");
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