2013-04-18 54 views
0

我只是想这个简单的事情,但日食不会让我使用find()方法,我不明白为什么cuz这是它在mongodb.org解释的方式..有人可以看到我做错了什么?其folk.find()方法,只要我不把任何条件,以有工作(NAMN:“罗伯特”)在MongoDB中的SQL查询

Mongo mongo= new Mongo(); 
DB db = mongo.getDB("Helly"); 
long startTime= System.currentTimeMillis(); 
DBCollection folk = db.getCollection("folk"); 
BasicDBObject document = new BasicDBObject(); 
document.put("namn", "Robert"); 
document.put("efternamn", "Brismo"); 
document.put("ålder", 34); 

BasicDBObject documentDetail = new BasicDBObject(); 
documentDetail.put("ålder", 47); 
documentDetail.put("hårfärg", "brun"); 
documentDetail.put("skostorlek", "44"); 

document.put("Utseende", documentDetail); 
folk.insert(document); 
DBCursor cursor= folk.find({namn:"Robert"}); 
while(cursor.hasNext()){ 
DBObject obj=cursor.next(); 
System.out.println(obj);} 
+0

mongodb.org上的哪些Java文档以您展示的方式显示“find”? JavaScript会以这种方式工作。 – WiredPrairie

+0

哦好吧,所以这是为JavaScript ..?你知道在Java中是否有这样做的方法?我有一堆针对SQL数据库的SQL查询,并且希望在mongoDB中使用相同的问题,因为我将数据从SQL服务器移动到Mongo。你有什么建议吗?即时在Eclipse中使用Java现在。 – glaring

+0

我添加了一个如何在Java中查找的答案。 – WiredPrairie

回答

0

要做到与namn一个查询发现,你需要使用的BasicDBObject实例,并使用它作为查询:

BasicDBObject query = new BasicDBObject("namn", "Robert"); 
DBCursor cursor= folk.find(query); 
try { 
    while(cursor.hasNext()) { 
     // .. do something 
     System.out.println(cursor.next()); 
    } 
} 
finally { 
    cursor.close(); 
} 

Getting Started Documentation

+0

谢谢这么多,它的作品! – glaring

0

另一种选择是使用的QueryBuilder类,如下所示。

// Connect to the Mongo database 
Mongo mongoConn = new Mongo("localhost", 27017); 
DB mongoDb = mongoConn.getDB("TESTDB"); 
DBCollection collection = mongoDb.getCollection("folk"); 

// Building the query parameters 
QueryBuilder qFinder= new QueryBuilder(); 
qFinder.put("name").is("Robert"); 

// Fetching the records for the query. get() method will convert QueryBuilder -> DBObject class of query parameters 
DBCursor dbCursor = collection.find(qFinder.get()); 

while(dbCursor.hasNext()) { 
// Do something with the code 
System.out.println(dbCursor.next()); 
} 

Querybuilder的优势在于您可以轻松链接查询。qFinder.put( “名称”)为( “罗伯特”)和( “时代”)GT(25)。等等。 请参考:My Blog Post