Assignments Of Day 13: MongoDB Relationships (Embedding vs. Referencing)

Rashmi Mishra
0

 Assignments Of Day 13: MongoDB Relationships (Embedding vs. Referencing)

Assignment 1: Embedding Documents in MongoDB

Task:
Create a MongoDB collection for Orders, where each order contains information about the order details and the customer information. Embed the customer details inside the order document.

Solution:

1.   Create the orders collection:

o    Create a document structure where the customer data is embedded within the order.

json

CopyEdit

{

  "_id": 1,

  "order_date": "2025-01-28",

  "total_amount": 100,

  "customer": {

    "name": "Alice",

    "email": "alice@example.com",

    "phone": "1234567890"

  },

  "items": [

    { "product": "Laptop", "quantity": 1, "price": 100 }

  ]

}

2.   Explanation:

o    The customer details (e.g., name, email, and phone) are embedded directly inside the order document.

o    This allows easy retrieval of all order information along with the customer data in a single query.

o    Best suited when the customer data is small and doesn't change frequently.


Assignment 2: Referencing Documents in MongoDB

Task:
Create a MongoDB database with two collections: Customers and Orders. Use a reference to link orders to customers by using the customer’s customer_id in the orders document.

Solution:

1.   Create customers collection:

json

CopyEdit

{

  "_id": 1,

  "name": "Alice",

  "email": "alice@example.com",

  "phone": "1234567890"

}

2.   Create orders collection:

json

CopyEdit

{

  "_id": 101,

  "order_date": "2025-01-28",

  "total_amount": 100,

  "customer_id": 1,

  "items": [

    { "product": "Laptop", "quantity": 1, "price": 100 }

  ]

}

3.   Explanation:

o    The orders collection references the customer via customer_id, which links the order to a customer.

o    This structure is more flexible if customer data needs to be updated, and there’s no redundancy.


Assignment 3: Embedded Array for One-to-Many Relationship

Task:
Model a blog post that contains an array of comments. Embed the comments directly within the blog post document.

Solution:

1.   Create blog_posts collection:

json

CopyEdit

{

  "_id": 1,

  "title": "MongoDB Basics",

  "content": "Learn MongoDB with examples.",

  "comments": [

    { "author": "Alice", "text": "Great post!" },

    { "author": "Bob", "text": "Very informative." }

  ]

}

2.   Explanation:

o    The blog post document contains an array of comments.

o    Embedding is useful since a blog post and its comments are often retrieved together.

o    Ideal for cases where comments are small and not frequently updated.


Assignment 4: Many-to-Many Relationship Using Referencing

Task:
Create a MongoDB schema for students and courses, where a student can enroll in multiple courses, and a course can have multiple students. Use referencing.

Solution:

1.   Create students collection:

json

CopyEdit

{

  "_id": 1,

  "name": "John Doe",

  "enrolled_courses": [101, 102]

}

2.   Create courses collection:

json

CopyEdit

{

  "_id": 101,

  "course_name": "MongoDB Basics",

  "students_enrolled": [1, 2]

}

3.   Explanation:

o    The students collection contains a reference to the course IDs the student is enrolled in.

o    The courses collection lists the student IDs enrolled in the course.

o    This many-to-many relationship is best handled with references.


Assignment 5: Using $lookup for Joining Referenced Data

Task:
Write a query using MongoDB's aggregation framework ($lookup) to join orders and customers collections by using the customer_id.

Solution:

1.   Aggregation Query:

js

CopyEdit

db.orders.aggregate([

  {

    $lookup: {

      from: "customers",

      localField: "customer_id",

      foreignField: "_id",

      as: "customer_details"

    }

  }

])

2.   Explanation:

o    This query retrieves all orders and "joins" them with the corresponding customer details using the $lookup operator.

o    The customer_details will contain the customer document from the customers collection for each order.


Assignment 6: Handling Large Data Sets with Referencing

Task:
Design a schema for an e-commerce platform where products and reviews are in separate collections. Use referencing to store reviews for products.

Solution:

1.   Create products collection:

json

CopyEdit

{

  "_id": 1001,

  "name": "Smartphone",

  "price": 500

}

2.   Create reviews collection:

json

CopyEdit

{

  "_id": 2001,

  "product_id": 1001,

  "rating": 4,

  "comment": "Great phone!"

}

3.   Explanation:

o    The reviews collection uses product_id to reference the associated product.

o    Referencing is ideal when the number of reviews for a product could grow large and need to be stored separately.


Assignment 7: Nested Embedding in MongoDB

Task:
Model a university system where each department contains professors and courses. Embed the professor information within each department.

Solution:

1.   Create departments collection:

json

CopyEdit

{

  "_id": 1,

  "department_name": "Computer Science",

  "professors": [

    { "name": "Dr. Smith", "email": "smith@university.com" },

    { "name": "Dr. Johnson", "email": "johnson@university.com" }

  ],

  "courses": [

    { "course_name": "Database Systems", "credits": 3 },

    { "course_name": "Data Structures", "credits": 4 }

  ]

}

2.   Explanation:

o    Professors are embedded within the department, which is efficient for queries related to departments and their faculty.

o    This design is suitable for smaller datasets.


Assignment 8: Updating Referenced Data

Task:
If the customer’s address changes in the Customers collection, demonstrate how to update this reference in the Orders collection.

Solution:

1.   Update Customer’s Address in customers collection:

js

CopyEdit

db.customers.updateOne(

  { _id: 1 },

  { $set: { "address": "New Address" } }

)

2.   Explanation:

o    This update modifies the address of a customer in the customers collection.

o    Since orders only stores a reference to customer_id, no changes are needed in the orders collection unless you are caching address data.


Assignment 9: Using Embedding for Single Entity Relationships

Task:
Create a MongoDB document structure for users with embedded profiles. The profile contains the user’s address, phone number, and bio.

Solution:

1.   Create users collection:

json

CopyEdit

{

  "_id": 1,

  "username": "alice123",

  "profile": {

    "address": "123 Main St, Cityville",

    "phone": "1234567890",

    "bio": "Software Developer"

  }

}

2.   Explanation:

o    Embedding user profiles is efficient because the profile information is small and does not change frequently.

o    This ensures fast retrieval of both the user and their profile in a single query.


Assignment 10: Performance Considerations with Embedding and Referencing

Task:
Discuss the performance implications of embedding vs. referencing in MongoDB for retrieving related documents.

Solution:

1.   Embedding:

o    Best for scenarios where you need to read related data together frequently.

o    Embedding reduces the need for multiple queries, improving read performance.

o    However, it may lead to larger documents, and updates to embedded data may be more costly.

2.   Referencing:

o    Best for scenarios with large data sets or many-to-many relationships.

o    Provides flexibility and avoids redundancy.

o    However, referencing may require multiple queries or the use of aggregation pipelines like $lookup to retrieve the related data.

3.   Explanation:

o    Embedding provides faster reads but can result in performance degradation for large datasets or when updates are frequent.

o    Referencing is better for scalability and flexibility but may incur a performance cost due to additional queries.


These assignments help students understand both embedding and referencing in MongoDB and provide practical experience with these two data modeling techniques.


Post a Comment

0Comments

Post a Comment (0)

About Me