Here's the complete solution for the CRUD mini-assignment from Part 6 — in both SQL and MongoDB (NoSQL).
We’ll assume you're working with a student named "Nitin Joshi", and your task was to:
-
Add the student
-
Include marks
-
Read/display their data
-
Update their class and one of the marks
-
Delete their record
✅ SQL Solution
⚙️ Step 1: Insert into Students
Table
INSERT INTO Students (StudentID, Name, Class)
VALUES (3, 'Nitin Joshi', '10A');
⚙️ Step 2: Insert into Marks
Table (Assuming it's a separate table)
INSERT INTO Marks (MarkID, StudentID, Subject, Score)
VALUES
(201, 3, 'English', 87),
(202, 3, 'Science', 91);
⚙️ Step 3: Read Nitin's Full Profile (Using JOIN)
SELECT Students.Name, Students.Class, Marks.Subject, Marks.Score
FROM Students
JOIN Marks ON Students.StudentID = Marks.StudentID
WHERE Students.StudentID = 3;
⚙️ Step 4: Update Nitin’s Class and English Score
UPDATE Students SET Class = '10B' WHERE StudentID = 3;
UPDATE Marks
SET Score = 90
WHERE StudentID = 3 AND Subject = 'English';
⚙️ Step 5: Delete Nitin’s Records
DELETE FROM Marks WHERE StudentID = 3;
DELETE FROM Students WHERE StudentID = 3;
✅ MongoDB Solution
⚙️ Step 1: Insert Student with Marks
db.students.insertOne({
student_id: 3,
name: "Nitin Joshi",
class: "10A",
marks: [
{ subject: "English", score: 87 },
{ subject: "Science", score: 91 }
]
});
⚙️ Step 2: Read Student Document
db.students.findOne({ student_id: 3 });
⚙️ Step 3: Update Class and English Score
A. Update Class
db.students.updateOne(
{ student_id: 3 },
{ $set: { class: "10B" } }
);
B. Update English Score
Use $set
with positional operator $
to target the right array element:
db.students.updateOne(
{ student_id: 3, "marks.subject": "English" },
{ $set: { "marks.$.score": 90 } }
);
⚙️ Step 4: Delete Student
db.students.deleteOne({ student_id: 3 });
๐ฏ Key Learnings
Operation | SQL | MongoDB |
---|---|---|
Related Data | JOIN across tables | Embedded in documents |
Update nested data | Table-specific updates | Use positional operator ($ ) |
Delete | Requires foreign key cleanup | Simple deleteOne() |
๐ง Which database did you find easier — SQL or MongoDB? Comment below with your choice and why!
๐ Try modifying this example with your own student data and share your version!
No comments:
Post a Comment