Practice Programs on JDBC with MongoDB

The application flow is 

MongoDb Application Flow

This diagram illustrates the basic architecture of a Java application connected to MongoDB.

  • Java Application – The application written in Java performs operations such as inserting, retrieving, updating, and deleting student data.
  • MongoDB Java Driver – Acts as a bridge between the Java application and MongoDB, allowing Java code to communicate with the database.
  • MongoDB Server – The MongoDB server receives requests from the Java application and manages the stored data.
  • studentdb Database – A database created in MongoDB to organize and store student-related information.
  • students Collection – A collection inside the studentdb database that contains student documents and their details.

Application Architecture

Application-architecture

Prerequisites

Install the following:

Java

Check Java:

java -version

Maven

Check Maven:

mvn -version

MongoDB

Make sure MongoDB Server is running.

The application will connect to:

mongodb://localhost:27017

 

Create the Maven Project

In IntelliJ IDEA:

     File -> New -> Project -> Maven

Enter: 

    GroupId : com.sample

ArtifactId : mongodb

Project name:

MongoDBStudentCRUD

 

Create below files

The pom.xml contains the MongoDB Java Driver dependency.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.sample</groupId>
    <artifactId>mongodb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
   <dependencies>
       <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
       <dependency>
           <groupId>org.mongodb</groupId>
           <artifactId>mongo-java-driver</artifactId>
           <version>3.12.14</version>
       </dependency>

   </dependencies>




</project>
package org.sample;

public class Student {

    private String id;
    private String name;
    private int age;
    private String department;
    private String email;
    private double cgpa;

    public Student() {
    }

    public Student(String name, int age, String department,
                   String email, double cgpa) {
        this.name = name;
        this.age = age;
        this.department = department;
        this.email = email;
        this.cgpa = cgpa;
    }

    public Student(String id, String name, int age,
                   String department, String email, double cgpa) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.department = department;
        this.email = email;
        this.cgpa = cgpa;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getDepartment() {
        return department;
    }

    public void setDepartment(String department) {
        this.department = department;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public double getCgpa() {
        return cgpa;
    }

    public void setCgpa(double cgpa) {
        this.cgpa = cgpa;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", department='" + department + '\'' +
                ", email='" + email + '\'' +
                ", cgpa=" + cgpa +
                '}';
    }
}
package org.sample;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Filters.eq;

public class StudentDAO {

    private final MongoCollection<Document> collection;

    public StudentDAO() {

        MongoDatabase database =
                MongoDBConnection.getDatabase();

        collection = database.getCollection("students");
    }

    // CREATE
    public String createStudent(Student student) {

        Document document = new Document()
                .append("name", student.getName())
                .append("age", student.getAge())
                .append("department", student.getDepartment())
                .append("email", student.getEmail())
                .append("cgpa", student.getCgpa());

        collection.insertOne(document);

        return document.getObjectId("_id").toHexString();
    }

    // READ ALL
    public List<Student> getAllStudents() {

        List<Student> students = new ArrayList<>();

        for (Document document : collection.find()) {

            Student student = convertDocumentToStudent(document);

            students.add(student);
        }

        return students;
    }

    // READ BY ID
    public Student getStudentById(String id) {

        Document document = collection.find(
                eq("_id", new ObjectId(id))
        ).first();

        if (document == null) {
            return null;
        }

        return convertDocumentToStudent(document);
    }

    // UPDATE
    public boolean updateStudent(String id, Student student) {

        Document updateDocument = new Document()
                .append("name", student.getName())
                .append("age", student.getAge())
                .append("department", student.getDepartment())
                .append("email", student.getEmail())
                .append("cgpa", student.getCgpa());

        var result = collection.updateOne(
                eq("_id", new ObjectId(id)),
                new Document("$set", updateDocument)
        );

        return result.getModifiedCount() > 0;
    }

    // DELETE
    public boolean deleteStudent(String id) {

        var result = collection.deleteOne(
                eq("_id", new ObjectId(id))
        );

        return result.getDeletedCount() > 0;
    }

    // Convert MongoDB Document to Student
    private Student convertDocumentToStudent(Document document) {

        return new Student(
                document.getObjectId("_id").toHexString(),
                document.getString("name"),
                document.getInteger("age"),
                document.getString("department"),
                document.getString("email"),
                document.getDouble("cgpa")
        );
    }
}
package org.sample;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class MongoDBConnection {

    private static final String CONNECTION_STRING =
            "mongodb://localhost:27017";

    private static final String DATABASE_NAME =
            "studentdb";

    private static MongoClient mongoClient;

    public static MongoDatabase getDatabase() {

        if (mongoClient == null) {
            mongoClient = MongoClients.create(CONNECTION_STRING);
        }

        return mongoClient.getDatabase(DATABASE_NAME);
    }

    public static void closeConnection() {

        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }
}
package org.sample;

import java.util.List;
import java.util.Scanner;

public class StudentApplication {

    private static final Scanner scanner =
            new Scanner(System.in);

    private static final StudentDAO studentDAO =
            new StudentDAO();

    public static void main(String[] args) {

        int choice;

        do {

            displayMenu();

            System.out.print("Enter your choice: ");
            choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {

                case 1:
                    createStudent();
                    break;

                case 2:
                    getAllStudents();
                    break;

                case 3:
                    getStudentById();
                    break;

                case 4:
                    updateStudent();
                    break;

                case 5:
                    deleteStudent();
                    break;

                case 6:
                    System.out.println(
                            "Exiting application..."
                    );
                    break;

                default:
                    System.out.println(
                            "Invalid choice!"
                    );
            }

        } while (choice != 6);

        MongoDBConnection.closeConnection();

        scanner.close();
    }

    private static void displayMenu() {

        System.out.println();
        System.out.println("================================");
        System.out.println("     STUDENT MANAGEMENT SYSTEM");
        System.out.println("================================");
        System.out.println("1. Create Student");
        System.out.println("2. Display All Students");
        System.out.println("3. Find Student By ID");
        System.out.println("4. Update Student");
        System.out.println("5. Delete Student");
        System.out.println("6. Exit");
        System.out.println("================================");
    }

    // CREATE
    private static void createStudent() {

        System.out.println("\n--- Create Student ---");

        System.out.print("Name: ");
        String name = scanner.nextLine();

        System.out.print("Age: ");
        int age = scanner.nextInt();
        scanner.nextLine();

        System.out.print("Department: ");
        String department = scanner.nextLine();

        System.out.print("Email: ");
        String email = scanner.nextLine();

        System.out.print("CGPA: ");
        double cgpa = scanner.nextDouble();
        scanner.nextLine();

        Student student = new Student(
                name,
                age,
                department,
                email,
                cgpa
        );

        String id = studentDAO.createStudent(student);

        System.out.println(
                "Student created successfully!"
        );

        System.out.println(
                "Generated ID: " + id
        );
    }

    // READ ALL
    private static void getAllStudents() {

        System.out.println("\n--- All Students ---");

        List<Student> students =
                studentDAO.getAllStudents();

        if (students.isEmpty()) {

            System.out.println(
                    "No students found."
            );

            return;
        }

        for (Student student : students) {
            System.out.println(student);
        }
    }

    // READ BY ID
    private static void getStudentById() {

        System.out.println("\n--- Find Student ---");

        System.out.print("Enter Student ID: ");
        String id = scanner.nextLine();

        try {

            Student student =
                    studentDAO.getStudentById(id);

            if (student != null) {

                System.out.println(student);

            } else {

                System.out.println(
                        "Student not found."
                );
            }

        } catch (IllegalArgumentException e) {

            System.out.println(
                    "Invalid MongoDB ObjectId."
            );
        }
    }

    // UPDATE
    private static void updateStudent() {

        System.out.println("\n--- Update Student ---");

        System.out.print("Enter Student ID: ");
        String id = scanner.nextLine();

        try {

            Student existing =
                    studentDAO.getStudentById(id);

            if (existing == null) {

                System.out.println(
                        "Student not found."
                );

                return;
            }

            System.out.print("New Name: ");
            String name = scanner.nextLine();

            System.out.print("New Age: ");
            int age = scanner.nextInt();
            scanner.nextLine();

            System.out.print("New Department: ");
            String department = scanner.nextLine();

            System.out.print("New Email: ");
            String email = scanner.nextLine();

            System.out.print("New CGPA: ");
            double cgpa = scanner.nextDouble();
            scanner.nextLine();

            Student student = new Student(
                    name,
                    age,
                    department,
                    email,
                    cgpa
            );

            boolean updated =
                    studentDAO.updateStudent(
                            id,
                            student
                    );

            if (updated) {

                System.out.println(
                        "Student updated successfully!"
                );

            } else {

                System.out.println(
                        "Student was not updated."
                );
            }

        } catch (IllegalArgumentException e) {

            System.out.println(
                    "Invalid MongoDB ObjectId."
            );
        }
    }

    // DELETE
    private static void deleteStudent() {

        System.out.println("\n--- Delete Student ---");

        System.out.print("Enter Student ID: ");
        String id = scanner.nextLine();

        try {

            boolean deleted =
                    studentDAO.deleteStudent(id);

            if (deleted) {

                System.out.println(
                        "Student deleted successfully!"
                );

            } else {

                System.out.println(
                        "Student not found."
                );
            }

        } catch (IllegalArgumentException e) {

            System.out.println(
                    "Invalid MongoDB ObjectId."
            );
        }
    }
}

Right click on the StudentApplication and Run the StudentApplication

Execution and Output:

"C:\Program Files\Java\jdk-17\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2025.3.1\lib\idea_rt.jar=50886" -Dfile.encoding=UTF-8 -classpath C:\Users\dudek\OneDrive\Desktop\mongodb\target\classes;C:\Users\dudek\.m2\repository\org\mongodb\mongo-java-driver\3.12.14\mongo-java-driver-3.12.14.jar org.sample.StudentApplication
Aug 29, 2026 7:09:37 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}

================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: Aug 29, 2026 7:09:37 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:1}] to localhost:27017
Aug 29, 2026 7:09:37 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[7, 0, 5]}, minWireVersion=0, maxWireVersion=21, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=4444300}
1

--- Create Student ---
Name: Lakshman
Age: 25
Department: IT
Email: lakshman@gmail.com
CGPA: 9.4

Aug 29, 2026 7:11:17 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:2}] to localhost:27017
Student created successfully!
Generated ID: 6a92e17dedb9333e5964473a

================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: 1

--- Create Student ---
Name: Mahesh
Age: 24
Department: IT
Email: mahesh@gmail.com
CGPA: 9.3
Student created successfully!
Generated ID: 6a92e1b1edb9333e5964473b

================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: 2

--- All Students ---
Student{id='6a92e17dedb9333e5964473a', name='Lakshman', age=25, department='IT', email='lakshman@gmail.com', cgpa=9.4}
Student{id='6a92e1b1edb9333e5964473b', name='Mahesh', age=24, department='IT', email='mahesh@gmail.com', cgpa=9.3}


================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: 3

--- Find Student ---
Enter Student ID: 6a92e17dedb9333e5964473a
Student{id='6a92e17dedb9333e5964473a', name='Lakshman', age=25, department='IT', email='lakshman@gmail.com', cgpa=9.4}

================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: 4

--- Update Student ---
Enter Student ID: 6a92e17dedb9333e5964473a
New Name: Lakshmi Narayana
New Age: 26
New Department: Product Manager
New Email: 
New CGPA: 9.2
Student updated successfully!


================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: 5

--- Delete Student ---
Enter Student ID: 6a92e1b1edb9333e5964473b
Student deleted successfully!

================================
     STUDENT MANAGEMENT SYSTEM
================================
1. Create Student
2. Display All Students
3. Find Student By ID
4. Update Student
5. Delete Student
6. Exit
================================
Enter your choice: 6
Exiting application...

Process finished with exit code 0
Code language: PHP (php)

Employee Table

Application Architecture

employee-architecture

Now create the below files,

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.employee</groupId>
    <artifactId>mongodb</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
   <dependencies>
       <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
       <dependency>
           <groupId>org.mongodb</groupId>
           <artifactId>mongo-java-driver</artifactId>
           <version>3.12.14</version>
       </dependency>

   </dependencies>




</project>
package org.employee;

public class Employee {

    private String id;
    private String name;
    private int age;
    private String department;
    private String email;
    private double salary;

    public Employee() {
    }

    public Employee(String name, int age, String department,
                    String email, double salary) {
        this.name = name;
        this.age = age;
        this.department = department;
        this.email = email;
        this.salary = salary;
    }

    public Employee(String id, String name, int age,
                    String department, String email, double salary) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.department = department;
        this.email = email;
        this.salary = salary;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String getDepartment() {
        return department;
    }

    public String getEmail() {
        return email;
    }

    public double getSalary() {
        return salary;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", department='" + department + '\'' +
                ", email='" + email + '\'' +
                ", salary=" + salary +
                '}';
    }
}
package org.employee;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.List;

import static com.mongodb.client.model.Filters.eq;

public class EmployeeDAO {

    private final MongoCollection<Document> collection;

    public EmployeeDAO() {

        MongoDatabase database =
                MongoDBConnection.getDatabase();

        collection = database.getCollection("employees");
    }

    // CREATE
    public String createEmployee(Employee employee) {

        Document document = new Document()
                .append("name", employee.getName())
                .append("age", employee.getAge())
                .append("department", employee.getDepartment())
                .append("email", employee.getEmail())
                .append("salary", employee.getSalary());

        collection.insertOne(document);

        return document.getObjectId("_id").toHexString();
    }

    // READ ALL
    public List<Employee> getAllEmployees() {

        List<Employee> employees = new ArrayList<>();

        for (Document document : collection.find()) {

            Employee employee =
                    convertDocumentToEmployee(document);

            employees.add(employee);
        }

        return employees;
    }

    // READ BY ID
    public Employee getEmployeeById(String id) {

        Document document = collection.find(
                eq("_id", new ObjectId(id))
        ).first();

        if (document == null) {
            return null;
        }

        return convertDocumentToEmployee(document);
    }

    // UPDATE
    public boolean updateEmployee(String id, Employee employee) {

        Document updateDocument = new Document()
                .append("name", employee.getName())
                .append("age", employee.getAge())
                .append("department", employee.getDepartment())
                .append("email", employee.getEmail())
                .append("salary", employee.getSalary());

        var result = collection.updateOne(
                eq("_id", new ObjectId(id)),
                new Document("$set", updateDocument)
        );

        return result.getModifiedCount() > 0;
    }

    // DELETE
    public boolean deleteEmployee(String id) {

        var result = collection.deleteOne(
                eq("_id", new ObjectId(id))
        );

        return result.getDeletedCount() > 0;
    }

    // Convert Document to Employee
    private Employee convertDocumentToEmployee(
            Document document) {

        return new Employee(
                document.getObjectId("_id").toHexString(),
                document.getString("name"),
                document.getInteger("age"),
                document.getString("department"),
                document.getString("email"),
                document.getDouble("salary")
        );
    }
}
package org.employee;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;

public class MongoDBConnection {

    private static final String CONNECTION_STRING =
            "mongodb://localhost:27017";

    private static final String DATABASE_NAME =
            "employeedb";

    private static MongoClient mongoClient;

    public static MongoDatabase getDatabase() {

        if (mongoClient == null) {
            mongoClient = MongoClients.create(CONNECTION_STRING);
        }

        return mongoClient.getDatabase(DATABASE_NAME);
    }

    public static void closeConnection() {

        if (mongoClient != null) {
            mongoClient.close();
            mongoClient = null;
        }
    }
}
package org.employee;

import java.util.List;
import java.util.Scanner;

public class EmployeeApplication {

    private static final Scanner scanner =
            new Scanner(System.in);

    private static final EmployeeDAO employeeDAO =
            new EmployeeDAO();

    public static void main(String[] args) {

        int choice;

        do {

            displayMenu();

            System.out.print("Enter your choice: ");
            choice = scanner.nextInt();
            scanner.nextLine();

            switch (choice) {

                case 1:
                    createEmployee();
                    break;

                case 2:
                    displayAllEmployees();
                    break;

                case 3:
                    findEmployeeById();
                    break;

                case 4:
                    updateEmployee();
                    break;

                case 5:
                    deleteEmployee();
                    break;

                case 6:
                    System.out.println(
                            "Exiting application..."
                    );
                    break;

                default:
                    System.out.println(
                            "Invalid choice!"
                    );
            }

        } while (choice != 6);

        MongoDBConnection.closeConnection();
        scanner.close();
    }

    private static void displayMenu() {

        System.out.println();
        System.out.println("================================");
        System.out.println("     EMPLOYEE MANAGEMENT SYSTEM");
        System.out.println("================================");
        System.out.println("1. Create Employee");
        System.out.println("2. Display All Employees");
        System.out.println("3. Find Employee By ID");
        System.out.println("4. Update Employee");
        System.out.println("5. Delete Employee");
        System.out.println("6. Exit");
        System.out.println("================================");
    }

    // CREATE
    private static void createEmployee() {

        System.out.println("\n--- Create Employee ---");

        System.out.print("Name: ");
        String name = scanner.nextLine();

        System.out.print("Age: ");
        int age = scanner.nextInt();
        scanner.nextLine();

        System.out.print("Department: ");
        String department = scanner.nextLine();

        System.out.print("Email: ");
        String email = scanner.nextLine();

        System.out.print("Salary: ");
        double salary = scanner.nextDouble();
        scanner.nextLine();

        Employee employee = new Employee(
                name, age, department, email, salary
        );

        String id = employeeDAO.createEmployee(employee);

        System.out.println(
                "Employee created successfully!"
        );

        System.out.println("Generated ID: " + id);
    }

    // READ ALL
    private static void displayAllEmployees() {

        System.out.println("\n--- All Employees ---");

        List<Employee> employees =
                employeeDAO.getAllEmployees();

        if (employees.isEmpty()) {

            System.out.println("No employees found.");
            return;
        }

        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }

    // READ BY ID
    private static void findEmployeeById() {

        System.out.println("\n--- Find Employee ---");

        System.out.print("Enter Employee ID: ");
        String id = scanner.nextLine();

        try {

            Employee employee =
                    employeeDAO.getEmployeeById(id);

            if (employee != null) {
                System.out.println(employee);
            } else {
                System.out.println("Employee not found.");
            }

        } catch (IllegalArgumentException e) {

            System.out.println(
                    "Invalid MongoDB ObjectId."
            );
        }
    }

    // UPDATE
    private static void updateEmployee() {

        System.out.println("\n--- Update Employee ---");

        System.out.print("Enter Employee ID: ");
        String id = scanner.nextLine();

        try {

            Employee existing =
                    employeeDAO.getEmployeeById(id);

            if (existing == null) {

                System.out.println("Employee not found.");
                return;
            }

            System.out.print("New Name: ");
            String name = scanner.nextLine();

            System.out.print("New Age: ");
            int age = scanner.nextInt();
            scanner.nextLine();

            System.out.print("New Department: ");
            String department = scanner.nextLine();

            System.out.print("New Email: ");
            String email = scanner.nextLine();

            System.out.print("New Salary: ");
            double salary = scanner.nextDouble();
            scanner.nextLine();

            Employee employee = new Employee(
                    name, age, department, email, salary
            );

            boolean updated =
                    employeeDAO.updateEmployee(id, employee);

            if (updated) {
                System.out.println(
                        "Employee updated successfully!"
                );
            } else {
                System.out.println(
                        "Employee was not updated."
                );
            }

        } catch (IllegalArgumentException e) {

            System.out.println(
                    "Invalid MongoDB ObjectId."
            );
        }
    }

    // DELETE
    private static void deleteEmployee() {

        System.out.println("\n--- Delete Employee ---");

        System.out.print("Enter Employee ID: ");
        String id = scanner.nextLine();

        try {

            boolean deleted =
                    employeeDAO.deleteEmployee(id);

            if (deleted) {

                System.out.println(
                        "Employee deleted successfully!"
                );

            } else {

                System.out.println(
                        "Employee not found."
                );
            }

        } catch (IllegalArgumentException e) {

            System.out.println(
                    "Invalid MongoDB ObjectId."
            );
        }
    }
}

Right click on the EmployeeApplication and Run the EmployeeApplication

Execution and Output:

"C:\Program Files\Java\jdk-17\bin\java.exe" "-javaagent:C:\Program Files\JetBrains\IntelliJ IDEA 2025.3.1\lib\idea_rt.jar=56536" -Dfile.encoding=UTF-8 -classpath C:\Users\dudek\OneDrive\Desktop\mongodb\target\classes;C:\Users\dudek\.m2\repository\org\mongodb\mongo-java-driver\3.12.14\mongo-java-driver-3.12.14.jar org.employee.EmployeeApplication
Aug 29, 2026 9:26:10 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: Aug 29, 2026 9:26:10 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:1, serverValue:3}] to localhost:27017
Aug 29, 2026 9:26:10 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, version=ServerVersion{versionList=[7, 0, 5]}, minWireVersion=0, maxWireVersion=21, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3272300}
1

--- Create Employee ---
Name: Lakshman
Age: 20
Department: Designer
Email: lakshman@gmail.com
Salary: 40,000
Aug 29, 2026 9:27:12 PM com.mongodb.diagnostics.logging.JULLogger log
INFO: Opened connection [connectionId{localValue:2, serverValue:4}] to localhost:27017
Employee created successfully!
Generated ID: 6a9301584ce8c26c01e066aa

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: 1

--- Create Employee ---
Name: Mahesh
Age: 29
Department: Product Manager
Email: mahesh@gmail.com
Salary: 35,000
Employee created successfully!
Generated ID: 6a93017b4ce8c26c01e066ab

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: 2

--- All Employees ---
Employee{id='6a9301584ce8c26c01e066aa', name='Lakshman', age=20, department='Designer', email='lakshman@gmail.com', salary=40000.0}
Employee{id='6a93017b4ce8c26c01e066ab', name='Mahesh', age=29, department='Product Manager', email='mahesh@gmail.com', salary=35000.0}

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: 3

--- Find Employee ---
Enter Employee ID: 6a9301584ce8c26c01e066aa
Employee{id='6a9301584ce8c26c01e066aa', name='Lakshman', age=20, department='Designer', email='lakshman@gmail.com', salary=40000.0}

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: 4

--- Update Employee ---
Enter Employee ID: 6a9301584ce8c26c01e066aa
New Name: Lakshmi Narayana
New Age: 32
New Department: IT
New Email: lakshman.12@gmail.com
New Salary: 60,000
Employee updated successfully!

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: 5

--- Delete Employee ---
Enter Employee ID: 6a93017b4ce8c26c01e066ab
Employee deleted successfully!

================================
     EMPLOYEE MANAGEMENT SYSTEM
================================
1. Create Employee
2. Display All Employees
3. Find Employee By ID
4. Update Employee
5. Delete Employee
6. Exit
================================
Enter your choice: 6
Exiting application...

Process finished with exit code 0
Code language: PHP (php)
Scroll to Top