As part of learning MongoDB, I decided to practice CRUD operations (Create, Read, Update, Delete) using a simple student collection. This hands-on approach helped me understand how MongoDB handles data in a flexible, JSON-like format.
Objective
Gain practical experience with MongoDB by performing CRUD operations on a students collection.
Student schema:
{
"student_id": "S001",
"name": "Santhosh",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}
1๏ธโฃ Create (Insert)
Insert 5 student records using insertOne() or insertMany():
db.students.insertOne({ "student_id": "S001", "name": "Santhosh", "age": 20, "department": "CSBS", "year": 2, "cgpa": 9 });
db.students.insertOne({ "student_id": "S002", "name": "Anjali", "age": 21, "department": "CSE", "year": 3, "cgpa": 8.5 });
db.students.insertOne({ "student_id": "S003", "name": "Ravi", "age": 19, "department": "ECE", "year": 1, "cgpa": 7.2 });
db.students.insertOne({ "student_id": "S004", "name": "Meera", "age": 22, "department": "CSE", "year": 3, "cgpa": 9.1 });
db.students.insertOne({ "student_id": "S005", "name": "Karthik", "age": 20, "department": "MECH", "year": 2, "cgpa": 6.8 });
2๏ธโฃ Read (Query)
Display all students:
db.students.find().pretty();
Students with CGPA > 8:
db.students.find({ "cgpa": { $gt: 8 } }).pretty();
Students in Computer Science (CSE):
db.students.find({ "department": "CSE" }).pretty();
3๏ธโฃ Update
Update CGPA for a student:
db.students.updateOne(
{ "student_id": "S001" },
{ $set: { "cgpa": 9.5 } }
);
Increment year for all 3rd-year students:
db.students.updateMany(
{ "year": 3 },
{ $inc: { "year": 1 } }
);
4๏ธโฃ Delete
Delete a student by ID:
db.students.deleteOne({ "student_id": "S005" });
Delete students with CGPA < 7.5:
db.students.deleteMany({ "cgpa": { $lt: 7.5 } });
Final Thoughts
This hands-on exercise taught me:
- How MongoDB manages JSON-like documents.
- Performing CRUD operations is straightforward and powerful.
Querying, updating, and deleting data in MongoDB is very flexible compared to traditional SQL.
๐ก Practicing with small datasets like a student collection is a great way to build confidence in NoSQL databases.
Top comments (0)