DEV Community

Nethra Loganathan
Nethra Loganathan

Posted on

CRUD Operations in MongoDB

Introduction

MongoDB is one of the most popular NoSQL databases used for building modern, scalable applications. Unlike traditional relational databases, MongoDB stores data in flexible JSON-like documents, making it perfect for handling real-world scenarios.

In this blog, we’ll explore CRUD operations (Create, Read, Update, Delete) with MongoDB using a simple example — a college student database.

1.create (Insert)

We start by inserting student records into our students collection.

Each student is stored as a document:

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

Insert multiple students at once:

use college;

db.students.insertMany([
{
"student_id": "S001",
"name": "Santhosh",
"age": 20,
"department": "Computer Science",
"year": 2,
"cgpa": 9
},
{
"student_id": "S002",
"name": "Priya",
"age": 21,
"department": "Computer Science",
"year": 3,
"cgpa": 8.5
},
{
"student_id": "S003",
"name": "Arjun",
"age": 19,
"department": "Electronics",
"year": 3,
"cgpa": 7.2
},
{
"student_id": "S004",
"name": "Meera",
"age": 22,
"department": "Computer Science",
"year": 1,
"cgpa": 6.8
},
{
"student_id": "S005",
"name": "Nethra",
"age": 20,
"department": "CSBS",
"year": 3,
"cgpa": 9.2
}
]);

2.read (Query)

Fetch all students:

db.students.find({});

Find all students with CGPA > 8:

db.students.find({ cgpa: { $gt: 8 } });

Find all students belonging to the CSE department:

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

3.Update

Update the CGPA of a specific student:

db.students.updateOne(
{ student_id: "S005" },
{ $set: { cgpa: 9.2};

Increase year of study for all 3rd-year students:

db.students.updateMany(
{ year: 3 },
{ $inc: { year: 1 } }
);

4.Delete

Delete one student record by ID:

db.students.deleteOne({ student_id: "S004" });

Delete all students with CGPA < 7.5:

db.students.deleteMany({ cgpa: { $lt: 7.5 } });

Conclusion

In this blog, we explored how to perform CRUD operations in MongoDB with a student database.

We:
✔ Inserted multiple student records
✔ Queried documents with filters
✔ Updated single and multiple documents
✔ Deleted records selectively

Top comments (0)