MongoDB With Node.js Project Practice Questions with Solutions

Introduction

MongoDB and Node.js work well together for building database-driven applications. In this chapter, you will practice creating a small Student Management Project using Node.js and the official MongoDB driver. You will connect Node.js to MongoDB, create student records, read and search data, update records, delete records, and build reusable project functions. These practical questions help you understand how MongoDB With Node.js Project Practice Questions with Solutions is actually used inside a Node.js application.

Q1. Create a Node.js MongoDB Project

Problem Statement

Create a new Node.js project and install the MongoDB driver.

Node.js Commands

Open the terminal and run:

mkdir student-management
cd student-management
npm init -y
npm install mongodb

Create a file named:

app.js

Expected Output

Your project structure will look similar to:

student-management/
│
├── node_modules/
├── package.json
├── package-lock.json
└── app.js

Explanation

The mongodb package is the official MongoDB driver for Node.js. It allows your Node.js application to connect to MongoDB and perform database operations.


Q2. Connect Node.js to MongoDB

Problem Statement

Connect the Node.js application to a MongoDB server running on the local computer.

Node.js Code

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

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

const client = new MongoClient(uri);

async function connectDB() {
    try {
        await client.connect();
        console.log("MongoDB connected successfully");
    } catch (error) {
        console.log("Connection error:", error);
    }
}

connectDB();

Run the program:

node app.js

Expected Output

MongoDB connected successfully

Explanation

MongoClient is used to establish a connection between Node.js and MongoDB.

The 127.0.0.1:27017 address points to a MongoDB server running locally on the default MongoDB port.


Q3. Select the Database and Collection

Problem Statement

Connect to a database named student_project and use a collection named students.

Node.js Code

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

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

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

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

    console.log("Database and collection selected");

    await client.close();
}

startProject();

Expected Output

Database and collection selected

Explanation

This line selects the database:

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

This line selects the collection:

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

The database and collection become persistent when data is stored.


Q4. Add a Student to the Project

Problem Statement

Create a function that adds a new student to the MongoDB database.

Node.js Code

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

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

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

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

    const student = {
        name: "Rahul",
        age: 17,
        course: "Python",
        city: "Delhi"
    };

    const result = await students.insertOne(student);

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

    await client.close();
}

addStudent();

Expected Output

Student added: ObjectId('...')

Explanation

The insertOne() method adds one student document to the students collection.

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


Q5. Add Multiple Students

Problem Statement

Insert multiple student records into the project database.

Node.js Code

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

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

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

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

    const data = [
        {
            name: "Priya",
            age: 16,
            course: "JavaScript",
            city: "Delhi"
        },
        {
            name: "Aman",
            age: 18,
            course: "Node.js",
            city: "Mumbai"
        },
        {
            name: "Neha",
            age: 17,
            course: "MongoDB",
            city: "Delhi"
        }
    ];

    const result = await students.insertMany(data);

    console.log("Students added:", result.insertedCount);

    await client.close();
}

addStudents();

Expected Output

Students added: 3

Explanation

insertMany() allows the application to add multiple documents in one operation.


Q6. Display All Students

Problem Statement

Create a function that retrieves all students from MongoDB and displays them in the terminal.

Node.js Code

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

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

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

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

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

    console.log(data);

    await client.close();
}

showStudents();

Expected Output

[
  {
    _id: ObjectId('...'),
    name: 'Rahul',
    age: 17,
    course: 'Python',
    city: 'Delhi'
  },
  {
    _id: ObjectId('...'),
    name: 'Priya',
    age: 16,
    course: 'JavaScript',
    city: 'Delhi'
  }
]

Explanation

find() retrieves matching documents. Since find() returns a cursor, toArray() is used to obtain the documents as a JavaScript array.


Q7. Search Students by Course

Problem Statement

Create a Node.js function that finds all students studying MongoDB.

Node.js Code

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

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

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

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

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

    console.log(data);

    await client.close();
}

findByCourse();

Expected Output

[
  {
    _id: ObjectId('...'),
    name: 'Neha',
    age: 17,
    course: 'MongoDB',
    city: 'Delhi'
  }
]

Explanation

The filter:

{ course: "MongoDB" }

returns students whose course field contains the value MongoDB.


Q8. Update Student Information

Problem Statement

Update Rahul’s city from Delhi to Noida.

Node.js Code

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

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

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

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

    const result = await students.updateOne(
        { name: "Rahul" },
        {
            $set: {
                city: "Noida"
            }
        }
    );

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

    await client.close();
}

updateStudent();

Expected Output

Matched: 1
Modified: 1

Explanation

The filter identifies Rahul:

{ name: "Rahul" }

The $set operator changes only the specified field:

{ $set: { city: "Noida" } }

The other fields remain unchanged.


Q9. Delete a Student from the Project

Problem Statement

Delete the student named Aman from the MongoDB database.

Node.js Code

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

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

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

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

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

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

    await client.close();
}

deleteStudent();

Expected Output

If Aman exists:

Deleted: 1

If Aman does not exist:

Deleted: 0

Explanation

deleteOne() removes the first document matching the specified filter.


Q10. Build a Complete Student Management Project

Problem Statement

Create a complete Node.js project that connects to MongoDB and provides functions for adding, displaying, searching, updating, and deleting students.

Node.js Code

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

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

const dbName = "student_project";

async function main() {
    try {
        await client.connect();

        console.log("MongoDB connected successfully");

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

        // CREATE
        const newStudent = {
            name: "Karan",
            age: 16,
            course: "Node.js",
            city: "Delhi"
        };

        const createResult = await students.insertOne(newStudent);

        console.log("Student created:");
        console.log(createResult.insertedId);

        // READ
        const allStudents = await students.find().toArray();

        console.log("All Students:");
        console.log(allStudents);

        // SEARCH
        const pythonStudents = await students.find({
            course: "Python"
        }).toArray();

        console.log("Python Students:");
        console.log(pythonStudents);

        // UPDATE
        const updateResult = await students.updateOne(
            { name: "Karan" },
            {
                $set: {
                    course: "MongoDB"
                }
            }
        );

        console.log("Updated:", updateResult.modifiedCount);

        // DELETE
        const deleteResult = await students.deleteOne({
            name: "Karan"
        });

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

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

main();

Expected Output

The exact _id values will vary, but the output will be similar to:

MongoDB connected successfully

Student created:
ObjectId('...')

All Students:
[
  {
    _id: ObjectId('...'),
    name: 'Karan',
    age: 16,
    course: 'Node.js',
    city: 'Delhi'
  }
]

Python Students:
[
  {
    _id: ObjectId('...'),
    name: 'Rahul',
    age: 17,
    course: 'Python',
    city: 'Delhi'
  }
]

Updated: 1

Deleted: 1

Explanation

This question combines the main operations practiced in this chapter:

Node.js
   ↓
MongoDB Driver
   ↓
MongoDB Server
   ↓
student_project
   ↓
students collection
   ↓
CRUD Operations

The project performs:

CREATE → insertOne()
READ   → find().toArray()
SEARCH → find({ ... })
UPDATE → updateOne() + $set
DELETE → deleteOne()

The try...catch...finally structure is also useful in real projects because it allows errors to be handled and ensures that the MongoDB client is closed when the operation finishes.

Key Takeaways

  • Node.js can communicate with MongoDB using the official mongodb driver.
  • MongoClient is used to establish a MongoDB connection.
  • client.db() selects a database.
  • db.collection() selects a collection.
  • insertOne() creates a single document.
  • insertMany() creates multiple documents.
  • find() retrieves multiple documents.
  • findOne() retrieves one matching document.
  • updateOne() updates one matching document.
  • $set changes specific fields without replacing the complete document.
  • deleteOne() removes one matching document.
  • toArray() converts a MongoDB cursor into a JavaScript array.
  • try...catch can be used for error handling.
  • finally can be used to close the MongoDB connection.
  • A Node.js + MongoDB project can combine all CRUD operations into one application.

FAQs

1. What is a MongoDB + Node.js project?

A MongoDB + Node.js project is an application where Node.js handles the application logic and MongoDB stores the application’s data.

2. Which package is used to connect Node.js with MongoDB?

The official mongodb Node.js driver is commonly used to connect a Node.js application to MongoDB.

3. How does Node.js connect to MongoDB?

Node.js connects to MongoDB using MongoClient and a MongoDB connection URI such as:

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

4. What CRUD operations can Node.js perform with MongoDB?

A Node.js application can perform Create, Read, Update, and Delete operations using MongoDB methods such as insertOne(), find(), updateOne(), and deleteOne().

5. Why is async/await used with MongoDB in Node.js?

MongoDB database operations are asynchronous. async/await makes it easier to write and read asynchronous database code in a sequential style.

6. What does toArray() do in a MongoDB Node.js project?

toArray() reads the documents from a MongoDB cursor and returns them as a JavaScript array.

7. Can a MongoDB + Node.js project be connected to a frontend?

Yes. Node.js can provide an API using a framework such as Express.js, and a frontend application such as React can communicate with that API to create, read, update, and delete MongoDB data.

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

Scroll to Top