Reputation: 1507
I cannot for the life of me find out how to get a count for a find query using the java driver in mongo db. Can someone please put me out of my misery?
I have the following:
MongoCursor<Document> findRes = collection.find().iterator();
But there is no count method that I can find anywhere.
Upvotes: 3
Views: 12249
Reputation: 41
long rows = db.getCollection(myCollection).count(new Document("_id", 10)) ;
this is in Java, myCollection
is collection name.
Upvotes: 3
Reputation: 1960
MongoDB has inbuilt method count()
that can be called on cursor to find the number of documents returned.
I tried following piece of code in mongodb, that worked well, can be easily applied in java or any other language too:
var findres = db.c.find()
findres.count()
gave output 29353
Upvotes: 0
Reputation:
public Long getTotalCount(String collectionName, Document filterDocument) {
MongoCollection collection = database.getCollection(collectionName);
return filterDocument != null ? collection.count(filterDocument) : collection.count();
}
Where filterDocument is org.bson.Document with filter criterias or null if you want to get total count
You may also use more powerful Filters
class. Example: collection.count(Filters.and(Filters.eq("field","value"),second condition and so on));
So, in order to be able to take both Document and Filters as param you may change signature to public Long getTotalCount(String collectionName, Bson filterDocument) {
Upvotes: 7
Reputation: 1142
cursor.count()
is what you're looking for I believe. Your find query returns a Cursor
so you can just call count()
on that.
Upvotes: 0