DEV Community

Cover image for MongoDB CRUD Operations
Ilakkiya
Ilakkiya

Posted on

MongoDB CRUD Operations

Databases don’t always have to be tables and rows — welcome to the world of MongoDB, where data lives as flexible documents!
In this post, we’ll explore how to perform the four basic operations — Create, Read, Update, and Delete (CRUD) — using a simple college student schema in MongoDB.

We’ll be using MongoDB Atlas, a free cloud-based platform that allows you to create and manage MongoDB databases online — no installation needed!

  • Steps to Set Up.
  1. Head over to MongoDB Atlas and sign up for a free account.
  2. Create a new Cluster (choose the free M0 shared tier).
  3. Once your cluster is ready, go to Collections → Create Database.
  4. Name your database collegeDB and add a collection named students.
  5. Open the Atlas Data Explorer — this is where you’ll run all your MongoDB commands.

Schema: Student Collection

We’ll use a collection called students, where each document looks like this:

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

Create (Insert Documents)

We’ll begin by inserting five sample student records.

Read (Query Documents)

Once data is inserted, let’s retrieve it using different query conditions.
Display All Student Records

db.students.find();
Enter fullscreen mode Exit fullscreen mode

Find Students with CGPA > 8

db.students.find({ cgpa: { $gt: 8 } });
Enter fullscreen mode Exit fullscreen mode


Find Students from the Computer Science Department

db.students.find({ department: "CSBS" });
Enter fullscreen mode Exit fullscreen mode

Update (Modify Documents)

Update a Specific Student’s CGPA

db.students.updateOne(
  { student_id: "S001" },
  { $set: { cgpa: 8 } }
);
Enter fullscreen mode Exit fullscreen mode

Increase the Year of Study for All 3rd-Year Students

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

Delete (Remove Documents)

Delete One Student by ID

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

Enter fullscreen mode Exit fullscreen mode

Delete All Students with CGPA < 7.5

Summary

✔ Create → Add new student documents
✔ Read → Query and filter documents efficiently
✔ Update → Modify existing records dynamically
✔ Delete → Safely remove unwanted data

MongoDB makes database handling simple, fast, and flexible — perfect for modern applications that evolve with changing data needs.

mongodb #nosql #crud #database #learning #devcommunity #webdev

Top comments (0)