Data Relationships in MongoDB – A quick guide

Read it in 8 Mins

Last updated on
19th Jan, 2022
Published
19th Jan, 2022
Views
5,918
Data Relationships in MongoDB – A quick guide

Understanding document relationships

Relationships enforce data integrity in relational databases. However, there are no relationships between documents in MongoDB and other NoSQL databases. As a result, documents are self-contained. There area few differing approaches to modelling these document relationships. 

using data relationship in MongoDB
MongoDB Relationships are the representation of how the multiple documents are logically connected to each other in MongoDB. The Embedded and Referenced methods are two ways to create such relationships. Embedded Relationships and Document Referenced Relationships are two types of relationships that have different ways of working with documents. 

While Embedded is ideal for one-to-one and one-to-many relationships, Referenced is ideal for many-to-many. Denormalization, which is Embedded, whereas Normalization is the name given to Reference relationships. Establishing relationships between documents can aid in the refinement of the database structure, as well as improve performance and reduce execution time. 

Embedded Document Model: 

The documents are embedded within one another in this model. For instance, we have two documents: one is a student document (which contains the student's basic information such as id and branch) and the other is an address document (which contains the address of the student). As a result, rather than creating two separate documents, the address documents are embedded within the student document. It will assist a user in retrieving data with a single query rather than a series of queries.

Reference Model: 

We keep the documents separate in this model, but one document contains the references to the others. For instance, we have two documents: one is a student document (which contains the student's basic information such as id and branch) and the other is an address document (which contains the address of the student). As a result, the id field of the address document is referenced in the student document. We can now query the address and get the student's address using this reference id. The normalised relationships are usually designed using this model.

A One-to-One relationship(1:1)  

The most basic of all relationships is the one-to-one relationship. If we have a one-parent and one-child document, it's an example of a one-to-one relationship. 

Example: 

Consider the following scenario: we have two documents. The first document contains the student's id name and branch, while the second document contains the student's permanent address information. 

// Student document 
{ 
    StudentName: Ishan, 
    StudentId: k_hut_2022, 
    Branch:CSE 
} 
 
// Address document 
{ 
    StudentName: Ishan, 
    PremanentAddress: XXXXXXX, 
    City: Jaipur, 
    PinCode:302022 
} 

If the address data is frequently used, the user creates a query using Student Name to retrieve the data from the address document. However, because two documents contain the same field (i.e., StudentName), the user must write a few more queries to retrieve the required information. This data retrieval procedure is time-consuming. As a result, the address document was embedded in the student document. 

{ 
    StudentNameIshan, 
    StudentIdk_hut_2020, 
    Branch:CSE 
    PermanentAddress:{ 
        PremanentAddress: XXXXXXX, 
        City: Jaipur, 
        PinCode:302022 
    }  
} 

To retrieve the required data, we now only need to write a single query. The benefit of using embedded documents is that we can group the necessary information into a single document. As a result, getting the details in one call is easier. However, as the document expands in size, for example, by adding academic and athletic information to the above document, it will become longer and take longer to retrieve the information. We may need academic or athletic information only when it is required, and in those cases, we may need to break up the document and use a subset pattern. 

Now, we will create a Database with name ‘Knowledgehut’ and a collection named ‘student’. 

db.student.insert({"StudentName":"Ishan","StudentId":"k_hut_2022","Branch":"CSE","PermanentAddress":{"permaAddress":"xxxxxxxx","City":"Jaipur","PinCode":302022}}) 

You can check the documents in the database with: 

db.student.find().pretty() 

Data Relationships in MongoDB – A quick guide

Now we will check the address of the student: 

db.student.find({StudentName:"Ishan"},{"PermanentAddress.permaAddress":1}).pretty() 

Data Relationships in MongoDB – A quick guide

A One-to-Many relationship (1:N) 

A single parent document that has multiple child documents is an example of a one-to-many relationship. It is similar to one-to-one, but with a large number of ‘children’ documents. Using the embedded method to establish a relationship can reduce the number of reading operations required to retrieve data. 

One-to-Many relationships with Embedded Documents

Example: 

We can create one-to-many relationships between data using embedded documents, allowing us to retrieve data quickly with few read operations. With the help of an example, we will now discuss the one-to-many relationship with embedded documents.  

A person may have multiple addresses, such as a current address (the location where he or she currently resides) and a residential address (the location where he or she owns a home or has a permanent address). One to many relationship possibilities occur during that time. As a result, we can store both permanent and current addresses in a single document using an embedded document model. 

// Student document 
{ 
    StudentNameIshan, 
    StudentIdk_hut_2022, 
    Branch:CSE 
} 
 
// Permanent Address document 
{ 
    StudentNameIshan, 
    PermanentAddress: XXXXXXX, 
    City: Jaipur, 
    PinCode:302022 
} 
 
// Current Address document 
{ 
    StudentNameIshan, 
    CurrentAddress: XXXXXXX, 
    City: Kota, 
    PinCode:324001 
} 

Instead of writing three documents, we can now combine them into one. 

// Student document 
{ 
    StudentNameishan, 
    StudentIdk_hut_2022, 
    Branch:CSE 
    Address: [ 
    { 
        StudentNameIshan, 
        PermanentAddress: XXXXXXX, 
        City: Jaipur, 
        PinCode:302022 
    }, 
    { 
        StudentNameIshan, 
        CurrentAddress: XXXXXXX, 
        City: kota, 
        PinCode:324001 
    } 
    ] 
} 

Because we keep all the data in a single collection (even if there are more than two types of address information, we can keep them in a JSON array), we can query in a single call and get the entire set of data, resulting in no data loss. 

Here, we are using the database knowledgehut and collection student. 

Insert the document in the collection with the following code: 

db.student.insert({"StudentName":"Ishan","StudentId":"k_hut_2022","Branch":"CSE","PermanentAddress":[{"permaAddress":"xxxxxxxx","City":"Jaipur","PinCode":302022}, {"currAddress": "pppppp","City": "Kota","PinCode": 324001}]}) 

Data Relationships in MongoDB – A quick guide

Now we will check the addresses of the student: 

db.student.find({StudentName:"Ishan"},{"PermanentAddress.permaAddress":1,"PermanentAddress.currAddress":1}).pretty() 

Data Relationships in MongoDB – A quick guide

One of the primary benefits of creating Embedded Relationships in MongoDB is that the queries are executed faster than the referenced relationship. This relationship also improves performance, and results are obtained quickly. This is also true for large datasets. 

One-to-Many relationships with the document reference \

The document reference model can also be used to create a one-to-many relationship. We keep the documents separate in this model, but one document contains the references to the others. 

Example: 

With the help of an example, we will now discuss the one-to-many relationship with document reference. Assume that we have a teacher who teaches in two different classes. And she is in possession of three documents: 

// Class 1 document 
{ 
    TeacherIdk_hut_2022, 
    ClassNamekhutA, 
    ClassIdD_123, 
    Studentcount44, 
    Subject: "DSA", 
} 
 
// Class 2 document 
{ 
    TeacherIdk_hut_2022, 
    ClassIdD_234, 
    ClassNamekhutB, 
    Studentcount55, 
    Subject: "Compiler”, 
} 

Data retrieval from these various documents is now time consuming. As a result, we'll use the reference model to assist the teacher in retrieving data with a single query. 

// Teacher document 
{ 
    teacherNameBhavesh, 
    TeacherIdk_hut_2022, 
    classIds: [ 
    D_123, 
    D_234 
    ] 
} 

The data for classes 1 and 2 can now be easily retrieved using these classIds fields. 

Here, we are working with the database knowledgehut and now, we will use a new collection teacher. 

To insert more than one document, we will use insertMany() method. 

db.teacher.insertMany([{"teacherName":"Bhavesh","teacherId":"k_hut_2022"},{"teacherId":"k_hut_2022","className":"khutA","classId":"D_123","studentCount":44,"subject":"DSA"},{"teacherId":"k_hut_2022","className":"khutB","classId":"D_234","studentCount":55,"subject":"Compiler"}]) 

As you insert these documents in the collection, you will see an output like this: 

{ 
        "acknowledged" : true, 
        "insertedIds" : [ 
                ObjectId("61d305da4c0ab35a584fc135"), 
                ObjectId("61d305da4c0ab35a584fc136"), 
                ObjectId("61d305da4c0ab35a584fc137") 
        ] 
} 

Now, to check the documents, use: 

db.teacher.find().pretty() 

Data Relationships in MongoDB – A quick guide

AMany-to-Many relationship (N:M) 

As there is no single command to implement a many-to-many relationship in a relational database, it is more difficult than a one-to-many relationship. The same is true when using mongoDB to implement them. In fact, you can't use a command to create any type of relationship in MongoDB 

Having the ability to store arrays in a document, on the other hand, allows you to store data in a way that is easy to retrieve and maintain, as well as providing you with the information you need to link two documents in your code. 

Many to Many relationships are a type of mongodb relationship in which any two entities within a document can have multiple relationships. 

In this relationship, we can consider a case of Online courses website where there are many courses and also many users. Each course is purchased by many users and each user may purchase many courses. 

Example: 

For this we will create a database knowledgehut and two different collections of users and courses. 

db.courses.insertMany([{"CourseName":"MongoDB Basics","price":50},{"CourseName":"NodeJS","price":50}]) 

Output: 

{ 
        "acknowledged" : true, 
        "insertedIds" : [ 
                ObjectId("61d31f0a4c0ab35a584fc144"), 
                ObjectId("61d31f0a4c0ab35a584fc145") 
        ] 
} 

In the courses collection, we have added two courses and prices of those courses in dollars. 

In the users collection we will add the documents of the users enrolled in the courses with this command:. 

db.users.insertMany([{"name":"Ishan", "isVerified":true, "courseId":[ObjectId("61d31f0a4c0ab35a584fc145")]},{"name":"Bhavesh","isVerified":true,"courseId":[ObjectId("61d31f0a4c0ab35a584fc144"),ObjectId("61d31f0a4c0ab35a584fc145")]}]) 

Output: 

{ 
        "acknowledged" : true, 
        "insertedIds" : [ 
                ObjectId("61d320244c0ab35a584fc146"), 
                ObjectId("61d320244c0ab35a584fc147") 
        ] 
} 

We can check the users collection with: 

db.users.find().pretty() 

Data Relationships in MongoDB – A quick guide

Next, we have to update the courses collection with the usersId . 

db.courses.updateMany({}, {$set: {userslist: [{userId:[ObjectId("61d320244c0ab35a584fc147"),ObjectId("61d320244c0ab35a584fc146")]}]}}) 

Output: 

{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 } 

Data Relationships in MongoDB – A quick guide

You can now see the courses collection with the usersId in the userslist.  

Embedded or Referenced? Which to use when? 

There are two types of relationships in MongoDB. Embedded and made as a reference. Every relationship has its own set of benefits and drawbacks. These connections aid in performance enhancement. It implements any of the relationships as One to One, One to Many, or Many to Many depending on the situation. The implementation of this relationship has improved data consistency. 

Profile

Abhresh Sugandhi

Author

Abhresh is specialized as a corporate trainer, He has a decade of experience in technical training blended with virtual webinars and instructor-led session created courses, tutorials, and articles for organizations. He is also the founder of Nikasio.com, which offers multiple services in technical training, project consulting, content development, etc.