MongoDB made more Groovy

Posted     

The session after mine here at RuPy was MongoDB presented by Mike Dirlof(@mdirlof). I looked at the Java examples yet they left a bit to be desired as they had the usual Java verbosity problems. One of the cooler lesser known things about Groovy is that Groovy can coerce objects to a specific interface. We use this alot for one-off WindowListerners interfaces and such. That same concept can be applied to the classes as well. We can take code from the Java MongoDB tutorial to make it more Groovy.

import com.mongodb.*

def m = new Mongo()

def db = m.getDB("mydb")
def coll = db.getCollection("testCollection")

coll.drop()
 
def doc = [name:"MongoDB", type:"database", count:1,
            info: [x:203, y:102]
          ] as BasicDBObject
def doc2 = [name:"MongoDB2", type:"database", count:2,
    info: [x:203, y:102] ] as BasicDBObject

    
coll.insert(doc)
coll.insert(doc2)

println coll.getCount()

def obj = coll.findOne([count:1] as BasicDBObject)
println obj

println "showing a custom query"
def cur = coll.find([count:['$lt':3]] as BasicDBObject)
while(cur.hasNext()) {
    println cur.next()
}

Because MongoDB's BasicDBObject is a subclass of HashMap, we can produce concise code that looks closer to the Ruby, Python, and Javascript examples Matt has presented. We can also nest documents within documents, turtles all the way down. Only the othermost document needs to be cast, the rest get cast to documents automatically. It seems that MongoDB's special params begin with a dollar sign ($gt, $lt, etc) need to be passed as a String literal with apostrophes.


Comments

  1. Tomash said:

    You should sooo make it a Groovy MongoDB driver (with Java driver as dependency) -- I'd love to have Grails capable of interfacing with MongoDB in a nice way (just put it in DataSource and let's roll)
  2. Mike Dirolf said:

    +1
  3. Fengbo Xie said:

    +1, that will be fantastic
  4. Paulo Poiati said:

    Very nice! But GMongo do all that stuff for you. Take a look: http://blog.paulopoiati.com/2010/06/20/gmongo-0-5-released/
  5. lainferoce said:

    +1
blog comments powered by Disqus