Grails Mongo低级API [英] Grails Mongo Low Level API

查看:97
本文介绍了Grails Mongo低级API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用Mongo低级API时,groovy代码中的这一行相当于什么?

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆