我正在尝试使用以下代码构建一个简单的mongodb数据库查找。在运行时,代码运行但从不返回值。
生成的查询在命令行中工作没问题。数据库非常大,大约2.8gb。
public static void main(String[]args){
String customer="peter";
String job="builder";
// To connect to mongodb server
MongoClient mongoClient=new MongoClient("localhost",27017);
// Now connect to your databases
MongoDatabase db=mongoClient.getDatabase("customers");
System.out.println("Connect to database successfully");
// Now connect to your collection
MongoCollection<Document> collection=db.getCollection("customerData");
System.out.println("Connect to collection");
BasicDBObject andQuery=new BasicDBObject();
List<BasicDBObject> obj=new ArrayList<BasicDBObject>();
obj.add(new BasicDBObject("job",job));
obj.add(new BasicDBObject("customer",customer));
andQuery.put("$and",obj);
System.out.println(andQuery.toString());
FindIterable<Document> iterable=collection.find(new Document(andQuery));
MongoCursor<Document> iterableDocument=iterable.iterator();
while(iterableDocument.hasNext()){
Document wholeDocument=(Document)iterableDocument.next();
System.out.println("1: "+wholeDocument.get("age"));
System.out.println("2: "+wholeDocument.get("dob"));
}
}
答案 0 :(得分:0)
尝试将查询简化为
DBObject obj = new BasicDBObject();
obj.put( "job", job );
obj.put( "customer", customer );
collection.find(new Document(obj))
此外,getDatabase和getCollection不进行连接。如果拼错了这些部分,查询将不返回任何内容,因为您正在访问空数据库。 (第一次连接尝试是当你调用'find'时。如果数据库或集合不存在,Mongo会在你写入时创建它)