Relationships in MongoDB

Relationships in MongoDB are used to specify how one or more documents are related to each other. In MongoDB, the relationships can be modelled either by Embedded way or by using the Reference approach. These relationships can be of the following forms :

  • One to One
  • One to Many
  • Many to Many

Embedded Relationship

In this approach, one document will be embedded in another document (like a subset).


Reference Relationship

In this approach, the documents are maintained separately (student and address). But, the student document will have a reference to the address document id field. This is basically used for designing normalized relationships. The basic idea behind any NoSQL database is to eliminate the complex relationships between documents, and MongoDB does the same. But, there are scenarios where these relationships are required to be modelled in the database.


One to One Relationship

Consider a student database of a college, where the college restricts only one course can be availed by the student at a time. So, this is nothing but One to One relationship i.e. a student can be enrolled only to one course at a time. Let us see how this can be modelled.

One to One Relationship in MongoDB documents

The above figure shows that there is student data which has a relationship with the course data. In MongoDB, these 2 collections can be embedded into one as shown below:

One to One Relationship in MongoDB documents


One to Many Relationship

Continuing with the same student database example, consider a student can have more than one address (permanent and current). Let us see how to model such a usecase which is a one to many relationship.

One to Many Relationship in MongoDB documents

Above you can see the data to be modelled, and below we have modelled it for MongoDB storage.

One to Many Relationship in MongoDB documents

With this embedded approach, both the addresses of the student can be retrieved by a single query!

With the reference approach, the above database can be modeled as shown below :

One to Many Relationship in MongoDB documents

Here we have used the ObejctIds of the addresses to reference it from the student document.


Many to Many Relationship

Consider the same student database example, where a student can have different roles like leader, cricket captain, football captain etc. i.e. many roles can be accomplished by students or students can be associated to multiple roles. Let us see how to model this approach which is a many to many relationship.

Embedded Approach :

One to Many Relationship in MongoDB documents

Reference Approach :

One to Many Relationship in MongoDB documents

Note : In the above example, each role will be stored in a separate role document and the same is referred through their ObjectIds.