Implementing many to many relation between domains in Grails with MongoDB

Posted By : Shivam Gupta | 03-May-2014

As we know that implementation of many to many in sql is difficult because it needs a third table for maintaining relation. But it is easy in MongoDB , I will show you steps how to implement many to many relation in Grails with MongoDB


In a project, I had to implement many to many relation between two domains named as User and Circle. Scenario is that user has many circles and each circle has many user.


I assume that you have configured mongodb plugin in grails application and created database in mongodb.


Steps for implement many to many relation


Create two domain using following commands

grails create-domain-class User

grails create-domain-class Circle


Add data members and mapping

In User

String name;

List<Circle> circles

static mapWith = "mongo"

static hasMany=[circles:Circle]


In Circle

String name;

List<User> users;

static mapWith = "mongo"

static belongsTo=User  //This line is used to make user as owner

static hasMany=[users:User]


After saving some documents in above domains you will see these domain like following manner in mongodb.


About Author

Author Image
Shivam Gupta

Shivam is a bright java developer with experience in building enterprise applications using Flex and Java. He is also well versed with Groovy and Grails development.

Request for Proposal

Name is required

Comment is required

Sending message..