Relationships in MongoDB

  • In MongoDB, relationships between documents are not as strictly defined as in SQL-based databases. Instead of using joins or foreign keys, MongoDB handles relationships by embedding documents or referencing documents. Here’s a detailed explanation of both types of relationships, with examples.
Types of Relationships in MongoDB:
  • One-to-One Relationship
  • One-to-Many Relationship
  • Many-to-Many Relationship
One-to-One Relationship
  • A one-to-one relationship exists when one document in a collection is related to one document in another collection. This can be handled by embedding one document inside another or referencing the related document.
Example (Embedding):
  • Suppose you have a Users collection, and each user has a unique profile stored in the Profiles collection. You can embed the Profile document directly inside the User document.


    {
        "_id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "profile": {
            "age": 29,
            "gender": "Male",
            "address": "1234 Elm Street"
        }
    }

Example (Referencing):

  • You could also keep the Profiles in a separate collection and reference the Profile document in the Users collection using the profile's ID.

    // Users Collection:
    {
        "_id": 1,
        "name": "John Doe",
        "email": "john@example.com",
        "profile_id": 101
    }

    // Profiles Collection:
    {
        "_id": 101,
        "age": 29,
        "gender": "Male",
        "address": "1234 Elm Street"
    }

  • Here, the profile_id is used to reference the corresponding profile in the Profiles collection.
One-to-Many Relationship
  • In a one-to-many relationship, a single document is related to many documents in another collection. This is commonly used when a single entity has multiple associated entities.
Example (Embedding):
  • Suppose you have an Authors collection, and each author has multiple books. You can embed the books inside the author document.

    {
        "_id": 1,
        "name": "J.K. Rowling",
        "books": [
            {
                "title": "Harry Potter and the Sorcerer's Stone",
                "year": 1997
            },
            {
                "title": "Harry Potter and the Chamber of Secrets",
                "year": 1998
            }
        ]
    }


Example (Referencing):

  • Alternatively, you can store the books in a separate collection and reference them in the author document.

    // Authors Collection:
    {
        "_id": 1,
        "name": "J.K. Rowling",
        "book_ids": [
            101,
            102
        ]
    }

    // Books Collection:
    {
        "_id": 101,
        "title": "Harry Potter and the Sorcerer's Stone",
        "year": 1997,
        "author_id": 1
    }

    {
        "_id": 102,
        "title": "Harry Potter and the Chamber of Secrets",
        "year": 1998,
        "author_id": 1
    }

  • This creates a one-to-many relationship where an author can have multiple books.
Many-to-Many Relationship
  • In a many-to-many relationship, multiple documents in one collection can relate to multiple documents in another collection. This is typically managed using references.
Example (Referencing):
  • Suppose you have a Students collection and a Courses collection, where students can enroll in multiple courses, and each course can have multiple students.

    // Students Collection:
    {
        "_id": 1,
        "name": "Alice",
        "course_ids": [
            101,
            102
        ]
    }

    {
        "_id": 2,
        "name": "Bob",
        "course_ids": [
            101
        ]
    }

    // Courses Collection:
    {
        "_id": 101,
        "course_name": "Math 101",
        "student_ids": [
            1,
            2
        ]
    }

    {
        "_id": 102,
        "course_name": "Physics 101",
        "student_ids": [
            1
        ]
    }

  • In this case, a student can enroll in many courses, and a course can have many students. The course_ids field in the Students collection and the student_ids field in the Courses collection establish the many-to-many relationship.
Choosing Between Embedding and Referencing
  • Embedding is preferred when:
    • The relationship is tightly coupled (e.g., profile data inside a user document).
    • The related data will always be retrieved along with the parent document.
    • The embedded document is relatively small and unlikely to change often.
  • Referencing is preferred when:
    • The relationship is loosely coupled (e.g., orders and customers).
    • The related data is large or frequently updated.
    • You need to maintain data consistency and avoid duplication.
Aggregation and Relationships
  • MongoDB provides the $lookup operator to join collections similar to SQL joins in referenced relationships.
Example of $lookup:
  • If you want to retrieve an author along with their books using the referencing approach, you can use the $lookup operator.

    db.authors.aggregate([
      {
        $lookup: {
          from: "books",           // The collection to join
          localField: "book_ids",   // Field from the authors collection
          foreignField: "_id",      // Field from the books collection
          as: "books"               // Output array field
        }
      }
    ])

  • This will return an author with an embedded array of books.
Conclusion
  • MongoDB provides flexibility in managing relationships between documents. Depending on your data model and use case, you can choose between embedding or referencing to design relationships efficiently. Understanding the trade-offs between the two approaches is key to building scalable and performant MongoDB applications.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...