Data 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
MongoDB: Embedded Relationship
In this approach, one document will be embedded in another document (like a subset).
MongoDB: 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.
MongoDB: 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.
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:
MongoDB: 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.
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.
MongoDB: 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.
Note: In the above example, each role will be stored in a separate
role document and the same is referred through their ObjectIds.