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)
- Display all student records:
db.students.find().pretty();
- Find students with CGPA > 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 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 < 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.
Next Steps
Take screenshots of your execution in MongoDB Atlas.
Export the final students collection as JSON or CSV for backup or further analysis.
Read (Query)
A.Display all students
{}
Students with CGPA > 8
{ "cgpa": { "$gt": 8 } }
Students in CSBS department
{ "department": { "$in": ["CSBS"] } }
Update
A.Update CGPA of a specific student (S002)
{ "student_id": "S002" }
Increase year of all 3rd year students by 1
{ "year": 3 }
Delete
A. Delete one student by student_id (S005)
{ "student_id": "S004" }
B. Delete all students with CGPA < 7.5
{ "cgpa": { "$lt": 7.5 } }
Top comments (0)