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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With