Open In App

MongoDB Relationships Embed or Reference

Last Updated : 19 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

MongoDB is a popular NoSQL database that offers flexibility in managing data relationships. Understanding the different methods of creating relationships in MongoDB is essential for designing efficient and effective database schemas.

In this article, We will explore two primary methods which are Embedded Relationships and Document Referenced Relationships, discussing their advantages, considerations and examples.

Methods to Create MongoDB Relationships

When designing a MongoDB database, there are several methods to consider for creating relationships between documents. MongoDB is a popular NoSQL database that offers the below methods for creating relationships between documents.

  1. Embedded Relationships
  2. Documented Reference Relationships

1. Embedded Relationships in MongoDB

In MongoDB, we can include related information directly inside a document. For example, a blog post’s comments could be stored within the post’s document. This approach eliminates the need to fetch related data separately but can lead to unnecessary duplication of data.

Below are the two types of relationships in the Embedded Relationships.

  • One-to-One Relationship
  • One-to-Many Relationship

1. One to One Relationship

  • In MongoDB, when one document from one collection should follow the structure or rules of another document with the same name in a different collection, it means that the documents share a similar schema or structure.
  • This can involve embedding documents within each other or referencing them to establish a relationship between them.

Example:

db.books.insert(
{
_id: 1,
title: "The Great Gatsby",
author: "F. Scott Fitzgerald",
year: 1925,
genre: "Fiction",
publisher: {
name: "Scribner",
location: "New York",
country: "USA"
}
}
)

Output:

WriteResult({ "nInserted" : 1 })

Explanation: This message indicates that one document was successfully inserted into the “books” collection.

2. One-to-Many Relationships

  • In MongoDB, a single document in one collection can be linked to multiple documents in another collection.
  • This approach allows for a flexible data structure where we can easily reference a wide range of documents. However, it requires careful management to ensure the relationships are properly maintained.

Example:

db.artists.insert(
{
_id: 3,
artistName: "XYZ",
albums: [
{
album: "DEF",
year: 2000,
genre: "Blues"
},
{
album: "ABC",
year: 2013,
genre: "Classical Music"
}
]
}
)

Output:

WriteResult({ "nInserted" : 1 })

Explanation:

  • The example demonstrates a one-to-many relationship between an artist and their albums.
  • One artist can have many albums (as represented by the albums array within the artist document).
  • Each album is a separate document within the albums array, containing details such as the album name, year, and genre.

2. Document Referenced Relationships in MongoDB

  • References can be used in documents, such as IDs, to connect them, simplifying data structure and ensuring data integrity. However, this approach can complicate relationship queries.
  • Integrating various measures in response to diverse needs, such as embedding data in future carcity, can speed up operations and optimize data storage and access. However, it adds difficulty and complexity to data design and querying.
  • In MongoDB, a link between two documents can be established using references, often by storing an identifier (e.g., ID) in one document and referencing it in the other. This allows for seamless flow of information between documents, unlike embedding all information within a single document.

For example, suppose we have two collections: ‘users’ and ‘posts’. Each post document contains a field called ‘author’, which stores the ‘ID’ of the corresponding user who authored the ‘post’. This establishes a reference relationship between the ‘posts’ and ‘users’ collections.

// users collection
{
"_id": ObjectId("609c11e1a435e2001f6383c4"),
"username": "john_doe",
"name": "John Doe",
"email": "john@example.com"
}
// posts collection
{
"_id": ObjectId("609c124ba435e2001f6383c5"),
"title": "Introduction to MongoDB",
"content": "This is a beginner's guide to MongoDB.",
"author": ObjectId("609c11e1a435e2001f6383c4") // Reference to the user who authored the post
}

Explanation: In this example, the ‘author‘ field in the posts collection references the ‘_id’ of the corresponding user in the ‘users’ collection. When querying the ‘posts’ collection, we can use this reference to fetch additional information about the author from the ‘users’ collection if needed.

1. Parent Document

In MongoDB, the term “parent document” refers to the primary entity within a collection. It serves as the container for related data or child documents. For example, in a database of blog posts, each individual blog post would be considered a parent document.

2. Child Documents

Child documents, on the other hand, are subordinate entities contained within a parent document. They are directly associated with and nested within the parent document. Using the blog post example, comments associated with a specific post would be considered child documents of that post.

3. Querying the MongoDB Relationships

When querying MongoDB relationships, it involves retrieving data based on the connections between parent and child documents. This typically entails searching for parent documents and, if necessary, retrieving related child documents. For instance, querying blog posts might involve retrieving comments associated with each post.

List of Drivers Supported by DBRefs

DBRefs, or Database References, are a standardized way of representing relationships between documents in MongoDB. Most MongoDB drivers support DBRefs, including:

  1. MongoDB Node.js Driver: The official MongoDB driver for Node.js supports DBRefs and provides functions for working with them.
  2. MongoDB Java Driver: The official MongoDB driver for Java also supports DBRefs and allows developers to use them in Java applications.
  3. MongoDB Python Driver (PyMongo): PyMongo, the official MongoDB driver for Python, supports DBRefs and provides methods for handling them.
  4. MongoDB C#/.NET Driver: The official MongoDB driver for C# and .NET also supports DBRefs and offers functionality for working with them.
  5. MongoDB Ruby Driver: The MongoDB driver for Ruby (MongoDB Ruby Driver or Mongoid) supports DBRefs and includes features for managing them.
  6. MongoDB Go Driver: The official MongoDB driver for Go supports DBRefs and provides utilities for working with them in Go applications.
  7. MongoDB Rust Driver: The MongoDB driver for Rust supports DBRefs and enables Rust developers to use them in their applications.
  8. MongoDB Swift Driver: The MongoDB driver for Swift supports DBRefs and offers functionality for working with them in Swift applications.

Conclusion

Overall, MongoDB offers Embedded Relationships for storing related information within a document, simplifying data access but risking data redundancy. Document Referenced Relationships use IDs to connect documents, ensuring data integrity but complicating queries. Understanding these methods is crucial for efficient database design. Most MongoDB drivers support DBRefs, enabling seamless relationship management across various platforms.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads