Showing posts with label MongoDB CRUD Example. Show all posts
Showing posts with label MongoDB CRUD Example. Show all posts

SQL vs MongoDB CRUD Assignment Solution with Full Code Example (Student Database)

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:

  1. Add the student

  2. Include marks

  3. Read/display their data

  4. Update their class and one of the marks

  5. 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!



Featured Post

Normalization vs Denormalization: SQL vs MongoDB Practice task Solution

✅ Solution: Normalization vs Denormalization Practice This tutorial provides the complete solution to the earlier practice task com...

Popular Posts