discodowney discodowney - 1 year ago 121
Java Question

MongoDB - How to get the count for a find query

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.

Answer Source
 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) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download