Showing posts with label #Practice-MongoDB. Show all posts
Showing posts with label #Practice-MongoDB. Show all posts

Solution: MongoDB $lookup Example: Reference Documents Tutorial

Solution: Referencing Courses in MongoDB Using $lookup


Here's the solution to the extra challenge on referencing documents in MongoDB — using course_ids in the students collection and retrieving the full course details using MongoDB’s $lookup aggregation.

Introduction

When working with MongoDB, deciding between embedding documents and referencing them is a key part of schema design. This post builds on a previous practice challenge by demonstrating how to use $lookup to retrieve related course data for a student, based on course_ids. It’s a practical example of performing manual joins in NoSQL, using aggregation pipelines.

๐Ÿงพ 1. Student Document (with course references)

{
  "student_id": 102,
  "name": "Ravi Kumar",
  "class": "10B",
  "date_of_birth": "2008-07-20T00:00:00Z",
  "contact_info": {
    "phone": "9876504321",
    "email": "ravi.kumar@example.com"
  },
  "course_ids": [301, 302],
  "marks": [
    { "subject": "Math", "score": 91 },
    { "subject": "Science", "score": 86 }
  ]
}

๐Ÿ—‚️ 2. Courses Documents (in courses collection)

{
  "course_id": 301,
  "title": "Mathematics",
  "teacher_name": "Mr. Arjun Mehta",
  "schedule": ["Mon", "Wed", "Fri"]
}
{
  "course_id": 302,
  "title": "Science",
  "teacher_name": "Ms. Reema Das",
  "schedule": ["Tue", "Thu"]
}

๐Ÿ” 3. Aggregation Query Using $lookup

db.students.aggregate([
  {
    $match: { student_id: 102 }
  },
  {
    $lookup: {
      from: "courses",                  // Collection to join
      localField: "course_ids",         // Field in students
      foreignField: "course_id",        // Field in courses
      as: "enrolled_courses"            // Output field for matched courses
    }
  },
  {
    $project: {
      _id: 0,
      name: 1,
      class: 1,
      enrolled_courses: 1
    }
  }
]);

Expected Output

{
  "name": "Ravi Kumar",
  "class": "10B",
  "enrolled_courses": [
    {
      "course_id": 301,
      "title": "Mathematics",
      "teacher_name": "Mr. Arjun Mehta",
      "schedule": ["Mon", "Wed", "Fri"]
    },
    {
      "course_id": 302,
      "title": "Science",
      "teacher_name": "Ms. Reema Das",
      "schedule": ["Tue", "Thu"]
    }
  ]
}

๐Ÿง  Key Concepts Used

Concept Purpose
$match Filters for a specific student
$lookup Joins two collections (manual join)
localField Field in the current (students) collection
foreignField Field in the other (courses) collection
$project Controls the output fields

๐Ÿง  When to Use This?

Use referencing with $lookup when:

  • You want to avoid duplicating large course data in every student document

  • You need to maintain consistency across shared data (e.g., course updates)

  • You’re modeling many-to-many or one-to-many relationships

๐Ÿ Conclusion

By using $lookup, we maintain data consistency and reduce redundancy while still retrieving complete related records across collections. This approach is especially useful for modeling relationships like students and courses in a scalable way. As you grow your MongoDB projects, mastering referencing and aggregation will be crucial for efficient data handling.



Extra Challenge: Using References Between Documents

 

๐ŸŽฏ ๐Ÿ’ก Extra Challenge: Using References Between Documents



Here's an Extra Challenge designed to build on the original MongoDB modeling task. This one introduces referencing between collections, helping learners understand when to use references instead of embedding — a key design concept in NoSQL databases like MongoDB.


๐Ÿ“Œ Scenario

Instead of embedding full course details in each student document (which can lead to duplication), you'll now reference courses using course_id.


๐Ÿ”น Step 1: Modify the Student Document

Update your students collection to reference enrolled courses like this:

{
  "student_id": 102,
  "name": "Ravi Kumar",
  "class": "10B",
  "date_of_birth": "2008-07-20T00:00:00Z",
  "contact_info": {
    "phone": "9876504321",
    "email": "ravi.kumar@example.com"
  },
  "course_ids": [301, 302],  // References to course documents
  "marks": [
    { "subject": "Math", "score": 91 },
    { "subject": "Science", "score": 86 }
  ]
}

๐Ÿ”น Step 2: Sample Courses (Already Inserted)

{
  "course_id": 301,
  "title": "Mathematics",
  "teacher_name": "Mr. Arjun Mehta",
  "schedule": ["Mon", "Wed", "Fri"]
}
{
  "course_id": 302,
  "title": "Science",
  "teacher_name": "Ms. Reema Das",
  "schedule": ["Tue", "Thu"]
}

๐Ÿ” Challenge Task

  1. Store course references in the students collection using course_ids

  2. Write a MongoDB query to retrieve a student’s name and the full details of the courses they are enrolled in


๐Ÿง  Hint for the Query

You’ll need to:

  • Use findOne() or aggregate() to get the student

  • Extract the course_ids

  • Use $lookup or multiple find() queries to fetch related course details from the courses collection

๐Ÿ”ง This mimics a one-to-many relationship without embedding full course documents.


๐Ÿง  Why This Matters

  • Demonstrates when and why referencing is better than embedding

  • Teaches the concept of manual joins in NoSQL

  • Prepares learners for more advanced aggregation and relationship modeling in MongoDB



  •  solution using $lookup (MongoDB aggregation): coming next


Featured Post

Number Guessing Game (code) in python

← Back to Projects About the project: This is a simple number guessing game and it is suitable for beginners who are learning python progra...

Popular Posts