DEV Community

SASHMITHA G 24CB054
SASHMITHA G 24CB054

Posted on

Hands-On MongoDB CRUD Operations with a College Student Schema

MongoDB is a powerful NoSQL database that allows flexible storage of JSON-like documents. In this blog, we’ll explore CRUD operations — Create, Read, Update, and Delete — using a simple college students collection.

🧱 Step 1: Create (Insert)

We start by inserting student records into the students collection. Each document follows this structure:

{
"student_id": "S001",
"name": "Soniya",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}

Insert five students:

db.students.insertMany([
{ "student_id": "S001", "name": "Soniya", "age": 20, "department": "CSBS", "year": 2, "cgpa": 9 },
{ "student_id": "S002", "name": "Isha", "age": 21, "department": "CSE", "year": 3, "cgpa": 8.5 },
{ "student_id": "S003", "name": "Sashmi", "age": 22, "department": "ECE", "year": 4, "cgpa": 7.2 },
{ "student_id": "S004", "name": "Priya", "age": 19, "department": "CSBS", "year": 1, "cgpa": 9.3 },
{ "student_id": "S005", "name": "Alice", "age": 20, "department": "Mechanical", "year": 2, "cgpa": 6.8 }
]);

🔍 Step 2: Read (Query)

  1. Display all student records:

db.students.find().pretty();

  1. Find students with CGPA > 8:

db.students.find({ cgpa: { $gt: 8 } }).pretty();

  1. Find students from the Computer Science department (CSBS):

db.students.find({ department: "CSBS" }).pretty();

✏ Step 3: Update

  1. Update CGPA of a specific student (e.g., student_id = "S002"):

db.students.updateOne(
{ student_id: "S002" },
{ $set: { cgpa: 8.8 } }
);

  1. Increase the year of study for all 3rd year students by 1:

db.students.updateMany(
{ year: 3 },
{ $inc: { year: 1 } }
);


🗑 Step 4: Delete

  1. Delete a student by student_id (e.g., "S005"):

db.students.deleteOne({ student_id: "S005" });

  1. Delete all students with CGPA < 7.5:

db.students.deleteMany({ cgpa: { $lt: 7.5 } });


🧠 Key Takeaways

Create: Insert documents using insertOne or insertMany.

Read: Use find with filters to query documents.

Update: Modify single or multiple documents using updateOne/updateMany.

Delete: Remove documents with deleteOne or deleteMany.

MongoDB makes CRUD operations intuitive and flexible, especially for JSON-like data structures, making it perfect for applications like student management systems.

Thank you @santhoshnc sir for guiding me..

MongoDB #NoSQL #CRUD #DatabaseLearning #DataEngineering #DevCommunity

Top comments (0)