DEV Community

Mukesh B
Mukesh B

Posted on

MongoDB CRUD Operations using a College Student Schema

🎯 Objective

The goal of this lab is to gain hands-on experience with performing basic CRUD (Create, Read, Update, Delete) operations in MongoDB Atlas using a simple college student schema.

We’ll use a students collection with fields like student_id, name, age, department, year, and cgpa.

🧱 Schema Structure

Each document in the students collection follows this structure:

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

βš™οΈ Step 1: Connect to MongoDB Atlas

πŸͺ„ Step 2: Create the Database and Collection
use college;

db.createCollection("students");

βœ… This creates a new database named college and a collection named students.

πŸ“Έ Screenshot: Collection created in Atlas.

🧩 Step 3: CREATE β€” Insert Student Records

We’ll insert at least 5 documents into the collection.

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

βœ… Inserted 5 student documents successfully.

πŸ” Step 4: READ β€” Query Student Records
πŸ“— 4.1 Display All Student Records
db.students.find();

πŸ“˜ 4.2 Find Students with CGPA > 8
db.students.find({ cgpa: { $gt: 8 } });

βœ… Displays all high-performing students.

πŸ“™ 4.3 Find Students from Computer Science Department
db.students.find({ department: "CSE" });

or for CSBS:

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

πŸ“˜ Description:
Filters documents where department equals CSE or CSBS.

✏️ Step 5: UPDATE β€” Modify Data
🧾 5.1 Update CGPA of a Specific Student
db.students.updateOne(
{ student_id: "S002" },
{ $set: { cgpa: 8.9 } }
);

βœ… Updates Meena’s CGPA to 8.9.

πŸ“ˆ 5.2 Increase Year of Study for All 3rd-Year Students by 1
db.students.updateMany(
{ year: 3 },
{ $inc: { year: 1 } }
);

βœ… Increments the year field for all 3rd-year students.

❌ Step 6: DELETE β€” Remove Data
πŸ—‘οΈ 6.1 Delete One Student by student_id
db.students.deleteOne({ student_id: "S005" });

βœ… Removes the student named Ravi (S005).

🚫 6.2 Delete All Students Having CGPA < 7.5
db.students.deleteMany({ cgpa: { $lt: 7.5 } });

βœ… Deletes all underperforming students.

Top comments (0)