获取Mongodb结果数量

huangapple go评论76阅读模式
英文:

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&lt;Document&gt; 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.

huangapple
  • 本文由 发表于 2020年5月4日 22:51:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/61595090.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定