DEV Community

SANCHAYAA S 24CB052
SANCHAYAA S 24CB052

Posted on

🌱 Hands-on with MongoDB CRUD Operations:

🎯 Objective

To gain hands-on experience in performing CRUD (Create, Read, Update, Delete) operations in MongoDB using a simple college student schema.

MongoDB, a popular NoSQL database, stores data in flexible, JSON-like documents. This makes it ideal for projects that require scalability, real-time analytics, and easy data handling.

🧩 Schema Design

We’ll use a collection called students.
Each student document follows this structure:

{
"student_id": "S001",
"name": "Sanchayaa",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}
🔹 1️⃣ CREATE (Insert Data)

Let’s add 5 sample student records.
use collegeDB;

db.students.insertMany([
{ "student_id": "S001", "name": "San", "age": 20, "department": "CSBS", "year": 2, "cgpa": 9 },
{ "student_id": "S002", "name": "Meena", "age": 21, "department": "CSE", "year": 3, "cgpa": 8.5 },
{ "student_id": "S003", "name": "Arun", "age": 19, "department": "ECE", "year": 1, "cgpa": 7.2 },
{ "student_id": "S004", "name": "Divya", "age": 22, "department": "CSE", "year": 3, "cgpa": 9.1 },
{ "student_id": "S005", "name": "Vikram", "age": 20, "department": "MECH", "year": 2, "cgpa": 8 }
]);

🔹 2️⃣ READ (Query Data)
➤ Display all student records
db.students.find().pretty();

➤ Find all students with CGPA > 8
db.students.find({ cgpa: { $gt: 8 } });

➤ Find students belonging to the Computer Science department
db.students.find({ department: "CSE" });

✅ Result: MongoDB displays only the filtered student documents that match the criteria.

🔹 3️⃣ UPDATE (Modify Data)
➤ Update the CGPA of a specific student
db.students.updateOne(
{ student_id: "S002" },
{ $set: { cgpa: 8.9 } }
);

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

✅ Result: CGPA updated and all third-year students promoted to the next year.
🔹 4️⃣ DELETE (Remove Data)
➤ 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 } });

✅ Result: Low-performing student records removed from the collection.

Top comments (0)