Grails Mongo低级API [英] Grails Mongo Low Level API
问题描述
db.countrycodes。 findOne({Country:Antarctica})
该行成功找到合适的记录在Mongo shell中,但我在我的控制器方法中尝试了很多变体,我一直得到NULL。 Heres是我当前正在失败的尝试:
$ b $ pre $ MongoClient mongoClient =新的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,
数字:10,
FIPS:AY,
IGA:
}
试试这个:
def cursor = coll.find()
def obj = cursor.next()
while(obj.Country!='Antarctica'){
obj = cursor.next()
}
效率低下,您必须每次遍历整个集合以查找记录,但最终会以'obj'为结尾你需要的记录。
What would be the equivalent of this line in groovy code when using the Mongo low level API?
db.countrycodes.findOne({"Country":"Antarctica"})
This line successfully finds the appropriate record for me in the Mongo shell but I tried many variations of it in my controller method and I keep getting NULL. Heres is my current attempt which is failing:
MongoClient mongoClient = new MongoClient("localhost", 27017)
DB db = mongoClient.getDB("twcdb");
DBCollection coll = db.getCollection('countrycodes')
println coll.find("Country":"Antarctica")
I know my collection and db is non NULL because when I do find()
I do get a valid cursor back through which I can print the first record in collection. Here is the record I am trying to find:
{
"_id" : ObjectId("539848b2119918654e7e90b1"),
"Country" : "Antarctica",
"Alpha2" : "AQ",
"Aplha3" : "ATA",
"Numeric" : "10",
"FIPS" : "AY",
"IGA" : ""
}
Try this:
def cursor = coll.find()
def obj = cursor.next()
while (obj.Country != 'Antarctica') {
obj = cursor.next()
}
It is inefficient, you will have to traverse the whole collection everytime to find a record, but it will end up with 'obj' being the record you need.
这篇关于Grails Mongo低级API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!