MongoDB - Blog - dev.to + LinkedIn Post

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MyrinNew
    Senior Member
    • Feb 2024
    • 5175

    #1

    MongoDB - Blog - dev.to + LinkedIn Post

    Objective

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


    Create (Insert)

    Insert at least 5 student records into the students collection.






    // Task — Create (Insert)
    const { MongoClient } = require("mongodb");

    // Atlas connection string
    const uri = "mongodb+srv://William:4dwQ454VgRgDtNSO@assignment.jfmqse7.mongod b.net/?retryWrites=true&w=majority&appName=Assignment";

    async function run() {
    const client = new MongoClient(uri);

    try {
    await client.connect();
    console.log("Connected to MongoDB Atlas");

    const db = client.db("Assign6");
    const students = db.collection("students");

    // 5 student records
    const studentData = [
    { student_id: "S001", name: "John", age: 20, department: "CSBS", year: 2, cgpa: 9.0 },
    { student_id: "S002", name: "Emma", age: 21, department: "ECE", year: 3, cgpa: 8.7 },
    { student_id: "S003", name: "Liam", age: 19, department: "MECH", year: 1, cgpa: 8.3 },
    { student_id: "S004", name: "Olivia", age: 22, department: "CSBS", year: 4, cgpa: 9.2 },
    { student_id: "S005", name: "Noah", age: 20, department: "EEE", year: 2, cgpa: 7.8 }
    ];

    const result = await students.insertMany(studentData);
    console.log(`Successfully inserted ${result.insertedCount} student documents!`);

    } catch (err) {
    console.error("Error:", err);
    } finally {
    await client.close();
    console.log("Connection closed.");
    }
    }

    run();






















    Read (Query)

    • Display all student records.
    • Find all students with CGPA > 8.
    • Find students belonging to the Computer Science department.




    // Task 2️ Read (Query)
    const { MongoClient } = require("mongodb");

    // Atlas connection string
    const uri = "mongodb+srv://William:4dwQ454VgRgDtNSO@assignment.jfmqse7.mongod b.net/?retryWrites=true&w=majority&appName=Assignment\n" ;

    async function run() {
    const client = new MongoClient(uri);

    try {
    await client.connect();
    console.log("Connected to MongoDB Atlas");

    const db = client.db("Assign6");
    const students = db.collection("students");

    // Display all student records
    const allStudents = await students.find().toArray();
    console.log("\nAll Students:");
    console.table(allStudents.map(s => ({
    student_id: s.student_id,
    name: s.name,
    age: s.age,
    department: s.department,
    year: s.year,
    cgpa: s.cgpa
    })));

    // Find all students with CGPA > 8
    const highCgpaStudents = await students.find({ cgpa: { $gt: 8 } }).toArray();
    console.log("\nStudents with CGPA > 8:");
    console.table(highCgpaStudents.map(s => ({
    student_id: s.student_id,
    name: s.name,
    cgpa: s.cgpa
    })));

    // Find students belonging to Computer Science department
    const csStudents = await students.find({ department: "CSE" }).toArray();
    console.log("\nComputer Science Department Students:");
    console.table(csStudents.map(s => ({
    student_id: s.student_id,
    name: s.name,
    year: s.year,
    cgpa: s.cgpa
    })));

    } catch (err) {
    console.error("Error:", err);
    } finally {
    await client.close();
    console.log("Connection closed.");
    }
    }

    run();
















    Update

    • Update the CGPA of a specific student.
    • Increase the year of study for all 3rd year students by 1.




    // Task 3️ — Update
    const { MongoClient } = require("mongodb");

    // connection string
    const uri = "mongodb+srv://William:4dwQ454VgRgDtNSO@assignment.jfmqse7.mongod b.net/?retryWrites=true&w=majority&appName=Assignment";

    async function run() {
    const client = new MongoClient(uri);

    try {
    await client.connect();
    console.log("Connected to MongoDB Atlas");

    const db = client.db("Assign6");
    const students = db.collection("students");

    // 1️ Update CGPA of a specific student (e.g., student_id = S002)
    const updateCGPAResult = await students.updateOne(
    { student_id: "S002" }, // filter
    { $set: { cgpa: 9.0 } } // new CGPA
    );
    console.log(`Updated CGPA for S002 — modifiedCount: ${updateCGPAResult.modifiedCount}`);

    // 2️ Increase year of all 3rd-year students by 1
    const increaseYearResult = await students.updateMany(
    { year: 3 }, // filter
    { $inc: { year: 1 } } // increment year by 1
    );
    console.log(`Increased year for ${increaseYearResult.modifiedCount} student(s)`);

    // Display updated collection
    const updatedStudents = await students.find().toArray();
    console.log("\nUpdated Students Collection:");
    console.table(updatedStudents.map(s => ({
    student_id: s.student_id,
    name: s.name,
    year: s.year,
    cgpa: s.cgpa
    })));

    } catch (err) {
    console.error("Error:", err);
    } finally {
    await client.close();
    console.log("Connection closed.");
    }
    }

    run();










    Delete

    • Delete one student record by student_id.
    • Delete all students having CGPA




    const { MongoClient } = require("mongodb");

    const uri = "mongodb+srv://William:4dwQ454VgRgDtNSO@assignment.jfmqse7.mongod b.net/?retryWrites=true&w=majority&appName=Assignment";

    async function run() {
    const client = new MongoClient(uri);

    try {
    await client.connect();
    console.log("Connected to MongoDB Atlas");

    const db = client.db("Assign6");
    const students = db.collection("students");

    // Delete one student record by student_id (example: S004)
    const deleteOneResult = await students.deleteOne({ student_id: "S004" });
    console.log("Deleted student S004 — deletedCount:", deleteOneResult.deletedCount);

    // Delete all students having CGPA const deleteManyResult = await students.deleteMany({ cgpa: { $lt: 7.5 } });
    console.log("Deleted students with CGPA
    // Display remaining collection
    const remainingStudents = await students.find().toArray();
    console.log("Remaining Students Collection:");
    console.table(remainingStudents.map(s => ({
    student_id: s.student_id,
    name: s.name,
    year: s.year,
    cgpa: s.cgpa
    })));

    } catch (err) {
    console.error("Error:", err);
    } finally {
    await client.close();
    console.log("Connection closed.");
    }
    }

    run();













    More...
Working...