The Wayback Machine - https://web.archive.org/web/20240906174201/https://www.geeksforgeeks.org/create-relationship-in-mongodb/
Open In App

Create Relationship in MongoDB

Last Updated : 18 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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:

  1. 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.
  2. 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.
  3. $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

exampleOutput

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.



Previous Article
Next Article

Similar Reads

Connect MongoDB (AWS) from Local Machine using WinSCP and MongoDB Compass
Pre-requisite: AWS and MongoDB In this article, we are going to connect to the Mongo database of the AWS Ubuntu Server instance using WinSCP and learn how to get connected to the server from your local machine using MongoDB Compass.  If you haven't installed a MongoDB server in your AWS EC2 instance then follow the steps present in this article and
4 min read
How to Integrate MongoDB Atlas and Segment using MongoDB Stitch
Data integration has become a crucial component of modern business strategies, allowing companies to enhance the power of data for informed decision-making. According to a recent survey, 85% of businesses believe that integrating data across multiple platforms is important for their success. In this article, We will learn about What is MongoDB Stit
5 min read
MongoDB - Delete Multiple Documents Using MongoDB Shell
The db.collection.deleteMany() method is used to delete multiple documents from a collection in Mongo Shell. This method deletes multiple documents from the collection according to the filter. The deleteMany() is a Mongo shell method, which can delete multiple documents. This method can be used in multi-document transactions. If you use this method
2 min read
Connect MongoDB Atlas Cluster to MongoDB Compass
MongoDB Compass is a free GUI for MongoDB. You might want to connect MongoDB Atlas Cluster to MongoDB Compass to take benefit of the GUI model for database administration. This guide explains how to connect MongoDB Atlas Cluster to MongoDB Compass. The connection process involves obtaining a connection string from MongoDB Atlas, configuring MongoDB
4 min read
MongoDB Shell vs MongoDB Node.JS Driver
MongoDB Shell and the MongoDB Node.js Driver are both tools for interacting with MongoDB, but they serve different purposes and are used in different contexts. Here's a comparison of the two: MongoDB Node.JS DriverA Node.js package called the MongoDB Node.js Driver enables programmatic communication between applications and MongoDB databases. Throu
4 min read
MongoDB Compass vs MongoDB Atlas
MongoDB is a popular NoSQL database known for flexibility and scalability. MongoDB Compass offers a graphical interface for managing databases visually while MongoDB Atlas is a cloud-based service for automated management and scaling of MongoDB databases. In this article, We will learn about the in-depth understanding of the difference between the
5 min read
How to Get Last Records in One to Many Relationship in MySQL
MySQL is a widely used relational database management system (RDBMS) that provides a robust and scalable platform for managing and organizing data. MySQL is an open-source software developed by Oracle Corporation, that provides features for creating, modifying, and querying databases. It utilizes the Structured Query Language (SQL) to interact with
9 min read
How to Select the Last Records in a One to Many Relationship using SQL Server
In database management, one-to-many relationships are common, where a record in one table can correspond to multiple records in another table. When dealing with such relationships, it's often necessary to select the last records from the "many" side for each record on the "one" side. In this article, we'll explore how to achieve this using differen
4 min read
Schema Design and Relationship in NoSQL Document-Base Databases
NoSQL databases are powerful alternatives to traditional relational databases, offering flexibility, scalability, and performance. Among the various types of NoSQL databases, document-based databases stand out for their ability to store and retrieve data in flexible, schema-less documents. In this article, we will explore the intricacies of schema
3 min read
How to Design a Relational Database for Customer Relationship Management (CRM)
Designing a relational database for Customer Relationship Management (CRM) is essential for businesses looking to effectively manage customer interactions and drive growth. A well-designed CRM database organizes customer data, tracks interactions, and provides insights for better decision-making. This article explores the key steps and best practic
6 min read
How to Design ER Diagrams for Customer Relationship Management (CRM) Software
In the world of business establishing and maintaining good customer contact is among the most important things. Customer-oriented applications (CRMs) are the main tools that promote long-term business-to-customer partnerships. An Entity-Relationship (ER) diagram is the conceptual design that forms the basis of every CRM system. This article helps y
5 min read
How to Draw Entity Relationship Diagrams (ERDs)
Entity Relationship Diagrams serve as valuable tools for designing complex systems and their relationships. This article will go through the step-by-step process of designing an ER diagram and defining how entities, attributes, and relationships are defined. Entity relationship diagrams are important in database design and require a clear structure
6 min read
How to Select the Last Records in a One-To-Many Relationship Using SQL Join
SQL (Structured Query Language) is a powerful tool used to communicate with and manage databases. Think of a database as a digital filing cabinet where you store information. Imagine a database as a digital filing cabinet where information is stored. SQL helps you interact with this filing cabinet, allowing you to perform tasks like adding, updatin
9 min read
Create a Newsletter Sourcing Data using MongoDB
There are many news delivery websites available like ndtv.com. In this article, let us see the very useful and interesting feature of how to get the data from ndtv.com via scraping feature i.e. extracting the contents from ndtv.com and storing them into MongoDB. MongoDB is a NoSQL Documentum model database. Using Mongoose, Node JS, and Cheerio, the
7 min read
How to create new Mongodb database using Node.js ?
mongodb module: This Module is used to performing CRUD(Create Read Update Read) Operations in MongoDb using Node.js. We cannot make a database only. We have to make a new Collection to see the database. The connect() method is used for connecting the MongoDb server with the Node.js project. Please refer this link for connect() method. Installing mo
1 min read
How to create new Collection in MongoDB using Node.js ?
MongoDB the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON (similar to JSON for
1 min read
How to Create a MongoDB Dump of Database?
MongoDB is a popular NoSQL database known for its flexibility and scalability. However, like any database system, it is crucial to have a backup plan in place to protect our data from loss or corruption. One of the best ways to back up your MongoDB database is by creating a dump. In this article, we will go through the process of creating a MongoDB
6 min read
How to Create a Search Index with Dynamic Field Mapping in MongoDB
Dynamic mapping in MongoDB Atlas Search is a powerful feature that automatically indexes all supported field types in a collection and making it ideal for applications with evolving data models. This type of mapping is particularly useful when the schema is unknown or changes regularly. Dynamic mappings assign fields automatically when new data is
7 min read
MongoDB - Create Database using Mongo Shell
A MongoDB Database is the container for all the collections, where the Collection is a bunch of MongoDB documents similar to tables in RDBMS and the Document is made up of fields similar to a tuple in RDBMS, but it has a dynamic schema here. This article explains the easy method to create a Database in MongoDB using Mongo Shell. How to Create a Mon
2 min read
How to Create Indexes in MongoDB using Node.js?
MongoDB, a popular NoSQL database, provides powerful indexing capabilities to improve query performance. Indexes in MongoDB help in quickly locating documents and speeding up read operations. In this tutorial, we'll explore how to create indexes in MongoDB using Node.js. What is an Index in MongoDB?In MongoDB, an index is a data structure that impr
3 min read
How to Create and Validate JSON Schema in MongoDB?
JSON Schema validation in MongoDB allows you to enforce the structure of documents in a collection. This ensures data integrity by validating documents against defined schemas before they are inserted or updated. In this article, we will cover how to create and validate JSON Schema in MongoDB using different approaches, provide a step-by-step guide
5 min read
How to Create Database and Collection in MongoDB
MongoDB is a widely used NoSQL database which is used for its flexibility and scalability in managing data. Creating a database in MongoDB is a simple process using the use command. In this article, we'll explore how to create a database, create collections, and insert documents into collections in MongoDB. Creating a Database and Collection in Mon
3 min read
Create user and add role in MongoDB
Creating users and assigning roles in MongoDB is essential for managing access control and securing your databases. MongoDB provides flexibility in defining user privileges through roles, allowing users to perform specific operations on designated resources. In this article, We will learn about How to Create user and add a role in MongoDB by unders
7 min read
Create Database using MongoDB Compass
MongoDB uses a document-oriented storage model which contrasts with traditional relational databases. Instead of storing data in tables with rows and columns, MongoDB stores data as documents in BSON format. In this article, We will learn about How to Create a Database using MongoDB Compass in detail. Understanding MongoDB Document-Oriented Storage
5 min read
MongoDB vs MySQL
Differences between MongoDB and MySQL on various parameters are discussed below: What are MongoDB and MySQL? MongoDB MySQL MongoDB is an open-source database developed by MongoDB, Inc. MongoDB stores data in JSON-like documents that can vary in structure. It is a popular NoSQL database. MySQL is a popular open-source relational database management
2 min read
Difference between Oracle and MongoDB
1. Oracle : Oracle is a relational database management system (RDBMS). It was developed by Oracle Corporation in 1980. It is the first database designed for grid computing that provides the most flexible and cost-effective way to manage information and application. It runs on major platforms like Windows, Unix, Linux, and macOS. It is a relational
2 min read
Connecting MongoDB to Jupyter Notebook
MongoDB is one of the most famous NoSql databases. It is an open-source database. The simple meaning of the NoSql database is a non-relational database. i.e., It doesn't include the specific structure of databases such as tables and all like the relational database. So, you can design the schemas without any restrictions. Jupyter Notebook is also a
3 min read
Introduction about Node.js and MongoDB
NoSQL databases are databases that store and retrieve the data that is present in a non-tabular format. Depending on the format of the data stored, NoSQL databases are split into 4 major types: Key-Value Graph database Document-oriented Column family These databases are built to address the shortcomings of traditional RDBMS and provide high perform
4 min read
MongoDB | Delete Database using MongoShell
Prerequisite : MongoDB Introduction Short Description : A MongoDB Database is a container for all the collections, where Collection is a bunch of MongoDB documents similar to tables in RDBMS and Document is made of fields similar to a tuple in RDBMS, but it has a dynamic schema here. Example of a Document : { "Name" : "Aman", Age : 24, Gender : "Ma
2 min read
Difference between RDBMS and MongoDB
MongoDB is an open-source document-oriented database used for high volume data storage. It falls under the classification of a NoSQL database. NoSQL tool means that it doesn't utilize the usual rows and columns. MongoDB uses BSON (document storage format) which is a binary style of JSON documents. Features of MongoDB: Multiple Servers: It can run o
2 min read