【问题标题】:Grails Mongo Low Level APIGrails Mongo 低级 API
【发布时间】:2014-06-24 16:55:24
【问题描述】:

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

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

这一行成功地在 Mongo shell 中为我找到了合适的记录,但我在我的控制器方法中尝试了它的许多变体,但我一直得到 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" : ""
}

【问题讨论】:

  • 你能粘贴你的控制器代码吗?
  • @Lalit Agarwal 已按要求更新。
  • @Christian P 如果我尝试打印'null'。

标签: mongodb grails


【解决方案1】:

试试这个:

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

效率低下,每次都必须遍历整个集合才能找到记录,但最终会以'obj'作为您需要的记录。

【讨论】:

    【解决方案2】:

    试试下面的代码,看看它是否有效。

    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/

    【讨论】:

    • cusor.next() 给出 null。
    猜你喜欢
    • 2020-07-03
    • 2017-12-10
    • 2018-04-10
    • 2011-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-30
    • 2017-09-29
    相关资源
    最近更新 更多