DEV Community

Baviya Varshini V
Baviya Varshini V

Posted on

CRUD (Create, Read, Update, Delete) operations in MongoDB using a simple college student schema.

To gain hands-on experience in performing CRUD (Create, Read, Update, Delete) operations in MongoDB using a simple college student schema.

🧱 Schema (Collection: students)

Each document follows this structure:

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

Enter fullscreen mode Exit fullscreen mode

⚙️ 1️⃣ CREATE (INSERT)
Insert at least 5 student records into the students collection:

db.students.insertMany([
  {
    "student_id": "S001",
    "name": "Santhosh",
    "age": 20,
    "department": "CSBS",
    "year": 2,
    "cgpa": 9
  },
  {
    "student_id": "S002",
    "name": "Baviya",
    "age": 19,
    "department": "CSE",
    "year": 1,
    "cgpa": 8.7
  },
  {
    "student_id": "S003",
    "name": "Karthik",
    "age": 21,
    "department": "ECE",
    "year": 3,
    "cgpa": 7.2
  },
  {
    "student_id": "S004",
    "name": "Anu",
    "age": 20,
    "department": "CSE",
    "year": 2,
    "cgpa": 9.3
  },
  {
    "student_id": "S005",
    "name": "Ravi",
    "age": 22,
    "department": "MECH",
    "year": 3,
    "cgpa": 6.8
  }
])

Enter fullscreen mode Exit fullscreen mode

🔍 2️⃣ READ (QUERY)

Find all students with CGPA > 8:

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

Enter fullscreen mode Exit fullscreen mode

Find students belonging to the Computer Science department:

db.students.find({ department: { $in: ["CSE", "CSBS"] } }).pretty()

Enter fullscreen mode Exit fullscreen mode

✏️ 3️⃣ UPDATE
(a) Update the CGPA of a specific student

db.students.updateOne(
  { student_id: "S002" },
  { $set: { cgpa: 9.1 } }
)

Enter fullscreen mode Exit fullscreen mode

(b) Increase the year of study for all 3rd-year students by 1

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

Enter fullscreen mode Exit fullscreen mode

🗑️ 4️⃣ DELETE
(a) Delete one student record by student_id:

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

Enter fullscreen mode Exit fullscreen mode

(b) Delete all students having CGPA < 7.5

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

Enter fullscreen mode Exit fullscreen mode

AFTER DELETION:

Top comments (0)