Open In App

What is Connection Pooling with MongoDB in Node.js ?

In this article, we are going to see in-depth connection pools MongoDB in Nodejs. A connection pool serves as a collection of established TCP connections that your application’s MongoDB driver maintains with a MongoDB server. This pool’s purpose is to minimize the need for frequent network handshakes, ultimately enhancing your application’s performance by reducing connection setup overhead.

Working Of Connection Pools:

Using and Creating Connection Pools :

Steps to create MongoDB Connection’s:

Step 1: First Install Mongodb module using NPM. Run below command to install MongoDB.



npm install mongodb

Step 2: Now create a new javascript file for creating a MongoDBconnection. The import mongoclient from mongodb using below line .

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

Step 3: Now you should use a connection string to connect to the database. If you are using atlas use a connection string from Atlas portal else use a local connection string.



const uri = <YOUR_CONNECTION_STRING_HERE>;

Example: In this example, we will write NodeJS code to create and use MongoDB connection pools. For this purpose, you can install MongoDB locally or you can use MongoDB Atlas. for this example, we will be using MongoDB Atlas .




const { MongoClient } = require('mongodb');
const uri = '<YOUR_CONNECTION_STRING_HERE>';
  
MongoClient.connect(uri,
    { minPoolSize: 2, maxPoolSize: 10 })
    .then(async client => {
        try {
            await client.db("admin").command({ ping: 1 });
            console.log("Connected to MongoDB!");
        } finally {
            await client.close();
        }
    });

Step 4: Run the file using below command.

node file.js

Output: After successful connectivity you should get following output.

Pros of MongoDb Connection Pooling:

Cons of MongoDb Connection Pooling:

Article Tags :