Tropical Software Observations

04 August 2009

Posted by Irregular Zero

at 4:28 PM

0 comments

Labels: , ,

Groovy Tutorial for MongoDB

Java Tutorial (http://www.mongodb.org/display/DOCS/Java+Tutorial)

Since Groovy is based on Java, you can make use of the Java driver for MongoDB as well as go through the tutorial shown above. The code can be used as-is or modified to look more groovy.

Create a groovy file (mongo.groovy) and place the Java driver in the same directory. Edit it so the code looks like:

this.class.classLoader.rootLoader.addURL(new File("mongo-0.6.jar").toURL())

import com.mongodb.*

DBAddress address = new DBAddress("localhost", "mydb")
Mongo db = new Mongo(address)
db.authenticate('testUser', 'testPassword')

DBCollection coll = db.getCollection("testCollection")

BasicDBObject doc = new BasicDBObject()
doc.put("name", "MongoDB")
doc.put("type", "database")
doc.put("count", 1)

BasicDBObject info = new BasicDBObject()
info.put("x", 203)
info.put("y", 102)
doc.put("info", info)

coll.insert(doc)

for(i in 1..100) {
coll.insert(new BasicDBObject().append("i", i))
}

println coll.getCount()

DBCursor cursor = coll.find()
while(cursor.hasNext()) {
println cursor.next()
}

You can see it's just a rehash of part of the Java tutorial, the output will be a count of the number of inserted objects followed by the objects themselves.

The first line of code loads the jar file, this is useful if you're not looking to put the jar in a classpath or one of groovy's configured library paths like '~/.groovy/lib'.

Running the script is accomplished by 'groovy mongo.groovy' in the terminal. You can also type in 'groovyConsole' to load the console then opening the script and running inside it.

0 comments: