DEV Community

NAVA (NAVA)
NAVA (NAVA)

Posted on

πŸš€ MongoDB CRUD Operations with a Student Schema

In this post, we’ll explore how to perform CRUD (Create, Read, Update, Delete) operations in MongoDB using a simple college student schema.
πŸ“Œ Student Schema
Collection: students
Each student document follows this structure:
{
"student_id": "S001",
"name": "Santhosh",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}
1️⃣ Create (Insert)
Insert at least 5 student records:
db.students.insertMany([
{ "student_id": "S001", "name": "Santhosh", "age": 20, "department": "CSBS", "year": 2, "cgpa": 9 },
{ "student_id": "S002", "name": "Priya", "age": 19, "department": "CSE", "year": 1, "cgpa": 8.5 },
{ "student_id": "S003", "name": "Arun", "age": 21, "department": "ECE", "year": 3, "cgpa": 7.8 },
{ "student_id": "S004", "name": "Meena", "age": 20, "department": "IT", "year": 2, "cgpa": 9.2 },
{ "student_id": "S005", "name": "Ravi", "age": 22, "department": "CSBS", "year": 3, "cgpa": 6.9 }
]);

2️⃣ Read (Query)
πŸ‘‰ Display all student records:
db.students.find({});
πŸ‘‰ Find all students with CGPA > 8:
db.students.find({ cgpa: { $gt: 8 } });
πŸ‘‰ Find students belonging to the Computer Science department:
db.students.find({ department: "CSBS" });



3️⃣ Update
πŸ‘‰ Update the CGPA of a specific student (say S002):
db.students.updateOne(
{ student_id: "S002" },
{ $set: { cgpa: 9.0 } }
);

πŸ‘‰ Increase the year of study for all 3rd year students by 1:
db.students.updateMany(
{ year: 3 },
{ $inc: { year: 1 } }
);


4️⃣ Delete

πŸ‘‰ Delete one student record by student_id:
db.students.deleteOne({ student_id: "S005" });

πŸ‘‰ Delete all students having CGPA < 7.5:
db.students.deleteMany({ cgpa: { $lt: 7.5 } });
πŸ“Έ Deliverables
MongoDB queries βœ…
Screenshots of execution results from MongoDB Atlas βœ…
Export of final students collection as JSON/CSV βœ…

πŸš€ Conclusion
With just a few lines of MongoDB queries, we performed CRUD operations on our students collection. This hands-on exercise demonstrates how easy and powerful MongoDB is for handling structured JSON-like documents.
Would love to hear your feedback or see how you adapt this schema for your own use cases!

Top comments (0)