0
0
MongoDBquery~5 mins

Connection pooling concept in MongoDB

Choose your learning style9 modes available
Introduction
Connection pooling helps reuse database connections to make apps faster and use less resources.
When your app needs to talk to the database many times quickly.
When you want to avoid the delay of opening a new connection each time.
When you want to save memory and CPU by sharing connections.
When multiple users or parts of your app access the database at once.
When you want smoother and faster database access in web apps.
Syntax
MongoDB
const client = new MongoClient(uri, { maxPoolSize: 10 });
maxPoolSize sets how many connections can be open at once.
The pool automatically manages connections for you.
Examples
Limits the pool to 5 connections for smaller apps.
MongoDB
const client = new MongoClient(uri, { maxPoolSize: 5 });
Allows up to 20 connections for busier apps.
MongoDB
const client = new MongoClient(uri, { maxPoolSize: 20 });
Uses default pool size if not specified.
MongoDB
const client = new MongoClient(uri);
Sample Program
This example connects to MongoDB with a pool size of 3, inserts a document, then finds and prints it.
MongoDB
import { MongoClient } from 'mongodb';

async function run() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri, { maxPoolSize: 3 });

  try {
    await client.connect();
    const db = client.db('testdb');
    const collection = db.collection('testcollection');

    // Insert a document
    await collection.insertOne({ name: 'Alice', age: 25 });

    // Find the document
    const result = await collection.findOne({ name: 'Alice' });
    console.log(result);
  } finally {
    await client.close();
  }
}

run();
OutputSuccess
Important Notes
Connection pools improve speed by reusing connections instead of opening new ones.
Too small a pool can cause waiting; too large wastes resources.
MongoDB driver manages the pool automatically once set.
Summary
Connection pooling reuses database connections for better speed and resource use.
Set maxPoolSize to control how many connections can be open at once.
Use connection pooling when your app talks to the database many times.