Node.js MongoDB Practice Questions with Solutions

Introduction

MongoDB is a popular NoSQL database used with Node.js applications to store and manage data. In this chapter, you will practice connecting Node.js with MongoDB and performing basic database operations. The 10 solved questions start from creating a connection and gradually move to databases, collections, inserting documents, reading data, updating documents, deleting documents, and building a simple student API. Node.js MongoDB practice questions with solutions help to understand the concepts.

Before you start: These examples use the official MongoDB Node.js driver. You need Node.js and access to a MongoDB server, either a local MongoDB installation or MongoDB Atlas.

Question 1: How do you connect Node.js to MongoDB?

Problem

Create a Node.js program that connects to MongoDB and prints a success message when the connection is established.

Step 1: Install the MongoDB Driver

Open your project folder in the terminal:

npm init -y

Then install the MongoDB driver:

npm install mongodb

Step 2: Create index.js

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function connectDatabase() {

    try {

        await client.connect();

        console.log("MongoDB connected successfully.");

    } catch (error) {

        console.error(
            "MongoDB connection failed:",
            error.message
        );

    }

}

connectDatabase();

Step 3: Run the Program

node index.js

Output

MongoDB connected successfully.

Step-by-Step Explanation

First, import MongoClient:

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

Then specify the MongoDB connection URL:

const uri = "mongodb://127.0.0.1:27017";

Create a MongoDB client:

const client = new MongoClient(uri);

Finally, connect:

await client.connect();

Question 2: How do you select a MongoDB database using Node.js?

Problem

Connect to MongoDB and select a database named school.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function connectDatabase() {

    try {

        await client.connect();

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

        console.log(
            "Connected to school database."
        );

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

connectDatabase();

Output

Connected to school database.

Step-by-Step Explanation

After connecting:

await client.connect();

select the database:

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

Here:

school

is the database name.


Question 3: How do you create and select a MongoDB collection?

Problem

Create a students collection inside the school database.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function createCollection() {

    try {

        await client.connect();

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

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

        console.log(
            "Students collection is ready."
        );

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

createCollection();

Output

Students collection is ready.

Step-by-Step Explanation

First select the database:

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

Then select the collection:

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

You can think of a MongoDB collection as being similar to a table in a relational database, although MongoDB collections and SQL tables are not exactly the same.

Question 4: How do you insert one document into MongoDB?

Problem

Insert one student document into the students collection.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function insertStudent() {

    try {

        await client.connect();

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

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

        const student = {

            name: "Rahul",

            age: 20,

            course: "Node.js"

        };

        const result =
            await students.insertOne(student);

        console.log(
            "Student inserted."
        );

        console.log(
            "Inserted ID:",
            result.insertedId
        );

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

insertStudent();

Output

Student inserted.
Inserted ID: ObjectId(...)

Step-by-Step Explanation

Create a JavaScript object:

const student = {

    name: "Rahul",

    age: 20,

    course: "Node.js"

};

Insert it using:

await students.insertOne(student);

MongoDB automatically generates an _id for the document if you do not provide one.

The generated ID is available through:

result.insertedId

MongoDB Document

The stored document will look approximately like:

{
    "_id": "ObjectId(...)",
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

Question 5: How do you insert multiple documents into MongoDB?

Problem

Insert three students into the students collection at once.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function insertStudents() {

    try {

        await client.connect();

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

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

        const data = [

            {
                name: "Rahul",
                age: 20,
                course: "Node.js"
            },

            {
                name: "Priya",
                age: 19,
                course: "Python"
            },

            {
                name: "Aman",
                age: 21,
                course: "JavaScript"
            }

        ];

        const result =
            await students.insertMany(data);

        console.log(
            `${result.insertedCount} students inserted.`
        );

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

insertStudents();

Output

3 students inserted.

Step-by-Step Explanation

Create an array containing multiple objects:

const data = [
    {
        name: "Rahul",
        age: 20,
        course: "Node.js"
    },
    {
        name: "Priya",
        age: 19,
        course: "Python"
    },
    {
        name: "Aman",
        age: 21,
        course: "JavaScript"
    }
];

Then use:

await students.insertMany(data);

The number of inserted documents is available through:

result.insertedCount

Question 6: How do you find documents in MongoDB?

Problem

Retrieve all students from the students collection.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function getStudents() {

    try {

        await client.connect();

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

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

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

        console.log(data);

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

getStudents();

Example Output

[
  {
    _id: ObjectId('...'),
    name: 'Rahul',
    age: 20,
    course: 'Node.js'
  },
  {
    _id: ObjectId('...'),
    name: 'Priya',
    age: 19,
    course: 'Python'
  }
]

Step-by-Step Explanation

Use:

students.find({})

The empty object:

{}

means there is no filter, so all matching documents are returned.

Then:

.toArray()

converts the cursor into an array.

Find Students From a Specific Course

const data =
    await students
        .find({ course: "Node.js" })
        .toArray();

This finds students whose course is Node.js.


Question 7: How do you find one document in MongoDB?

Problem

Find the first student whose name is Rahul.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function findStudent() {

    try {

        await client.connect();

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

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

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

        if (student) {

            console.log(
                "Student found:"
            );

            console.log(student);

        } else {

            console.log(
                "Student not found."
            );

        }

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

findStudent();

Output

If Rahul exists:

Student found:
{
    _id: ObjectId(...),
    name: 'Rahul',
    age: 20,
    course: 'Node.js'
}

If Rahul does not exist:

Student not found.

Step-by-Step Explanation

The filter is:

{
    name: "Rahul"
}

MongoDB searches for a matching document:

students.findOne({
    name: "Rahul"
});

The result is stored in:

const student

Then we check:

if (student)

Question 8: How do you update a document in MongoDB?

Problem

Change Rahul’s course from Node.js to MongoDB.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function updateStudent() {

    try {

        await client.connect();

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

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

        const result =
            await students.updateOne(

                {
                    name: "Rahul"
                },

                {
                    $set: {
                        course: "MongoDB"
                    }
                }

            );

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

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

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

updateStudent();

Example Output

Matched: 1
Modified: 1

Step-by-Step Explanation

The first object identifies the document:

{
    name: "Rahul"
}

The second object describes the update:

{
    $set: {
        course: "MongoDB"
    }
}

$set changes the selected field without replacing the complete document.

Before

{
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

After

{
    "name": "Rahul",
    "age": 20,
    "course": "MongoDB"
}

Question 9: How do you delete a document from MongoDB?

Problem

Delete the student whose name is Aman.

Solution

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

const uri = "mongodb://127.0.0.1:27017";

const client = new MongoClient(uri);

async function deleteStudent() {

    try {

        await client.connect();

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

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

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

        if (result.deletedCount === 1) {

            console.log(
                "Student deleted successfully."
            );

        } else {

            console.log(
                "Student not found."
            );

        }

    } catch (error) {

        console.error(
            error.message
        );

    } finally {

        await client.close();

    }

}

deleteStudent();

Output

If the student exists:

Student deleted successfully.

If the student does not exist:

Student not found.

Step-by-Step Explanation

The filter:

{
    name: "Aman"
}

identifies the document.

MongoDB deletes the matching document using:

await students.deleteOne({
    name: "Aman"
});

Then check:

result.deletedCount

If it is 1, one document was deleted.


Question 10: How do you create a simple Node.js + Express + MongoDB API?

Problem

Create a small REST API that:

  • Connects to MongoDB
  • Creates students
  • Gets all students
  • Uses Express
  • Returns JSON responses
  • Handles basic errors

Step 1: Install Packages

npm init -y

Install Express and MongoDB:

npm install express mongodb

Step 2: Create index.js

const express = require("express");

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

const app = express();

app.use(express.json());


const uri =
    "mongodb://127.0.0.1:27017";

const client =
    new MongoClient(uri);

let students;


// Connect to MongoDB

async function connectDatabase() {

    await client.connect();

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

    students =
        db.collection("students");

    console.log(
        "MongoDB connected."
    );

}


// GET all students

app.get("/students", async (req, res) => {

    try {

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

        res.json({

            success: true,

            students: data

        });

    } catch (error) {

        res.status(500).json({

            success: false,

            message:
                "Unable to get students."

        });

    }

});


// POST a student

app.post("/students", async (req, res) => {

    try {

        const {
            name,
            age,
            course
        } = req.body;

        if (!name || !course) {

            return res.status(400).json({

                success: false,

                message:
                    "Name and course are required."

            });

        }

        const student = {

            name: name,

            age: age,

            course: course

        };

        const result =
            await students.insertOne(
                student
            );

        res.status(201).json({

            success: true,

            message:
                "Student created successfully.",

            id: result.insertedId

        });

    } catch (error) {

        res.status(500).json({

            success: false,

            message:
                "Unable to create student."

        });

    }

});


// Start application

async function startServer() {

    try {

        await connectDatabase();

        app.listen(3000, () => {

            console.log(
                "Server running on http://localhost:3000"
            );

        });

    } catch (error) {

        console.error(
            "Server startup failed:",
            error.message
        );

    }

}

startServer();

Step 3: Run the Application

node index.js

Output

MongoDB connected.
Server running on http://localhost:3000

Test 1: Get Students

Send:

GET http://localhost:3000/students

Response

{
    "success": true,
    "students": []
}

If students already exist, they will appear in the array.

Test 2: Create Student

Send:

POST http://localhost:3000/students

JSON body:

{
    "name": "Rahul",
    "age": 20,
    "course": "Node.js"
}

Response

{
    "success": true,
    "message": "Student created successfully.",
    "id": "ObjectId(...)"
}

Test 3: Create Another Student

Send:

{
    "name": "Priya",
    "age": 19,
    "course": "MongoDB"
}

Response

{
    "success": true,
    "message": "Student created successfully.",
    "id": "ObjectId(...)"
}

Step-by-Step Explanation

The application first imports Express:

const express = require("express");

Then imports MongoDB:

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

Express JSON middleware allows the API to read JSON:

app.use(express.json());

The MongoDB client is created:

const client =
    new MongoClient(uri);

The application connects to MongoDB before starting the server:

await connectDatabase();

The collection is stored in:

students =
    db.collection("students");

The GET route reads documents:

students
    .find({})
    .toArray();

The POST route inserts a document:

students.insertOne(student);

Complete Application Flow

Client
   ↓
Express Server
   ↓
Route
   ↓
MongoDB Driver
   ↓
MongoDB Database
   ↓
Result
   ↓
Express Response
   ↓
Client

Key Takeaways

  • MongoDB is a NoSQL database that stores data as documents.
  • Node.js can communicate with MongoDB using the MongoDB Node.js driver.
  • MongoClient is used to create a MongoDB client.
  • client.connect() connects the application to MongoDB.
  • client.db() selects a database.
  • db.collection() selects a collection.
  • MongoDB documents are similar in structure to JavaScript objects.
  • MongoDB automatically creates an _id for documents when one is not provided.
  • insertOne() inserts one document.
  • insertMany() inserts multiple documents.
  • find() is used to retrieve multiple matching documents.
  • findOne() retrieves one matching document.
  • toArray() converts a MongoDB cursor into an array.
  • updateOne() updates one matching document.
  • $set can change specific fields.
  • deleteOne() deletes one matching document.
  • insertedId provides the ID of an inserted document.
  • insertedCount tells you how many documents were inserted.
  • matchedCount tells you how many documents matched an update filter.
  • modifiedCount tells you how many documents were modified.
  • deletedCount tells you how many documents were deleted.
  • Express can be combined with MongoDB to create REST APIs.
  • express.json() allows Express to process JSON request bodies.
  • Database operations are asynchronous, so async and await are commonly used.
  • Database errors should be handled instead of exposing raw errors to users.
  • MongoDB connection logic can be separated into its own module in larger applications.
  • Never place real database passwords directly in source code.
  • Environment variables are commonly used to store database connection strings securely.

FAQs

1. What is MongoDB in Node.js?

MongoDB is a NoSQL database that can be used by Node.js applications to store and retrieve data.

Node.js communicates with MongoDB using a driver such as the official MongoDB Node.js driver.

2. How do I connect Node.js to MongoDB?

You can use MongoClient:

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

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

await client.connect();

After connecting, you can select a database with:

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

3. What is a MongoDB collection?

A collection is a group of MongoDB documents.

For example:

school
   ↓
students
   ↓
documents

You can select a collection using:

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

4. How do you insert data into MongoDB using Node.js?

Use insertOne() for a single document:

await students.insertOne({
    name: "Rahul",
    course: "Node.js"
});

For multiple documents, use:

await students.insertMany([
    {
        name: "Rahul"
    },
    {
        name: "Priya"
    }
]);

5. How do you retrieve MongoDB data in Node.js?

Use find() to retrieve multiple documents:

const students =
    await collection
        .find({})
        .toArray();

For one document, use:

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

6. How do you update MongoDB data using Node.js?

Use updateOne() with an update operator such as $set:

await collection.updateOne(

    {
        name: "Rahul"
    },

    {
        $set: {
            course: "MongoDB"
        }
    }

);

The first object identifies the document, while $set specifies what should change.

7. How do you delete MongoDB data using Node.js?

Use deleteOne():

await collection.deleteOne({
    name: "Aman"
});

You can check whether a document was deleted using:

result.deletedCount

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

Scroll to Top