MongoDB CRUD Application Practice Questions with Solutions

Introduction

A MongoDB CRUD application allows users to Create, Read, Update, and Delete data from a MongoDB database. In this chapter, you will practice building CRUD operations using Node.js, Express.js, and MongoDB. The questions are designed to help beginners understand how a real application communicates with MongoDB. Each practice question includes a problem statement, code, and expected output so you can practice step by step. MongoDB CRUD Application practice questions with solutions to help you understand the concepts.

Q1. Create a MongoDB CRUD Application Project

Problem Statement

Create a new Node.js project for a MongoDB CRUD application and install the required packages.

Solution

Open the terminal and run:

mkdir mongodb-crud-app
cd mongodb-crud-app
npm init -y
npm install express mongodb

Create a file named:

server.js

Expected Output

After installation, your project can look like this:

mongodb-crud-app/
│
├── node_modules/
├── package.json
├── package-lock.json
└── server.js

Explanation

The express package is used to create the web server and API routes, while the official mongodb package allows Node.js to communicate with MongoDB.


Q2. Connect the CRUD Application to MongoDB

Problem Statement

Create a MongoDB connection using MongoClient and connect the application to a local MongoDB server.

Solution

Add the following code to server.js:

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

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function connectDB() {
    await client.connect();
    console.log("MongoDB connected successfully");
}

connectDB();

Run:

node server.js

Expected Output

MongoDB connected successfully

Explanation

MongoClient creates the connection between Node.js and MongoDB.


Q3. Create a Student Using the Create Operation

Problem Statement

Insert a new student into the students collection.

Solution

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

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function createStudent() {
    await client.connect();

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

    const result = await students.insertOne({
        name: "Rahul",
        age: 16,
        course: "Python"
    });

    console.log("Student created:", result.insertedId);

    await client.close();
}

createStudent();

Expected Output

Student created: ObjectId('...')

Explanation

insertOne() creates a new document in the MongoDB collection.


Q4. Read All Students from MongoDB

Problem Statement

Retrieve all students from the students collection.

Solution

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

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function getStudents() {
    await client.connect();

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

    const data = await students.find().toArray();

    console.log(data);

    await client.close();
}

getStudents();

Expected Output

[
  {
    _id: ObjectId('...'),
    name: 'Rahul',
    age: 16,
    course: 'Python'
  }
]

Explanation

find() returns a cursor. The toArray() method converts the returned documents into a JavaScript array.


Q5. Read One Student Using a Filter

Problem Statement

Find a student whose name is Rahul.

Solution

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

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function findStudent() {
    await client.connect();

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

    const student = await students.findOne({
        name: "Rahul"
    });

    console.log(student);

    await client.close();
}

findStudent();

Expected Output

{
  _id: ObjectId('...'),
  name: 'Rahul',
  age: 16,
  course: 'Python'
}

Explanation

findOne() returns the first document that matches the filter.


Q6. Update a Student

Problem Statement

Update Rahul’s course from Python to Data Analytics.

Solution

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

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function updateStudent() {
    await client.connect();

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

    const result = await students.updateOne(
        { name: "Rahul" },
        { $set: { course: "Data Analytics" } }
    );

    console.log("Matched:", result.matchedCount);
    console.log("Modified:", result.modifiedCount);

    await client.close();
}

updateStudent();

Expected Output

Matched: 1
Modified: 1

Explanation

updateOne() updates the first document matching the filter.

The $set operator changes the value of the course field without replacing the complete document.


Q7. Delete a Student

Problem Statement

Delete the student whose name is Rahul.

Solution

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

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function deleteStudent() {
    await client.connect();

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

    const result = await students.deleteOne({
        name: "Rahul"
    });

    console.log("Deleted:", result.deletedCount);

    await client.close();
}

deleteStudent();

Expected Output

Deleted: 1

Explanation

deleteOne() removes the first document matching the filter.


Q8. Create an Express.js API for Adding Students

Problem Statement

Create a POST API that receives student information and inserts it into MongoDB.

Solution

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

const app = express();

app.use(express.json());

const client = new MongoClient("mongodb://127.0.0.1:27017");

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

app.post("/students", async (req, res) => {
    const student = req.body;

    const result = await students.insertOne(student);

    res.json({
        message: "Student created successfully",
        id: result.insertedId
    });
});

app.listen(3000, async () => {
    await client.connect();
    console.log("Server running on port 3000");
});

Send a POST request to:

POST /students

Example JSON:

{
    "name": "Priya",
    "age": 15,
    "course": "JavaScript"
}

Expected Output

{
    "message": "Student created successfully",
    "id": "..."
}

Explanation

express.json() allows Express to read JSON request bodies.

The received data is available through:

req.body


Q9. Create GET, PUT and DELETE APIs

Problem Statement

Create APIs for reading, updating, and deleting students.

Solution

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

const app = express();

app.use(express.json());

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function startServer() {
    await client.connect();

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

    // READ
    app.get("/students", async (req, res) => {
        const data = await students.find().toArray();
        res.json(data);
    });

    // UPDATE
    app.put("/students/:name", async (req, res) => {
        const name = req.params.name;

        const result = await students.updateOne(
            { name: name },
            { $set: req.body }
        );

        res.json({
            message: "Student updated successfully",
            matched: result.matchedCount,
            modified: result.modifiedCount
        });
    });

    // DELETE
    app.delete("/students/:name", async (req, res) => {
        const name = req.params.name;

        const result = await students.deleteOne({
            name: name
        });

        res.json({
            message: "Student deleted successfully",
            deleted: result.deletedCount
        });
    });

    app.listen(3000, () => {
        console.log("Server running on port 3000");
    });
}

startServer();

Expected Output

GET:

GET /students

Returns:

[
    {
        "_id": "...",
        "name": "Priya",
        "age": 15,
        "course": "JavaScript"
    }
]

PUT:

PUT /students/Priya

Request body:

{
    "course": "React.js"
}

Response:

{
    "message": "Student updated successfully",
    "matched": 1,
    "modified": 1
}

DELETE:

DELETE /students/Priya

Response:

{
    "message": "Student deleted successfully",
    "deleted": 1
}

Explanation

These three routes demonstrate the main database operations:

  • GET → Read
  • PUT → Update
  • DELETE → Delete

Q10. Build a Complete MongoDB CRUD Application

Problem Statement

Create a complete Student CRUD application using Express.js and MongoDB with APIs for creating, reading, updating, and deleting students.

Solution

Create server.js:

const express = require("express");
const { MongoClient, ObjectId } = require("mongodb");

const app = express();

app.use(express.json());

const client = new MongoClient("mongodb://127.0.0.1:27017");

async function startServer() {
    await client.connect();

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

    // CREATE
    app.post("/students", async (req, res) => {
        try {
            const student = req.body;

            const result = await students.insertOne(student);

            res.status(201).json({
                message: "Student created successfully",
                id: result.insertedId
            });
        } catch (error) {
            res.status(500).json({
                error: error.message
            });
        }
    });

    // READ ALL
    app.get("/students", async (req, res) => {
        try {
            const data = await students.find().toArray();

            res.json(data);
        } catch (error) {
            res.status(500).json({
                error: error.message
            });
        }
    });

    // READ ONE
    app.get("/students/:id", async (req, res) => {
        try {
            const id = new ObjectId(req.params.id);

            const student = await students.findOne({
                _id: id
            });

            if (!student) {
                return res.status(404).json({
                    message: "Student not found"
                });
            }

            res.json(student);
        } catch (error) {
            res.status(400).json({
                error: "Invalid student ID"
            });
        }
    });

    // UPDATE
    app.put("/students/:id", async (req, res) => {
        try {
            const id = new ObjectId(req.params.id);

            const result = await students.updateOne(
                { _id: id },
                { $set: req.body }
            );

            if (result.matchedCount === 0) {
                return res.status(404).json({
                    message: "Student not found"
                });
            }

            res.json({
                message: "Student updated successfully",
                modified: result.modifiedCount
            });
        } catch (error) {
            res.status(400).json({
                error: "Invalid student ID"
            });
        }
    });

    // DELETE
    app.delete("/students/:id", async (req, res) => {
        try {
            const id = new ObjectId(req.params.id);

            const result = await students.deleteOne({
                _id: id
            });

            if (result.deletedCount === 0) {
                return res.status(404).json({
                    message: "Student not found"
                });
            }

            res.json({
                message: "Student deleted successfully"
            });
        } catch (error) {
            res.status(400).json({
                error: "Invalid student ID"
            });
        }
    });

    app.listen(3000, () => {
        console.log("MongoDB CRUD Application running on port 3000");
    });
}

startServer();

Expected Output

Start the application:

node server.js

Output:

MongoDB CRUD Application running on port 3000

The application now supports:

HTTP MethodAPICRUD Operation
POST/studentsCreate
GET/studentsRead all
GET/students/:idRead one
PUT/students/:idUpdate
DELETE/students/:idDelete

Example POST request:

{
    "name": "Aman",
    "age": 17,
    "course": "Node.js"
}

Example response:

{
    "message": "Student created successfully",
    "id": "68c..."
}

Explanation

This is a basic real-world CRUD API structure.

The application uses:

  • Express.js for HTTP APIs
  • MongoDB for database storage
  • MongoClient for database connection
  • ObjectId for MongoDB document IDs
  • insertOne() for Create
  • find() and findOne() for Read
  • updateOne() for Update
  • deleteOne() for Delete

Key Takeaways

  • CRUD stands for Create, Read, Update, and Delete.
  • MongoDB provides methods such as insertOne(), find(), updateOne(), and deleteOne() for CRUD operations.
  • Node.js can connect to MongoDB using the official mongodb package.
  • Express.js can be used to create REST APIs for MongoDB.
  • req.body is useful for receiving JSON data.
  • req.params is useful for reading values from URL parameters.
  • ObjectId() is used when working with MongoDB _id values.
  • GET is commonly used for reading data.
  • POST is commonly used for creating data.
  • PUT is commonly used for updating data.
  • DELETE is commonly used for deleting data.
  • A CRUD application connects the frontend/API layer with database operations.

FAQs

1. What is a CRUD application in MongoDB?

A CRUD application is an application that performs four basic database operations: Create, Read, Update, and Delete.

2. Which MongoDB methods are used for CRUD operations?

Common MongoDB methods include insertOne(), insertMany(), find(), findOne(), updateOne(), updateMany(), deleteOne(), and deleteMany().

3. Can MongoDB CRUD be used with Node.js?

Yes. Node.js can communicate with MongoDB using the official MongoDB Node.js driver.

4. Can Express.js be used to create a MongoDB CRUD API?

Yes. Express.js can provide HTTP routes such as POST, GET, PUT, and DELETE, while MongoDB stores the application data.

5. What is the difference between MongoDB CRUD and REST API?

MongoDB CRUD describes database operations, while a REST API provides HTTP endpoints through which applications or clients can perform those operations.

6. Why is ObjectId used in a MongoDB CRUD application?

MongoDB automatically generates an _id for documents, commonly using the BSON ObjectId type. When an API receives an ID as a URL string, ObjectId() can convert it into the type needed to query an _id field.

7. How do I test a MongoDB CRUD application?

You can test the API using tools such as Postman, Insomnia, curl, or a frontend application. Test the POST, GET, PUT, and DELETE endpoints separately.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top