Hands-On CRUD Operations in MongoDB Using a Student Schema
MongoDB is a popular NoSQL database that stores data in flexible, JSON-like documents rather than traditional tables. In this tutorial, we’ll explore CRUD operations (Create, Read, Update, Delete) using a simple college student schema. By the end, you’ll be comfortable performing these operations in MongoDB Atlas.
Student Schema
Each student document follows this structure:
{
"student_id": "S001",
"name": "Santhosh",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}
We will use a collection called students to store these documents.
1️⃣ Create (Insert) Students
We’ll insert 5 student records into the students collection.
{ "student_id": "S001", "name": "Santhosh", "age": 20, "department": "CSBS", "year": 2, "cgpa": 9 },
{ "student_id": "S002", "name": "Kiran", "age": 21, "department": "CSE", "year": 3, "cgpa": 8.5 },
{ "student_id": "S003", "name": "Anita", "age": 19, "department": "ECE", "year": 2, "cgpa": 7.8 },
{ "student_id": "S004", "name": "Ramesh", "age": 22, "department": "CSE", "year": 3, "cgpa": 8.2 },
{ "student_id": "S005", "name": "Priya", "age": 20, "department": "CSBS", "year": 1, "cgpa": 9.1 }
]);
💡 Tip: insertMany() allows inserting multiple documents in one
command.
2️⃣ Read (Query) Students
Display all students:
db.students.find().pretty();
db.students.find({ "cgpa": { $gt: 8 } });
Find students in the Computer Science department (CSE):
db.students.find({ "department": "CSE" });
`
3️⃣ Update Students
Update CGPA of a specific student (S002):
db.students.updateOne(
{ "student_id": "S002" },
{ $set: { "cgpa": 9 } }
);
Increase year of all 3rd-year students by 1:
`
db.students.updateMany(
{ "year": 3 },
{ $inc: { "year": 1 } }
);
`
💡 Tip: $set updates a field, while $inc increments numerical values.
4️⃣ Delete Students
Delete a student by student_id (S003):
db.students.deleteOne({ "student_id": "S003" });
Delete all students with CGPA < 7.5:
db.students.deleteMany({ "cgpa": { $lt: 7.5 } });
Conclusion
In this tutorial, we explored how to create, read, update, and delete student records in MongoDB using a simple schema. MongoDB Atlas makes database management interactive and easy, giving us hands-on experience with real-world operations.
Final Collection Sample
[{ "student_id": "S002", "name": "Kiran", "age": 21, "department": "CSE", "year": 3, "cgpa": 8.5 },
{ "student_id": "S003", "name": "Anita", "age": 19, "department": "ECE", "year": 2, "cgpa": 7.8 },
{ "student_id": "S004", "name": "Ramesh", "age": 22, "department": "CSE", "year": 3, "cgpa": 8.2 }]
📌 Deliverables for this assignment:
- MongoDB queries (insert, find, update, delete)
- Screenshots of query execution in MongoDB Atlas
- Export of the final students collection as JSON/CSV
Special thanks to @santhoshnc Sir for guiding and encouraging me throughout this assignment. Your mentorship made learning MongoDB hands-on and enjoyable! 🙏
Top comments (0)