(Quick Reference)

2 Getting Started - Reference Documentation

Authors: Graeme Rocher, Burt Beckwith

Version: 3.0.0

2 Getting Started

To get started with GORM for Mongo you need configure it as a dependency in BuildConfig.groovy:

plugins {
	compile ':mongodb:3.0.0.RC1' // or whatever is the latest vesrion
}

With that done you need to set up a running MongoDB server. Refer to the MongoDB Quick Start guide for an explanation on how to startup a Mongo instance. Once installed starting Mongo is typically a matter of executing the following command:

MONGO_HOME/bin/mongod

With the above commands executed in a terminal window you should see output like the following appear:

Tue Mar 18 14:16:35.267 [initandlisten] db version v2.4.9
Tue Mar 18 14:16:35.267 [initandlisten] git version: 52fe0d21959e32a5bdbecdc62057db386e4e029c
Tue Mar 18 14:16:35.267 [initandlisten] build info: Darwin bs-osx-106-x86-64-2.10gen.cc 10.8.0 Darwin Kernel Version 10.8.0: Tue Jun  7 16:32:41 PDT 2011; root:xnu-1504.15.3~1/RELEASE_X86_64 x86_64 BOOST_LIB_VERSION=1_49
Tue Mar 18 14:16:35.267 [initandlisten] allocator: system
Tue Mar 18 14:16:35.267 [initandlisten] options: {}
Tue Mar 18 14:16:35.268 [initandlisten] journal dir=/data/db/journal
Tue Mar 18 14:16:35.268 [initandlisten] recover : no journal files present, no recovery needed
Tue Mar 18 14:16:35.297 [websvr] admin web console waiting for connections on port 28017
Tue Mar 18 14:16:35.297 [initandlisten] waiting for connections on port 27017

As you can see the server is running on port 27017, but don't worry the Mongodb plugin for Grails will automatically configure itself to look for Mongodb on that port by default.

If you want to configure how Grails connects to Mongo then you can do so using the following settings in grails-app/conf/DataSource.groovy:

grails {
    mongo {
        host = "localhost"
        port = 27017
        username = "blah"
        password = "blah"
        databaseName = "foo"
    }
}

2.1 Using MongoDB Standalone

If you plan to use MongoDB as your primary datastore then you need to remove the Hibernate plugin from the grails-app/conf/BuildConfig.groovy file by commenting out the hibernate line in the plugins block

compile ':hibernate:3.6.10.12'

With this done all domain classes in grails-app/domain will be persisted via MongoDB and not Hibernate. You can create a domain class by running the regular create-domain-class command:

grails create-domain-class Person

The Person domain class will automatically be a persistent entity that can be stored in MongoDB.

2.2 Combining MongoDB and Hibernate

If you have both the Hibernate and Mongo plugins installed then by default all classes in the grails-app/domain directory will be persisted by Hibernate and not Mongo. If you want to persist a particular domain class with Mongo then you must use the mapWith property in the domain class:

static mapWith = "mongo"

Alternatively you can persist Hibernate entities to Mongo using the special mongo scope added to all Hibernate entities:

def hibernatePerson = Person.get(1)

hibernatePerson.mongo.save()

def mongoPerson = Person.mongo.get(1)

2.3 Advanced Configuration

Mongo Database Connection Configuration

As mentioned the GORM for Mongo plugin will configure all the defaults for you, but if you wish to customize those defaults you can do so in the your grails-app/conf/DataSource.groovy file:

grails {
    mongo {
        host = "localhost"
        port = 27017
        username = "blah"
        password = "blah"
        databaseName = "foo"
    }
}

The databaseName setting configures the default database name. If not specified the databaseName will default to the name of your application.

You can also customize the Mongo connection settings using an options block:

grails {
    mongo {
        options {
            autoConnectRetry = true
            connectTimeout = 300
        }
    }
}

Available options and their descriptions are defined in the MongoOptions javadoc.

In production scenarios you will typically use more than one MongoDB server in either master/slave or replication scenarios. The plugin allows you to configure replica sets:

grails {
    mongo {
        replicaSet = [ "localhost:27017", "localhost:27018"]
    }
}

The replica sets are defined using a list of strings that conform to the MongoDB DBAddress specification.

MongoDB Connection Strings

Since 2.0, you can also use MongoDB connection strings to configure the connection:

grails {
    mongo {
        connectionString = "mongodb://localhost/mydb"
    }
}

Using MongoDB connection strings is currently the most flexible and recommended way to configure MongoDB connections.

SSL Connections

You can configure SSL connections by setting ssl to true in the options block:

grails {
    mongo {
        …
        options {
            ssl = true
            …
        }
    }
}

Note you can also configure the SSLSocketFactory manually if necessary. All settings within the options block are propagated to the underlying MongoOptionsFactoryBean

Configuration Options Guide

Below is a complete example showing all configuration options

grails {
    mongo {
        databaseName = "myDb" // the default database name
        host "localhost" // the host to connect to
        port = 27017 // the port to connect to
        username = ".." // the username to connect with
        password = ".." // the password to connect with
        stateless = false // whether to use stateless sessions by default

// Alternatively, using 'replicaSet' or 'connectionString' // replicaSet = [ "localhost:27017", "localhost:27018"] // connectionString = "mongodb://localhost/mydb"

options { connectionsPerHost = 10 // The maximum number of connections allowed per host threadsAllowedToBlockForConnectionMultiplier = 5 maxWaitTime = 120000 // Max wait time of a blocking thread for a connection. connectTimeout = 0 // The connect timeout in milliseconds. 0 == infinite socketTimeout = 0 // The socket timeout. 0 == infinite socketKeepAlive = false // Whether or not to have socket keep alive turned on writeNumber = 0 // This specifies the number of servers to wait for on the write operation writeTimeout = 0 // The timeout for write operations in milliseconds writeFsync = false // Whether or not to fsync autoConnectRetry = false // Whether or not the system retries automatically on a failed connect maxAutoConnectRetryTime = 0 // The maximum amount of time in millisecons to spend retrying slaveOk = false // Specifies if the driver is allowed to read from secondaries or slaves ssl = false // Specifies if the driver should use an SSL connection to Mongo sslSocketFactory = … // Specifies the SSLSocketFactory to use for creating SSL connections } } }

Global Mapping Configuration

Using the grails.mongo.default.mapping setting in Config.groovy you can configure global mapping options across your domain classes. This is useful if, for example, you want to disable optimistic locking globally or you wish to use DBRefs in your association mappings. For example, the following configuration will disable optimistic locking globally and use DBRefs for all properties:

grails.mongo.default.mapping = {
    version false
    '*'(reference:true)
}

The * method is used to indicate that the setting applies to all properties.