Showing posts with label MongoDB practice solution. Show all posts
Showing posts with label MongoDB practice solution. 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.



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