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 :
In this approach, one document will be embedded in another document (like a subset).
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.
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.
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:
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.
Above you can see the data to be modelled, and below we have modelled it for MongoDB storage.
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 :
Here we have used the ObejctIds of the addresses to reference it from the student document.
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 :
Reference Approach :
Note : In the above example, each role will be stored in a separate
role document and the same is referred through their ObjectIds.