Reputation: 356
I am trying to count the results of a find()
method, but it doesn´t work. I am using the mongodb-driver-3.2.2
and mongodb-driver-core-3.2.2
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 find()
method, it doesn´t work:
long a = collection.find(eq("status", 1)).count();
Error:
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 ) {
a++;
}
I DON´T like this solution. Is there a other solution to count the results?
Upvotes: 1
Views: 996
Reputation: 3554
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));
Upvotes: 1