MongoDB is one of the most popular NoSQL databases used by developers today for building modern, scalable applications. Unlike traditional relational databases, MongoDB stores data in flexible JSON-like documents, making it easier to work with real-world scenarios.
In this blog, We’ll walk through CRUD operations (Create, Read, Update, Delete) in MongoDB using a simple example: a student database. We’ll insert student details, query them, update academic information, and even delete records.
To make it more exciting, we’ll run these queries directly on MongoDB Atlas Cluster (cloud-based MongoDB). Along the way, I’ll include screenshots of my MongoDB Atlas dashboard and outputs so you can follow along visually.
Outcome:-
How to insert multiple documents into a collection
How to read and filter records using queries
How to update documents (single & multiple)
How to delete documents based on conditions
How CRUD fits into real-world development
Setup: Creating a Cluster
Create a free MongoDB Atlas account
Create a cluster and a database called collegeDB
Inside it, create a collection called STUDENTS
Create (Insert):-
Insert at least 5 student records into the students collection.
We cannot start by inserting 5 student records into our students collection together. We can create each student as separate document.
Code:-
{
student_id: "S001",
name: "Harshitha",
age: 20,
department: "CSBS",
year: 2,
cgpa: 9
}
{
student_id: "S002",
name: "Madhummitha",
age: 21,
department: "CSBS",
year: 3,
cgpa: 8.5
}
{
student_id: "S003",
name: "Lokhitha",
age: 20,
department: "MI",
year: 3,
cgpa: 8
}
{
student_id: "S004",
name: "Hareesh",
age: 22,
department: "IT",
year: 3,
cgpa: 9.2
}
{
student_id: "S001",
name: "Harshitha",
age: 20,
department: "CSBS",
year: 2,
cgpa: 9
}
{
student_id: "S002",
name: "Madhummitha",
age: 21,
department: "CSBS",
year: 3,
cgpa: 8.5
}
READ(QUERY)
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" })
UPDATE
Update the CGPA of a specific student.
{ "student_id": "S005" }
Delete:-
Delete one student record by student_id.
{ "student_id": "S004" }
RESULT
Conclusion:-
In this blog, we explored how to perform CRUD operations in MongoDB using a real-world example of a student database. Starting from inserting records, querying based on conditions, updating multiple documents, and finally deleting specific records – we’ve covered the foundation of working with MongoDB.
CRUD operations form the building blocks of every application, whether you’re managing users in a website, products in an e-commerce app, or students in a college system.
Thanks to Mr.@santhoshnc for encouraging us in exploring new paths in technology and gain knowledge.
Top comments (0)