Grails Mongo Low Level API



当使用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" : ""
}

试试这个:

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

这是低效的,你将不得不遍历整个集合每次找到一个记录,但它将结束'obj'是你需要的记录

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

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/

最新更新