CRUD Operations in MongoDB for Beginners
mongodb #database #tutorial #beginners
MongoDB is a widely used NoSQL database that offers flexibility and scalability for modern applications. Unlike traditional SQL databases, MongoDB stores data as JSON-like documents, making it perfect for handling dynamic and complex data structures.
In this article, we’ll explore the CRUD operations — Create, Read, Update, and Delete — in MongoDB through a simple student database example. You’ll learn how to insert, retrieve, modify, and remove records while getting hands-on with MongoDB Atlas, the cloud-based version of MongoDB.
🎯 Learning Outcomes
By the end of this tutorial, you’ll understand how to:
Insert one or multiple documents into a collection
Retrieve and filter data using queries
Update single or multiple documents
Delete documents based on specific conditions
Apply CRUD logic in real-world development
⚙ Setup: Creating Your MongoDB Cluster
Create a free account on MongoDB Atlas
Set up a cluster and a database named collegeDB
Inside it, create a collection called STUDENTS
Once your setup is ready, let’s dive into the CRUD operations.
🟢 CREATE (INSERT)
We’ll begin by inserting student data into our STUDENTS collection. Each record represents a student as a separate document.
{
"student_id": "S001",
"name": "Harsh",
"age": 20,
"department": "CSBS",
"year": 2,
"cgpa": 9
}
{
"student_id": "S002",
"name": "ini",
"age": 21,
"department": "CSBS",
"year": 3,
"cgpa": 8.5
}
{
"student_id": "S003",
"name": "madh",
"age": 20,
"department": "MI",
"year": 3,
"cgpa": 8
}
{
"student_id": "S005",
"name": "nidh",
"age": 20,
"department": "CIVIL",
"year": 2,
"cgpa": 8.8
}
{
"student_id": "S006",
"name": "rohi",
"age": 22,
"department": "CSE",
"year": 3,
"cgpa": 9.2
}
Let’s fetch data from our collection based on certain conditions.
Find students with CGPA greater than 8:
db.students.find({ cgpa: { $gt: 8 } })
Find students belonging to the Computer Science department:
db.students.find({ department: "CSE" })
We can update student details such as CGPA or department.
For example, to update a specific student’s CGPA:
db.students.updateOne(
{ student_id: "S005" },
{ $set: { cgpa: 9.0 } }
)
To remove a student record from the database, use:
db.students.deleteOne({ student_id: "S004" })
You’ll now see that the inserted, queried, updated, and deleted data reflect directly in your MongoDB Atlas Dashboard — making it easy to visualize every operation.
🧠 CONCLUSION
We’ve successfully explored CRUD operations in MongoDB using a practical student database. From inserting and querying to updating and deleting, you now have a clear understanding of how to manage data in MongoDB effectively.
These CRUD fundamentals are the backbone of most applications — whether managing users, products, or student records.
A special thanks to Mr. @santhoshnc for guiding and inspiring us to explore new technologies and keep learning! 🚀
Top comments (0)