Issue
I am having trouble with finding out how to get a number of documents in my result from the query. All I can do now is
long count = collection.countDocuments();
Result from this is always same.
FindIterable<Document> iterDoc = collection.find(query).skip(skip).limit(size);
But I want to know the number of results from
collection.find(query)
But for the FindIterable document there isn't countDocuments()
function. The point of this is I want to know a number of pages for my pagination. Is there some MongoDB function for counting results?
Thank you and sorry for my English.
Solution
You can write a function something like this
public long getFieldCountInCollection(String field, Object value) {
BasicDBObject query = new BasicDBObject();
query.put(field, value);
return mongoCollection.count(query);
}
Note that the parameter field denotes the key name that you have in your collection, and the value denotes the expected value that is present in the collection. If there is no such record meeting the condition, you will get 0 as the result of this function call.
Answered By - Ajay Kr Choudhary
Answer Checked By - Robin (JavaFixing Admin)