umping into NoSQL? MongoDB's flexible, document-based structure makes it incredibly fast, but the query language is different from SQL. The best way to learn is by doing the basics: CRUD (Create, Read, Update, Delete).
We're going to use the MongoDB Shell (mongosh) to manage a simple college student roster.
Schema: The Student Document
Our documents in the students collection follow a clean, clear structure:
The C in CRUD: Insertion
We start by populating our collection using insertMany.
// Task 1: Insert at least 5 student records
db.students.insertMany([
// ... 5+ documents as defined in the previous response ...
]);The R in CRUD: Querying Power
Reading data is where MongoDB's JSON-like syntax shines. We use comparison operators like $gt (greater than) and $in.
// Task 2b: Find all students with CGPA > 8
db.students.find({ "cgpa": { $gt: 8 } });
// Task 2c: Find students from Computer Science departments
db.students.find({ "department": { $in: ["CSBS", "CSE"] } });
- The U in CRUD: Atomic Changes Updating documents is handled using update operators. We use $set for direct value changes and $inc to increment fields atomically. // Task 3a: Update the CGPA of a specific student (S001) db.students.updateOne( { "student_id": "S001" }, { $set: { "cgpa": 9.2 } } );
// Task 3b: Increase the year of study for all 3rd year students by 1
db.students.updateMany(
{ "year": 3 },
{ $inc: { "year": 1 } }
);
- The D in CRUD: Deletion Use deleteOne for a single, targeted removal (often by a unique ID) and deleteMany for bulk removal based on a condition. // Task 4a: Delete one student record by student_id (S006) db.students.deleteOne({ "student_id": "S006" });
// Task 4b: Delete all students having CGPA < 7.5
db.students.deleteMany({ "cgpa": { $lt: 7.5 } });
Conclusion: You've Mastered the Fundamentals!
You've successfully performed the core CRUD operations—the foundation of all database interactions. Understanding how to use the specific operators ($set, $inc, $gt, $in) is key to unlocking MongoDB's performance and flexibility.
A special acknowledgment to @santhoshnc sir, whose consistent demonstration of NoSQL best practices has been instrumental in my ability to apply these concepts effectively.
Top comments (0)