1

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

Community
  • 1
  • 1
alaster
  • 3,821
  • 3
  • 24
  • 32

2 Answers2

8

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.

Philipp
  • 67,764
  • 9
  • 118
  • 153
  • Thanks, but is it the only way? I have to make secondary request to mongodb – alaster Nov 23 '15 at 15:15
  • @alaster whatever you do with the cursor would only give you the count of actually returned documents after applying `limit` and `skip`. Counting all documents in the collection without pagination is an entirely different operation and thus requires a separate request. – Philipp Nov 23 '15 at 15:16
  • According to mongodb manual this functionality exists in mongo shell - https://docs.mongodb.org/manual/reference/method/cursor.count/. So maybe there is another solution – alaster Nov 23 '15 at 15:22
  • @alaster Note the wording: "The operation does not perform the query but *instead counts the results that would be returned by the query*". It can not do this without querying the database. This implies that calling the count method does in fact create an additional, independent request to the database. – Philipp Nov 23 '15 at 15:25
  • Ok, I got it. Just want to wait some time for another answers – alaster Nov 23 '15 at 15:27
1

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

Kacper Cichecki
  • 540
  • 5
  • 12