Create Relationship in MongoDB
In MongoDB, managing relationships between data is crucial for structuring and querying databases effectively. Relationships can be handled using embedded documents, references and the $lookup aggregation stage, each offering different advantages depending on the use case.
In this article, We will learn about the Relationship in MongoDB by understanding various relationships with the help of examples and so on.
Relationship in MongoDB
In MongoDB, relationships between data can be managed using embedded documents and references:
- Embedded Documents: This approach stores related data within a single document, ideal for data that is frequently accessed together. It simplifies data retrieval and ensures data locality.
- Reference Model: This method involves storing references to related documents using unique identifiers, suitable for large or independently accessed data. It allows for normalization and maintains data consistency.
- $lookup: MongoDB’s aggregation framework supports joins between collections using the
$lookup
stage, enabling complex many-to-many relationships.
These techniques provide flexibility in handling various data relationships, optimizing both storage and access patterns.
1. 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.
2. 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,
PermanentAddress: 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:{
PermanentAddress: 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
Output
Now we will display the address of the student
db.student.find({StudentName:"GeeksA"},{"PermanentAddress.permaAddress":1}).pretty()
Output
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
Output
Now we will display all the addresses of the student
db.student.find({StudentName:"GeeksA"},
{"Address.permaAddress":1,
"Address.currAddress":1}).pretty()
Output
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
Output
Now we will display the values of classId field
db.teacher.findOne({name:"Sunita"}, {classId:1})
Output

Conclusion
MongoDB offers flexible approaches to managing relationships, including embedded documents for frequently accessed data, references for normalization and data consistency, and the $lookup stage for complex joins. These methods optimize both storage and retrieval, enabling efficient handling of various data relationship scenarios.
FAQs on Relationship in MongoDB
What is a relationship in MongoDB?
In MongoDB, a relationship defines how data is connected across different collections or documents. Relationships can be managed using embedded documents, which store related data within a single document, or references, which use unique identifiers to link separate documents.
Has many relationships MongoDB?
In MongoDB, “has many” relationships can be represented using either embedded documents or references. Embedded documents store all related data in a single document, ideal for small, frequently accessed related data. References involve linking documents through unique identifiers, suitable for larger datasets or when related data is accessed independently.
What are the relationships in NoSQL?
NoSQL databases, like MongoDB, manage relationships using methods such as embedded documents and references. Unlike traditional SQL databases that rely on foreign keys, NoSQL databases offer flexible schema designs, allowing for various approaches to handle one-to-one, one-to-many, and many-to-many relationships based on the application’s requirements and data access patterns.