Using MongoDB with GroovyJames Williams (@ecspike)BT/Ribbit
Just as NoSQL is...
• post - relational• schemaless• flexible
Groovy is ...
• a superset of Java• open to metaprogramming• a more concise way to write code
Groovy + Mongo
• JavaBasicDBObject doc = new BasicDBObject();doc.put("name", "MongoDB");doc.put("type", "database");doc.put("count", 1);coll.insert(doc);
• Groovierdef doc = [name:"MongoDB", count:1,type:"database", info: [x:203, y:102] ] as BasicDBObjectcoll.insert(doc)
• Grooviest (using groovy-mongo)coll.insert([name:"MongoDB", type:"database", info: [x:203, y:102]])
Dynamic Finders
• let you query the database as if there was a schema• build complex query functions at runtime
Ex. collection.findByAuthorAndPostCreatedGreaterThan(...) collection.findByComments_CreatedOn(...)
How dynamic finders work
1. Groovy tries to execute the function but can't find it2. It invokes methodMissing instead3. The body of methodMissing takes the attempted method
name and parses it4. It uses the names and the modifiers (>, <, etc) with
BasicDBObjectBuilder to create a prototype5. It caches the created function under that name and runs it. 6. Further invocations don't incur the performance hit.
Groovy + Mongo in the wild
Links
• Andrill: http://andrill.org• CoreRef: http://coreref.org• groovy-mongo: http://github.com/jwill/groovy-mongo
• Personal Blog: http://jameswilliams.be/blog• Twitter: @ecspike