Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call count operation after find with mongodb java driver

Tags:

I am using MongoDB 3.0. suppose there is a set of documents named photos, its structure is

{"_id" : 1, photographer: "jack"}

with database.getCollection("photos"), Mongodb will return a MongoCollection object, on which I have the method count() to get the number documents returned.

However, when I make queries with specific conditions. For example find documents with id smaller than 100 :

photosCollections.find(Document.parse("{_id : {$lt : 100}}"))

Above find method will always return a cursor which doesn't provide a count() function. So how can I know how many documents returned ? I know on command line, I can use

db.photos.find({_id : {$lt : 100}}).count()

Of course, I can go through the iterator and count the number of documents myself. However I find it really clumsy. I am wondering does MongoDB java driver provides such functionality to count the number of documents returned by the find() method ? If not, what is the reason behind the decision ?

like image 938
Ensom Hodder Avatar asked Sep 20 '15 19:09

Ensom Hodder


People also ask

How do I count data in MongoDB?

Description. n = count( conn , collection ) returns the total number of documents in a collection by using the MongoDB connection. n = count( conn , collection ,'Query', mongoquery ) returns the total number of documents in an executed MongoDB query on a collection.

How do I count rows in MongoDB?

count() method is used to return the count of documents that would match a find() query. The db. collection. count() method does not perform the find() operation but instead counts and returns the number of results that match a query.

Which function in MongoDB is used to count the records?

MongoDB count() Method – db. Collection. count() The count() method counts the number of documents that match the selection criteria.


Video Answer


1 Answers

As you said the MongoCollection has the count() method that will return the number of documents in the collection, but it has also a count(Bson filter) that will return the number of documents in the collection according to the given options.

So you can just use:

long count = photosCollections.count(Document.parse("{_id : {$lt : 100}}"))

or maybe clearer:

Document query = new Document("_id", new Document("$lt", 100));
long count = photosCollections.count(query);

ref: http://api.mongodb.com/java/3.3/com/mongodb/client/MongoCollection.html#count-org.bson.conversions.Bson-

like image 195
Enrichman Avatar answered Oct 07 '22 09:10

Enrichman