Grails Projects Using MongoDB

Do you like this?

This post shows you how to set up grails app with mongodb as database.


I assume you all know how to set up a grails project. If not, please have a look at Grails Hello World Application. Firstly, you have to have your local mongodb server set up. Please follow the instructions at MongoDB Installation. In my case, following were the steps I ran to get it set up in my local machine which is Ubuntu OS.

sudo apt-key adv --keyserver hkp:// --recv 7F0CEB10
echo 'deb dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
sudo apt-get update
sudo apt-get install -y mongodb-org
sudo service mongod start
Next, you have to make sure you have an existing database with a specific username/password pair to log in from your grails application.
use myDBname
db.addUser("dblogin", "dbpwd")
What you will get from this is a connection string mongodb://localhost/myDBname and you can log in using User("dblogin", "dbpwd"). Now let's create our grails application.
grails create-app grails-mongo
Clear everything from DataSource.groovy and replace it with the followings.
grails { 
  mongo { 
    host = "localhost" 
    port = 27017 
    username = "dblogin" 
    password= "dbpwd" 
    databaseName = "myDBname" 
  • Comment out runtime ":hibernate:$grailsVersion"
  • Comment out runtime ":database-migration:1.3.2"
  • Comment out compile ':cache:1.0.1'
  • Add compile ":mongodb:1.3.3"
In console, under your project's folder, run grails run-app to refresh all dependencies. After this, you can create new domain classes, save them into database. For example, run the following command to generate domain classes.
grails create-domain-class Story
Edit Story.groovy as follows:

package your_package
class Story {
	String content
In grails shell, try the following commands:
import your_package.Story

s= new Story(content: "content")
Story.withCriteria { eq("content","content") }

If you want to see all the queries to MongoDB, you have to install mongosniff. Below are the steps to set it up:
git clone
cd mongo
git checkout r2.4.6
apt-get install scons libpcap-dev g++
scons mongosniff
sudo build/linux2/normal/mongo/mongosniff --source NET lo 27017

comments powered by Disqus