Introduction
Connection pooling helps reuse database connections to make apps faster and use less resources.
const client = new MongoClient(uri, { maxPoolSize: 10 });
const client = new MongoClient(uri, { maxPoolSize: 5 });
const client = new MongoClient(uri, { maxPoolSize: 20 });
const client = new MongoClient(uri);
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();
maxPoolSize.maxPoolSize correctly in the connection string.const client = new MongoClient(uri, { maxPoolSize: 5 });
await client.connect();
const db = client.db('test');
const col = db.collection('items');
// Simulate 10 quick queries
for (let i = 0; i < 10; i++) {
await col.findOne({});
}
What is the effect of setting maxPoolSize to 5 here?const client = new MongoClient(uri, { maxPoolSize: 10 });
await client.connect();
// Later in code
await client.close();
await client.connect();
But you notice performance drops after reconnecting. What is the likely problem?Pass the test and this pattern moves unknown