我在mongodb tutorial for java中发现了如何从mongo集合中查询,但他们使用的 'validators' => array(
'invokables' => array(
//'emailExist' => 'Application\MyValidation\EmailExistValidator',
),
'factories' => array(
'emailExist' => function ($vm) {
$serviceLocator = $vm->getServiceLocator();
$emailExistValidator = new \Application\MyValidation\EmailExistValidator();
$doctrineEntityManager = $serviceLocator->get('Doctrine\ORM\EntityManager');
$emailExistValidator->setObjectManager($doctrineEntityManager);
return $emailExistValidator;
},
),
),
对我不起作用!你知道如何使用mongo和java过滤集合中的文档吗?
这是我的尝试:
eq
我想要类似的东西:
package Database;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class StackOverflow {
public static void main(String[] args) {
// insert something to mongo:
final String URI = "mongodb://localhost:27017";
final String DB = "StackOverflowQuestion";
final String COLLECTION = "eqDoesntExcist";
MongoClientURI connection = new MongoClientURI(URI);
MongoClient mongo = new MongoClient(connection);
MongoDatabase database = mongo.getDatabase(DB);
MongoCollection<Document> collection = database.getCollection(COLLECTION);
Document doc = new Document("name", "Troy").append("height", 185);
collection.insertOne(doc);
doc = new Document("name", "Ann").append("height", 175);
collection.insertOne(doc);
// read something from mongo
FindIterable<Document> findIt = collection.find(eq("name", "Troy"));
// ERROR!!! the method eq(String, String) is undefined!
mongo.close();
}
}
答案 0 :(得分:4)
您可以使用eq
Filter
作为:
Bson bsonFilter = Filters.eq("name", "Troy");
FindIterable<Document> findIt = collection.find(bsonFilter);
或者让它看起来像doc建议的方式包含方法调用的静态导入Filters.eq
import static com.mongodb.client.model.Filters.eq;
并进一步使用与您相同的代码:
FindIterable<Document> findIt = collection.find(eq("name", "Troy")); // static import is the key to such syntax
答案 1 :(得分:0)
你不能这样做:
collection.find(eq("name", "Troy"));
因为编译器会在您的班级StackOverflow
中使用名为eq
的方法,而这不是您需要的方法..
您要查找的内容在Filter class
中定义public static <TItem> Bson eq(String fieldName, Item value)
所以它可能是
collection.find(Filters.eq("name", "Troy"));