Here's the complete solution to your MongoDB document modeling assignment, including:
-
✅ Sample documents for
students
andcourses
collections -
✅ Correct JSON structure
-
✅ MongoDB queries for the bonus task
-
✅ Notes on best practices (embed vs reference)
๐งพ ✅ MongoDB Document Modeling – Solution
๐น 1. Sample Document for students
Collection
{
"student_id": 101,
"name": "Aisha Khan",
"class": "10A",
"date_of_birth": "2008-05-10T00:00:00Z",
"contact_info": {
"phone": "9876543210",
"email": "aisha.khan@example.com"
},
"marks": [
{ "subject": "Math", "score": 85 },
{ "subject": "Science", "score": 90 },
{ "subject": "English", "score": 88 }
]
}
๐น 2. Sample Document for courses
Collection
{
"course_id": 301,
"title": "Mathematics",
"teacher_name": "Mr. Arjun Mehta",
"schedule": ["Mon", "Wed", "Fri"]
}
You can insert these into MongoDB using:
db.students.insertOne({ /* student document above */ });
db.courses.insertOne({ /* course document above */ });
๐น 3. MongoDB Query – Bonus Task
Q: Find all students who scored above 80 in Math and display only their name and Math score.
✅ MongoDB Query:
db.students.find(
{ "marks": { $elemMatch: { "subject": "Math", "score": { $gt: 80 } } } },
{
"name": 1,
"marks": {
$filter: {
input: "$marks",
as: "mark",
cond: { $and: [ { $eq: ["$$mark.subject", "Math"] } ] }
}
}
}
);
๐ง Explanation:
-
$elemMatch
filters students with at least one "Math" score > 80. -
$filter
inside the projection limits returned marks to only the Math subject.
๐ Notes & Best Practices
-
Embedding marks inside the student document is useful when the marks are tightly coupled with the student (1:1 ownership).
-
Use referencing (e.g. linking course_id) when many students share the same course and you need cross-document querying or analytics.
-
Store
date_of_birth
in ISO 8601 format for date operations.
๐ง Summary
You’ve now:
-
Designed realistic NoSQL documents
-
Learned how to embed nested data
-
Queried and filtered embedded arrays
No comments:
Post a Comment