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

Solution MongoDB document Modelling Assignment

 Here's the complete solution to your MongoDB document modeling assignment, including:

  • ✅ Sample documents for students and courses 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


Next: Extra Practice Challenge



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