Freundlicher Freundlicher - 1 year ago 146
Java Question

MongoDB java-driver-3.2.2 count results from find()-method

I am trying to count the results of a

method, but it doesn´t work. I am using the
for JAVA.

This is the code I am using to connect to the MongoDB

MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("database_name");
MongoCollection<Document> collection = database.getCollection("collection_name");

I search in the MongoDb with this code:

collection.find(eq("status", 1));

The method ".count()" work only for the whole collection, like this:

long a = collection.count();

But when i try to us it in combination with the
method, it doesn´t work:

long a = collection.find(eq("status", 1)).count();


The method count() is undefined for the type FindIterable<Document>

So, my solution is:

long a = 0;
FindIterable<Document> results = collection.find(eq("status", 1));
for (Document current : results ) {

I DON´T like this solution. Is there a other solution to count the results?

mtj mtj
Answer Source

Count is a method on the collection object, not on the FindIterable. It takes the filter as an optional parameter, so to stay in the Filters-world:

collection.count(eq("status", 1));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download