James Williams
LinkedInMastodonGithub

MongoDB made more Groovy

The session after mine here at RuPy was MongoDB presented by Mike Dirlof(@mdirolf). 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.