MongoDB java-driver-3.2.2 计算 find() 方法的结果
MongoDB java-driver-3.2.2 count results from find()-method
我正在尝试计算 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++;
}
我不喜欢这个解决方案。是否有其他解决方案来计算结果?
试试这个:
collection.count(new Document().append("status",1));
Count 是集合对象上的方法,而不是 FindIterable 上的方法。它将过滤器作为可选参数,因此留在过滤器世界中:
collection.count(eq("status", 1));
我正在尝试计算 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++;
}
我不喜欢这个解决方案。是否有其他解决方案来计算结果?
试试这个:
collection.count(new Document().append("status",1));
Count 是集合对象上的方法,而不是 FindIterable 上的方法。它将过滤器作为可选参数,因此留在过滤器世界中:
collection.count(eq("status", 1));