• Post author:
  • Post category:MongoDB
  • Post last modified:May 9, 2024
  • Reading time:9 mins read
You are currently viewing MongoDB Embedded or Reference Relationships

The MongoDB has two relationships embedded and reference. and these relationships can be one-to-one(1:1), one-to-many(1:N), or many-to-many(N:N) connections.

Advertisements

This article will dive into the discussion on embedded and reference relationships along with their implementation in MongoDB.

1. MongoDB Embedded relationship

All the information we need for a particular entity is stored in one place, making it easy to fetch and update in embedded relationships. Embedding can also improve query performance, as it allows us to fetch related data with a single query.

However, there are some downsides to embedding as well. Embedding can also be difficult if the related data is large or frequently changing, as it can lead to performance issues. Let’s dive into the embedded relationship types with examples.

1.1 One-to-One(1:1) embedded relationship

A document is embedded as a field within another document in a one-to-one relationship. As an illustration, we have a student collection that includes student documents with the following fields: _id, name, email, and personal_info. So, we could represent the student’s personal information as an embedded document like this:


# Embedded document creation
db.student.insert({
   name: "Edward Mark",
   email: "[email protected]",
   personal_info: {
      age: 30,
      gender: "Male",
      address: {
         street: "5531 Main St",
         city: "San Francisco",
         state: "CA"
      }
   }
})

Thereby, we can run the following command to find a student’s personal information with a given email.


# Fetch information of Collection
db.student.findOne({ email: "[email protected]" }.personal_info)

Consequently, the output looks like this:

Mongodb Embed and Reference Relationship

1.2 One-to-Many embedded relationship

Although, a variety of documents can be embedded as sub-documents inside another document in an embedded one-to-many relationship. For this purpose, we have an updated collection called student with the embedded array exam. Here, a student has different exams on different days. Then, we represent the exams documents as an array of embedded documents.


# Addition of embedded array
db.student.insertOne({
   name: "Jenna Gilbert",
   email: "[email protected]",
   exams: [
      {
         exam1: "Calculus",
         day: "Monday"
      },
      {
         exam2: "Data Structure",
         day: "Thursday"
      }
   ]
})

By executing the following command, we can fetch all the exams of a student with a specific email:


# Fetching student exam details
db.student.findOne({ email: "[email protected]" }.exams)

The output is displayed like this in the following image:

Mongodb Embed and Reference Relationship

More details of MongoDB One-to-Many relationship with embedded documents can be found here.

2. MongoDB Reference relationship

On the other hand, referencing involves storing a reference to related data in another MongoDB collection. This approach avoids data duplication and allows for more flexibility in querying and updating the data.

Surprisingly, referencing also has its own set of drawbacks. Referencing can also be less efficient than embedding in terms of query performance, as it requires multiple queries and data retrieval from multiple collections.

Henceforth, we can see the implementation of the reference relationship below.

2.1 One-to-Many reference relationship

Analogous to the embedded relationship in the output of the above MongoDB query, the document reference relationship, related data is stored in separate documents that are linked through a unique identifier. Moreover, the reference relationship model support one-to-one or one-to-many relationship between two entities by storing a reference to related data in another collection.

We have again modified the collection student where the following documents are inserted to demonstrate the one-to-many reference relationship:


# Modifying collection
db.student.insertMany([
   {
      _id: 1,
      name: "Emily Dark",
      email: "[email protected]"
   },
   {
      _id: 2,
      name: "Jermy Doe",
      email: "[email protected]"
   }
])

Afterward, we inserted some sample documents into the course collection which is referencing the student collection.


# Adding sample documents to collection
db.course.insertMany([
   {
      _id: 1,
      name: "C++",
      student_id: 1
   },
   {
      _id: 2,
      name: "OOP",
      student_id: 1
   },
   {
      _id: 3,
      name: "Java",
      student_id: 2
   }
])

Now, we can use the following command to find all the courses taken by a specific student with a given ID. The find query will return all the documents in the course collection where the student_id field matches the given student ID.


# Applying Find function to fetch relevant details
db.course.find({ student_id: 1 })

Following is the output of the above query:

Mongodb Embed and Reference Relationship

2.2 Many-to-Many reference relationship

Generally, the reference relationship in MongoDB can model massive hierarchical data sets or portray more complicated many-to-many relationships.

Therefore, we can model a many-to-many relationship using a reference approach with an intermediate collection to represent the relationship. We have created the collections students and subjects respectively and inserted the document inside them.

Here, we can see the sample collection student with the inserted documents.


# Inserting documents to collection student
db.student.insertMany([
   {
      _id: 001,
      name: "Alex Kim",
      email: "[email protected]"
   },
   {
      _id: 002,
      name: "Klause Matt",
      email: "[email protected]"
   }
])

Then, we can see the collection subject with the following documents.


# Inserting documents to collection subject
db.subject.insertMany([
   {
      _id: 102,
      title: "MongoDB",
      teacher: "John Smith"
   },
   {
      _id: 103,
      title: "SQL",
      teacher: "Jane Doe"
   }
])

Thereafter, we have an intermediate collection called enrollments to represent the relationship between students and subjects as follows:


# Creating enrollments collection
db.enrollments.insertMany([
   {
      student_id: 001,
      subject_id: 102
   },
   {
      student_id: 002,
      subject_id: 102
   },
   {
      student_id: 002,
      subject_id: 103
   }
])

In order to, search for the student with a given ID who enrolled in specific subjects, we can use the following query. Then, we will get all the documents in the enrollments collection where the student_id field matches the given student ID and will populate the subject_id field with the relevant documents from the subjects collection based on the reference.


# Applying find function
db.enrollments.find({ student_id: 001 }.subject_id)

The query returned the expected results as shown.

Mongodb Embed and Reference Relationship

3. Conclusion

In all cases, choosing between embedded and reference relationships in MongoDB depends on a variety of factors, including the size and complexity of the data and the performance requirements of the application. Understanding the trade-offs between these two approaches can help us make the right decision for the specific use case.