4 Low-level API - Reference Documentation
Authors: Graeme Rocher, Burt Beckwith
Version: 1.1.0.GA
4 Low-level API
A lower level API is provided by the plugin that is based on the GMongo project.GMongo is a simple Groovy wrapper around the regular Mongo Java Driver. In general you can refer to the Mongo Java Drivers Javadoc API when using GMongo.GMongo provides some nice enhancements like easy access to collections using the dot operator and support for Groovy operator overloading.There is an excellent tutorial on how to use the Mongo Java driver's API directly in the Mongo documentationAn example of GMongo usage can be seen below:
// Get a db reference in the old fashion way def db = mongo.getDB("gmongo")// Collections can be accessed as a db property (like the javascript API) assert db.myCollection instanceof com.mongodb.DBCollection // They also can be accessed with array notation assert db['my.collection'] instanceof com.mongodb.DBCollection// Insert a document db.languages.insert([name: 'Groovy']) // A less verbose way to do it db.languages.insert(name: 'Ruby') // Yet another way db.languages << [name: 'Python']// Insert a list of documents db.languages << [[name: 'Javascript', type: 'prototyped'], [name: 'Ioke', type: 'prototyped']]
mongo instance (which is an of the com.mongodb.Mongo class) inside a controller or service simple define a mongo property:def mongo
def myAction = {
def db = mongo.getDB("mongo")
db.languages.insert([name: 'Groovy'])
}databaseName config option, plus the suffix "DB").def peopleDB
def myAction = {
peopleDB.languages.insert([name: 'Fred'])
}collection property that allows easy access to the underlying DBCollection instance and hence the GMongo API:Person.collection.count() == 1 Person.collection.findOne(firstName:"Fred").lastName == "Flintstone"
If you are using Hibernate entities with Mongo then the collection will be scoped in the mongo namespace. Example: Person.mongo.collection.count()
You can easily convert from a native MongoDB DBObject into an entity using a cast:def fred = Person.collection.findOne(firstName:"Fred") as Person