我正在尝试计算 find()
方法的结果,但它不起作用。我正在使用 JAVA 的 mongodb-driver-3.2.2
和 mongodb-driver-core-3.2.2
。
这是我用来连接到 MongoDB 的代码
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("database_name");
MongoCollection<Document> collection = database.getCollection("collection_name");
我使用以下代码在 MongoDb 中搜索:
collection.find(eq("status", 1));
方法“.count()”仅适用于整个集合,如下所示:
long a = collection.count();
但是当我尝试将它与 find()
方法结合使用时,它不起作用:
long a = collection.find(eq("status", 1)).count();
错误:
The method count() is undefined for the type FindIterable<Document>
所以,我的解决方案是:
long a = 0;
FindIterable<Document> results = collection.find(eq("status", 1));
for (Document current : results ) {
a++;
}
我不喜欢这个解决方案。还有其他解决方案来计算结果吗?
最佳答案
Count 是集合对象上的方法,而不是 FindIterable 上的方法。它将过滤器作为可选参数,因此留在过滤器世界中:
collection.count(eq("status", 1));
关于java - MongoDB java-driver-3.2.2 计数 find() 方法的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37722238/