Anonymous Human
Anonymous Human

Reputation: 1948

Grails Mongo Low Level API

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" : ""
}

Upvotes: 1

Views: 243

Answers (2)

user3578266
user3578266

Reputation:

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.

Upvotes: 1

Lalit Agarwal
Lalit Agarwal

Reputation: 2354

Try below code and see if it works.

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

def cursor = coll.find(query)

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

For more info look here: http://docs.mongodb.org/ecosystem/tutorial/getting-started-with-java-driver/

Upvotes: 0

Related Questions