Hands-On with MongoDB: Performing CRUD Operations on a College Student Database
MongoDB is a popular NoSQL database that stores data in JSON-like documents, making it flexible and easy to use. In this blog, we’ll explore CRUD operations (Create, Read, Update, Delete) using a simple college student schema.
This is a perfect exercise for anyone looking to get hands-on experience with MongoDB.
Student Schema
We’ll use a collection called students
. Each document has the following structure:
{
"student_id": "S001",
"name": "Santhosh",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}
Create (Insert) Records
Let’s start by adding 5 students to the database.
db.students.insertMany([
{ "student_id": "S001", "name": "Santhosh", "age": 20, "department": "CSBS", "year": 2, "cgpa": 9 },
{ "student_id": "S002", "name": "Kriti", "age": 20, "department": "CSE", "year": 4, "cgpa": 7.8 },
{ "student_id": "S003", "name": "Meera", "age": 19, "department": "ECE", "year": 1, "cgpa": 7.8 },
{ "student_id": "S004", "name": "Rohit", "age": 22, "department": "CSE", "year": 3, "cgpa": 6.9 },
{ "student_id": "S005", "name": "Siddu", "age": 20, "department": "ECE", "year": 3, "cgpa": 9.5 }
])
Read (Query) Records
Find students with CGPA greater than 8
{ cgpa: { $gt: 8 } }
Find students from the Computer Science department
{"department":{"in": ["CSE"]} }
Update Records
Update the CGPA of a specific student (S001)
{ "$set: : {"cgpa":8.9}}
Increase the year of study for all 3rd year students by 1.
{ "$inc" : {"year" : 1}}
Delete
Delete one student record by student_id.
{"student_id" : S005 }
Delete all students having CGPA < 7.5.
{ "cgpa" : {"$lt" : 7.5}}
CONCLUSION
MongoDB makes it easy to handle data with flexible documents. Performing CRUD operations allows you to:
- Insert multiple records quickly
- Query data efficiently
- Update records in bulk or individually
- Delete unnecessary or outdated data
Practicing CRUD operations is a great way to get comfortable with NoSQL databases and start building your own projects.
Top comments (0)