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


No comments:

Post a Comment

Featured Post

Extra Challenge: Using References Between Documents

  🎯 💡 Extra Challenge: Using References Between Documents Here's an  Extra Challenge  designed to build on the original MongoDB mod...

Popular Posts