我正在尝试计算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));
试试这个:
collection.count(new Document().append("status",1));