๐ฏ ๐ก 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
-
Store course references in the
students
collection usingcourse_ids
-
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()
oraggregate()
to get the student -
Extract the
course_ids
-
Use
$lookup
or multiplefind()
queries to fetch related course details from thecourses
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