Data Relationships in MongoDB

Welcome to a tutorial on Data Relationships in MongoDB. Here you learn about the different forms of Data Relationships.

In MongoDB, Relationships are used to specify how one or more documents are related. This relationship can be modeled either in an Embedded way or by making use of the Reference approach. 

 

Data Relationship in MongoDB can be of the following forms.

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

 

MongoDB: Embedded Relationship

In the Embedded Relationship approach, a document will be embedded in another document (i.e. like a subset).

 

MongoDB: Reference Relationship

In the Reference Relationship, the documents are maintained separately (e.g. student and address). However, the student document will have a reference to the address documentid field. This approach is commonly used for designing normalized relationships. The basic idea behind any NoSQL database is to eliminate the complex relationships existing between documents, and it is the same with MongoDB. Although, there are cases where these relationships are required to be modeled in the database.

 

MongoDB: One-to-One Relationship

Suppose a student database of a college, in which the college restricts only one course can be availed by the student at a time. hence, this is a one-to-one relationship, that is, a student can be enrolled only in one course at a time. check out the example below to see how this can be modeled.

 

In the example above, there is student data that has a relationship with the course data. These 2 collections can be embedded into one in MongoDB. This is shown below.

 

 

MongoDB: One to Many Relationship

Here, we will continue with the same student database example. now, consider a student can have more than one address (i.e. permanent and current). Check out the example below to see how to model such a case which is a one-to-many relationship.

 

In the example above, you will notice the data to be modeled, and in the example below we have modeled it for MongoDB storage.

 

Using the embedded approach, both the addresses of the student can be retrieved by a single query.

Also with the reference approach, the above database can be modeled.

 

In the above example, we used the ObjectIds of the addresses to reference them from the student document.

 

MongoDB: Many to Many Relationship

Let's consider the same student database example, where a student can have different roles such as leader, cricket captain, football captain, and so on, that many roles can be accomplished by students or students can be associated with multiple roles. Check out how to model this approach to many relationships.

Embedded Approach:

 

Reference Approach:

 

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