Skip to content
Related Articles

Related Articles

Create Relationship in MongoDB
  • Last Updated : 17 Feb, 2021

In MongoDB, a relationship represents how different types of documents are logically related to each other. Relationships like one-to-one, one-to-many, etc., can be represented by using two different models:

  1. Embedded document model
  2. Reference model

Embedded Document Model: In this model, the documents are embedded inside one document. For example, we have two documents one is a student(which contains the basic information of the student like id, name branch) and another is an address document(which contains the address of the student). So, instead of creating two different documents, we embed the address documents inside the student document. It will help the user to retrieve the data using a single query rather than writing a bunch of queries.

Reference Model: In this model, we maintain the documents separately but one document contains the reference of the other documents. For example, we have two documents one is a student(which contains the basic information of the student like id, name branch) and another is an address document(which contains the address of the student). So, here student document contains the reference to the address document’s id field. Now using this reference id we can query the address and get the address of the student. This model is generally used to design the normalized relationships.

One-to-One Relationships with Embedded Documents

Using embedded documents we can create one-to-one relationships between the data so, that we can easily retrieve data using few read operations. 

Now we will discuss the one-to-one relationship with embedded documents with the help of an example. Let us consider we have two documents. The first document contains the id name and branch of the student and the second document contains the Permanent address detail of the student.



// Student document
{
    StudentName: GeeksA,
    StudentId: g_f_g_1209,
    Branch:CSE
}

// Address document
{
    StudentName: GeeksA,
    PremanentAddress: XXXXXXX,
    City: Delhi,
    PinCode:202333
}

Now, if the address data is used frequently, the user retrieves the data of the address document by creates a query using Student Name but here two documents contain the same field(i.e., StudentName) so the user needs to write few more queries to retrieve the required information. This process of retrieving data is cumbersome. So, we embedded the address document in the student document. 

{
    StudentName: GeeksA,
    StudentId: g_f_g_1209,
    Branch:CSE
    PermanentAddress:{
        PremanentAddress: XXXXXXX,
        City: Delhi,
        PinCode:202333
    } 
}

Now, we have to write only a single query to retrieve the required data. The advantage of using the embedded documents is we can group the required information and can keep it in a single document. So it is easier to get the details in one call itself. But when the document starts to grow, for example, adding the academic information, athletics information to the above document, it will become lengthier and takes more time to retrieve the details. Only when required, we may need to have academic or athletics information, and hence during those scenarios, we may need to break up the document and can go for a subset pattern. In the Subset pattern, we break the large sum of information into small chunks so that we can easily retrieve data. Because the large sum of data slows down the read operation.  But subset pattern has also a drawback that is splitting your data into many small collections, the database maintenance part is difficult, and tracking for the data will also become a hassle.

Example:

Here, we are working with:

Database: gfg

Collection: student

Documents: One document that contains the details of a student



Now we will display the address of the student

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

One-to-Many Relationships with Embedded Documents

Using embedded documents we can create one-to-many relationships between the data so, that we can easily retrieve data using few read operations. Now we will discuss the one-to-many relationship with embedded documents with the help of an example. Sometimes, there are possibilities of a person containing multiple addresses like having a current address (the place where he/she stays) and the residential address (the place where he/she having own house or permanent address). During that time, one to many relationship possibilities occurs. So, we can use an embedded document model to store permanent and current address in a single document

// Student document
{
    StudentName: GeeksA,
    StudentId: g_f_g_1209,
    Branch:CSE
}

// Permanent Address document
{
    StudentName: GeeksA,
    PermanentAddress: XXXXXXX,
    City: Delhi,
    PinCode:202333
}

// Current Address document
{
    StudentName: GeeksA,
    CurrentAddress: XXXXXXX,
    City: Mumbai,
    PinCode:334509
}

Now instead of writing three documents, we can embed them into a single document.

// Student document
{
    StudentName: GeeksA,
    StudentId: g_f_g_1209,
    Branch:CSE
    Address: [
    {
        StudentName: GeeksA,
        PermanentAddress: XXXXXXX,
        City: Delhi,
        PinCode:202333
    },
    {
        StudentName: GeeksA,
        CurrentAddress: XXXXXXX,
        City: Mumbai,
        PinCode:334509
    }
    ]
}

As we keep all the data(even if there are more than 2 address kind of information, we can keep them in a JSON array) in a single collection, we can query in a single call and get a whole set of data, which leads to getting whole information and no loss occurs.

Example:

Here, we are working with:

Database: gfg

Collection: student

Documents: One document that contains the details of a student

Now we will display all the addresses of the student

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

One-to-Many relationships with the document reference

We can also perform a one-to-many relationship using the document reference model. In this model, we maintain the documents separately but one document contains the reference of the other documents. 

Now we will discuss the one-to-many relationship with embedded documents with the help of an example. Let us considered we have a teacher which teaches in 2 different classes. So, she has three documents:

// Teacher document
{
    teacherName: Sunita,
    TeacherId: g_f_g_1209,
}

// Class 1 document
{
    TeacherId: g_f_g_1209,
    ClassName: GeeksA,
    ClassId: C_123
    Studentcount: 23,
    Subject: "Science",
}

// Class 2 document
{
    TeacherId: g_f_g_1209,
    ClassId: C_234
    ClassName: GeeksB,
    Studentcount: 33,
    Subject: "Maths",
}

Now retrieving data from these different documents is cumbersome. So, here we use the reference model which will help teacher to retrieve data using single query.

// Teacher document
{
    teacherName: Sunita,
    TeacherId: g_f_g_1209,
    classIds: [
    C_123,
    C_234
    ]
}

Now using these classIds field teacher can easily retrieve the data of class 1 and 2.

Example:

Here, we are working with:

Database: gfg

Collection: teacher

Documents: three document that contains the details of the classes

Now we will display the values of classId field

db.teacher.findOne({name:"Sunita"}, {classId:1})

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :