discodowney
discodowney

Reputation: 1507

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.

Upvotes: 3

Views: 12249

Answers (4)

Appala
Appala

Reputation: 41

long rows = db.getCollection(myCollection).count(new Document("_id", 10)) ;

this is in Java, myCollection is collection name.

Upvotes: 3

Kamal Nayan
Kamal Nayan

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

user2104560
user2104560

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

Oli
Oli

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

Related Questions