alaster
alaster

Reputation: 4171

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

Upvotes: 2

Views: 4894

Answers (2)

Kacper Cichecki
Kacper Cichecki

Reputation: 680

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

Upvotes: 1

Philipp
Philipp

Reputation: 69663

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.

Upvotes: 8

Related Questions