DEV Community

Ramya
Ramya

Posted on

Mastering MongoDB CRUD with a College Students Collection

MongoDB is a dynamic NoSQL database that stores data in flexible, JSON-like documents. In this guide, we’ll dive into CRUD operations — Create, Read, Update, and Delete — using a simple college students collection.
Step 1: Create (Insert)

Let’s start by adding student records to the students collection. Each document has 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)

View all student records:

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

Find students with CGPA greater than 8:

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

Find students from the Computer Science department (CSBS):

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

✏ Step 3: Update

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

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

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

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

🗑 Step 4: Delete

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

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

Delete all students with CGPA less than 7.5:

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

🧠 Key Takeaways

Create: Add documents using insertOne or insertMany.

Read: Query documents using find() with filters.

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

Delete: Remove documents using deleteOne or deleteMany.

MongoDB makes managing JSON-like data intuitive and flexible, making it ideal for applications like student management systems.

Top comments (0)