英文:
Mongodb get number of results
问题
我在查找如何获取查询结果中文档数量方面遇到了问题。目前我只能使用以下代码:
long count = collection.countDocuments();
但是这种方式的结果始终相同。
我的下一个命令是分页:
FindIterable<Document> iterDoc = collection.find(query).skip(skip).limit(size);
但我想知道来自以下查询的结果数量:
collection.find(query)
但对于FindIterable文档,没有countDocuments()
函数。我的目标是要知道我的分页所需的页数。是否有一些用于计算结果数量的MongoDB函数?
谢谢,对不起我的英语。
英文:
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.
My next command is pagination
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.
答案1
得分: 1
你可以编写类似这样的函数:
public long getFieldCountInCollection(String field, Object value) {
BasicDBObject query = new BasicDBObject();
query.put(field, value);
return mongoCollection.count(query);
}
注意,参数 field 表示集合中的键名,而 value 表示集合中存在的预期值。如果没有满足条件的记录,调用该函数将会返回 0。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论