Open In App

What is Connection Pooling with MongoDB in Node.js ?

Last Updated : 12 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Connections pools create multiple connections at the same time.
  • We can use these connections as per requirement, and perform operations on the database.
  • Once the operation is completed the connection is automatically returned to the pool.
  • When an application requires a new connection a connection from the available connection is used.

Using and Creating Connection Pools :

  • You can create a connection pool by specifying maxPoolSize while creating a connection. By default, it has a value of 100.
  • You can also specify a minimum number of connections that a pool should contain. This value should be less than minPoolSize.
  • Connections Pools have other attributes which can be used to configure other settings.

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 .

Javascript




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.

Screenshot-(292)

Pros of MongoDb Connection Pooling:

  • Improved Performance
  • Resource Management
  • Scalability

Cons of MongoDb Connection Pooling:

  • Potential Connection Staleness
  • Increased Complexity

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads