2014-06-24 47 views
1

當使用Mongo低級API時,Groovy代碼中的這一行等價於什麼?Grails Mongo低級API

db.countrycodes.findOne({"Country":"Antarctica"}) 

此行成功地找到相應的記錄,我在蒙戈外殼,但我想在我的控制方法,它的許多變化,我不斷收到NULL。繼承人是我這失敗當前的嘗試:

MongoClient mongoClient = new MongoClient("localhost", 27017) 
    DB db = mongoClient.getDB("twcdb"); 
    DBCollection coll = db.getCollection('countrycodes') 
    println coll.find("Country":"Antarctica") 

我知道我的收藏和DB非NULL,因爲當我做find()我得到一個有效的光標回來,通過它我可以打印第一個記錄集。這裏是我試圖找到的記錄:

{ 
    "_id" : ObjectId("539848b2119918654e7e90b1"), 
    "Country" : "Antarctica", 
    "Alpha2" : "AQ", 
    "Aplha3" : "ATA", 
    "Numeric" : "10", 
    "FIPS" : "AY", 
    "IGA" : "" 
} 
+0

你可以粘貼你的控制器代碼嗎? –

+0

@Lalit Agarwal發佈更新按要求。 –

+0

@Christian P如果我嘗試打印'null'。 –

回答

1

試試這個:

def cursor = coll.find() 
    def obj = cursor.next() 
    while (obj.Country != 'Antarctica') { 
     obj = cursor.next() 
    } 

這是低效的,你將不得不遍歷整個集合每次來查找記錄,但它會結束'obj'是你需要的記錄。

0

請嘗試下面的代碼,看看它是否工作。

BasicDBObject query = new BasicDBObject("Country", "Antartica"); 

def cursor = coll.find(query) 

try { 
    while(cursor.hasNext()) { 
    System.out.println(cursor.next()); 
    } 
} finally { 
    cursor.close(); 
} 

欲瞭解更多信息請看這裏:http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

+0

cusor.next()給出null。 –