Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoCursor has no count() method?

So my code is:

FindIterable<Document> findIterable = collection.find().skip(20).limit(10);
MongoCursor<Document> cursor = findIterable.iterator();
while (cursor.hasNext()) {
    Document doc = cursor.next();
    // My stuff with documents here
}
cursor.close(); // in finally block

Now I want to know the total count of documents before skip and limit.

There is an answer for exact same question, but I have mongo-java-driver v3.1.0 and API I use is different. There is no methods count() or size() in both FindIterable and MongoCursor classes. Thanks!

UPDATE

Seems like the only workaround is making another call to mongodb: collection.count as said @Philipp

like image 705
alaster Avatar asked Aug 05 '26 07:08

alaster


2 Answers

The count method can now be found in MongoCollection:

int count = collection.count();

returns the total number of documents in a collection.

int count = collection.count(criteria);

returns the number of documents in a collection which match the given criteria.

like image 119
Philipp Avatar answered Aug 07 '26 20:08

Philipp


You should use MongoCollection.countDocuments(Bson filter) to calculate exact number of documents. You can also pass additional param CountOptions options and specify offset, limit. MongoCollection.countDocuments

If you need faster response and the exact number is not a must you can also use MongoCollection.estimatedDocumentCount() MongoCollection.estimatedDocumentCount

like image 37
Kacper Cichecki Avatar answered Aug 07 '26 20:08

Kacper Cichecki