MongoDB plugin for Griffon
A couple of weeks ago, I showed how you could make MongoDB a bit more Groovy. In this post, I'll be covering a preview release of the Mongo DB plugin. Behind the scenes, this plugin uses Guice for Dependency Injection.
Getting started:
Install the mongodb plugin:
griffon install-plugin mongo-db
In your conf directory create a file named MongoConfig.groovy listing the database connection details, like this:
mongo {
host="localhost"
port=27017
dbName="mine"
collectionName="testcoll"
}
Add the following bit to your Application.groovy file:
guice {
modules = [ "MongoModule"]
}
MongoModule.groovy is provided by the plugin. Getting a collection Collections are the approximate equivalent to a RDBMS table. Collections will be wh2ere you do most of your work. We can get a reference to a collection by adding @Inject MongoDBCollectionFactory factory to our controller and calling injector.injectMembers(this). Guice uses the settings in MongoConfig to properly wire our Mongo and DB instance giving us a CollectionFactory. Let's make a collection called posts and populate a couple of documents:
def coll2 = factory.getCollection("posts")
coll2.insert(['title':'Whatever', 'postcreated':new Date(), 'comments':[
'text':'A sample comment','datecreated':new Date(109,10,13)]] as BasicDBObject)
coll2.insert(['title':'Whatever1', 'postcreated':new Date()] as BasicDBObject)
coll2.insert(['title':'Whatever3', 'postcreated':new Date()] as BasicDBObject)
Dynamic Finders
Just before the factory returns the collection, it decorates it with code to generate GORM-like dynamic finders with operators like LessThan, LessThanEquals, GreaterThan, NotEqual, etc. Let's query our collection for all posts with a specific title:
def cursor3 = coll2.findByTitle('Whatever')
The return value is a DBCursor that we can iterate though. In addition to dynamic finders, the MongoDB plugin allows you to access child documents. This is extra useful because Mongo usually stores related documents as child documents of a parent. An underscore between two property names indicates a property on a sub-document. So if you wanted to find the comments created on a specific date. You'd use a query like this:
coll.findByComments_DateCreated(new Date('2009-10-10'))
This plugin, codenamed MonGorm, is a preview release so everything isn't fully baked. Comments/feedback welcome (emails/tweets better than comments on this post)