Paramclasses Academy - Blog

Tutorials Details

←
Post 25 of 35
→

Connect MongoDB with Node.js Using the Official MongoDB Driver

Connect MongoDB with Node.js Using the Official MongoDB Driver

November 5, 2026

Connect MongoDB with Node.js Using the Official MongoDB Driver

1. Introduction

Node.js is a JavaScript runtime environment that allows developers to run JavaScript outside the browser. MongoDB is a NoSQL database that stores data in flexible, document-based structures.

By connecting MongoDB with Node.js, developers can build dynamic applications that store, retrieve, update and delete database records.

For example, an online shopping application can use:

  • Node.js to handle application logic.

  • MongoDB to store products, customers and orders.

  • MongoDB Node.js Driver to communicate between Node.js and MongoDB.

In this tutorial, we will learn how to connect MongoDB with Node.js using the official MongoDB Node.js Driver.

2. What Is the MongoDB Node.js Driver?

The MongoDB Node.js Driver is an official library that allows Node.js applications to communicate with MongoDB databases.

It provides methods to:

  • Connect to MongoDB.

  • Select databases and collections.

  • Insert documents.

  • Retrieve documents.

  • Update documents.

  • Delete documents.

The official package name is mongodb.

You can install it using npm:

npm install mongodb

3. Requirements Before Connecting MongoDB with Node.js

Before starting, make sure you have installed:

Software Purpose
Node.js Runs JavaScript applications
npm Installs Node.js packages
MongoDB Community Server or MongoDB Atlas Provides the database
VS Code Code editor
MongoDB Node.js Driver Connects Node.js with MongoDB

You can download Node.js from:

https://nodejs.org/

You can download MongoDB Community Server from:

https://www.mongodb.com/try/download/community

4. Create a Node.js Project

First, create a new folder for your project.

mkdir mongodb-node-project

Open the project folder:

cd mongodb-node-project

Initialize the Node.js project:

npm init -y

This command creates a package.json file.

The package.json file stores project information, dependencies and other configuration details.

5. Install the MongoDB Node.js Driver

Now install the official MongoDB package.

npm install mongodb

After installation, npm adds the MongoDB package to your project dependencies.

Your project structure will look similar to this:

mongodb-node-project/
│
├── node_modules/
├── package-lock.json
├── package.json
└── app.js

Create a new file named app.js.

6. Understand MongoDB Connection URI

A MongoDB connection URI tells your Node.js application where the MongoDB server is located and how to connect to it.

For a local MongoDB server, use:

mongodb://127.0.0.1:27017

For MongoDB Atlas, the connection string looks like:

mongodb+srv://username:password@cluster-url.mongodb.net/

Replace the username, password and cluster URL with your actual Atlas connection details.

Important: Never share your database password or publish it in public source code.

7. Import MongoClient

The official MongoDB Node.js Driver provides a class called MongoClient.

It is used to establish a connection with a MongoDB deployment.

Add this code to app.js:

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

Here:

  • mongodb is the installed package.

  • MongoClient is the class used to create a database client.

8. Connect Node.js with MongoDB

Now create a MongoDB connection.

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.error("MongoDB Connection Error:", error);

    }

}

connectDB();

Explanation

Code Purpose
MongoClient Creates a MongoDB client
uri Specifies the MongoDB connection address
new MongoClient(uri) Creates the client instance
client.connect() Connects to MongoDB
try Executes connection code
catch Handles connection errors

The await keyword waits for the asynchronous connection operation to finish.

Expected output when MongoDB is running:

MongoDB Connected Successfully!

9. Connect to MongoDB Atlas

You can also connect your Node.js application to MongoDB Atlas, which is a cloud database service.

Follow these steps:

  1. Open https://www.mongodb.com/atlas.

  2. Sign in or create an account.

  3. Create a MongoDB cluster.

  4. Create a database user.

  5. Configure Network Access to allow your application's IP address.

  6. Open the cluster's Connect option.

  7. Select Drivers.

  8. Choose Node.js and copy the connection string.

  9. Replace the username and password placeholders with your database credentials.

Example:

const uri = "mongodb+srv://username:password@cluster-url.mongodb.net/";

For a real application, store the URI in an environment variable instead of writing credentials directly in your source code.

10. Select a Database in Node.js

After connecting to MongoDB, use the db() method to select a database.

const database = client.db("collegeDB");

Here:

  • client.db() selects a database.

  • collegeDB is the database name.

If the database does not exist, MongoDB creates it when data is first stored in it.

11. Select a Collection

A collection stores documents inside a MongoDB database.

Use the collection() method:

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

Here:

  • database represents the selected database.

  • collection() selects a collection.

  • students is the collection name.

The collection is created automatically when a document is first inserted if it does not already exist.

12. Insert Data Using insertOne()

The insertOne() method inserts one document into a MongoDB collection.

Example:

const result = await students.insertOne({
    name: "Rahul",
    age: 21,
    course: "Node.js",
    city: "Raipur"
});

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

The inserted document receives an _id field automatically if you do not provide one.

13. Insert Multiple Documents Using insertMany()

The insertMany() method inserts multiple documents in one operation.

const result = await students.insertMany([
    {
        name: "Priya",
        age: 22,
        course: "Python",
        city: "Raipur"
    },
    {
        name: "Amit",
        age: 23,
        course: "Java",
        city: "Bilaspur"
    },
    {
        name: "Neha",
        age: 20,
        course: "MongoDB",
        city: "Durg"
    }
]);

console.log("Inserted Count:", result.insertedCount);

This operation inserts multiple student documents into the students collection.

14. Retrieve Data Using find()

The find() method retrieves documents from a collection.

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

console.log(result);

The toArray() method converts the returned cursor into an array of documents.

You can also retrieve students from a particular city:

const result = await students.find({
    city: "Raipur"
}).toArray();

console.log(result);

15. Retrieve One Document Using findOne()

The findOne() method returns the first matching document.

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

console.log(student);

This retrieves the first student document whose name is Rahul.

16. Update Data Using updateOne()

The updateOne() method updates the first document that matches a filter.

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

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

Here:

  • The filter finds Rahul's document.

  • $set changes the course field.

  • modifiedCount reports how many documents were modified.

17. Delete Data Using deleteOne()

The deleteOne() method deletes the first document that matches a filter.

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

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

This deletes the first matching document whose name is Amit.

18. Complete MongoDB and Node.js Connection Example

Now let's combine the connection and basic CRUD operations in one program.

Create or update app.js:

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

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

const client = new MongoClient(uri);

async function main() {

    try {

        // Connect to MongoDB
        await client.connect();

        console.log("MongoDB Connected Successfully!");

        // Select database
        const database = client.db("collegeDB");

        // Select collection
        const students = database.collection("students");

        // Insert one student
        const insertResult = await students.insertOne({
            name: "Rahul",
            age: 21,
            course: "Node.js",
            city: "Raipur"
        });

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

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

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

        // Update student
        const updateResult = await students.updateOne(
            {
                name: "Rahul"
            },
            {
                $set: {
                    course: "Full Stack Development"
                }
            }
        );

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

        // Delete student
        const deleteResult = await students.deleteOne({
            name: "Rahul"
        });

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

    } catch (error) {

        console.error("Error:", error);

    } finally {

        // Close MongoDB connection
        await client.close();

        console.log("MongoDB Connection Closed");

    }

}

main();

Note: This is a learning demonstration. Every time you run it, it inserts a new Rahul document and then updates and deletes one matching Rahul document. For production applications, use a unique identifier or a deliberate test-data strategy to avoid affecting an unintended record.

19. Run the Node.js Application

Open the terminal in your project folder.

Run:

node app.js

If the MongoDB server is running and the connection URI is correct, you should see messages similar to:

MongoDB Connected Successfully!

Inserted ID: ObjectId("...")

All Students: [
    {
        _id: ObjectId("..."),
        name: "Rahul",
        age: 21,
        course: "Node.js",
        city: "Raipur"
    }
]

Updated Count: 1
Deleted Count: 1

MongoDB Connection Closed

The exact ObjectId and output depend on your database records.

20. MongoClient vs MongoDB Database

MongoClient Database
Creates a connection to MongoDB Represents a selected database
Uses the connection URI Selected using client.db()
Manages connection pools Provides access to collections
Example: new MongoClient(uri) Example: client.db("collegeDB")

A single MongoClient can be used to access multiple databases on the same MongoDB deployment.

21. Important Best Practices

  • Use the official MongoDB Node.js Driver.

  • Reuse a single MongoClient for the lifetime of a typical application.

  • Keep connection strings and credentials in environment variables.

  • Handle connection errors using try and catch.

  • Close the client when the application is shutting down.

  • Use appropriate filters when updating or deleting documents.

  • Avoid inserting duplicate test data unintentionally.

  • Use a supported Node.js version and a compatible MongoDB Driver version.

22. Practical Exercise

Try the following tasks:

  1. Create a Node.js project named student-management.

  2. Install the mongodb package.

  3. Connect Node.js with your local MongoDB server.

  4. Create a database named collegeDB.

  5. Select a collection named students.

  6. Insert five student documents.

  7. Retrieve all student records using find().

  8. Retrieve one student using findOne().

  9. Update a student's course using updateOne().

  10. Delete a student using deleteOne().

23. Frequently Asked Questions (FAQs)

Q1. How do I connect MongoDB with Node.js?

Install the official MongoDB Driver using npm install mongodb, create a MongoClient instance and connect using client.connect().

Q2. What is MongoClient in Node.js?

MongoClient is a class provided by the MongoDB Node.js Driver. It creates and manages connections to MongoDB deployments.

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

The official package is named mongodb.

Q4. Can Node.js connect to MongoDB Atlas?

Yes. You can connect using the MongoDB Atlas connection URI and the official MongoDB Node.js Driver.

Q5. What is the use of client.db() in Node.js?

The client.db() method selects a database from the connected MongoDB deployment.

Q6. What is the difference between insertOne() and insertMany()?

insertOne() inserts one document, while insertMany() inserts multiple documents.

Q7. Do I need Express.js to connect MongoDB with Node.js?

No. You can connect directly using the MongoDB Node.js Driver. Express.js is an optional web framework used to build web servers and APIs.

24. Conclusion

Connecting MongoDB with Node.js allows developers to build dynamic applications using JavaScript and a flexible NoSQL database.

In this tutorial, we learned how to:

  • Create a Node.js project.

  • Install the official MongoDB Driver.

  • Use MongoClient.

  • Connect to MongoDB.

  • Select a database and collection.

  • Insert and retrieve documents.

  • Update and delete records.

  • Run a complete MongoDB CRUD application.

By learning MongoDB with Node.js, you can start building real-world applications such as student management systems, e-commerce websites, blog platforms and REST APIs.

←
Post 25 of 35
→