Check the below code:
const mongodb = require('mongodb');
const express = require('express');
const app = express();
let db;
const options = {};
mongodb.MongoClient.connect('mongodb://localhost:27017/test', options, function(err, database) {
if (err) throw err;
db = database.db('test');
app.listen(process.env.PORT || 3000, function() {
console.log(`Express.js server up.`);
});
});
app.get('/', function (req, res) {
db.collection('test').countDocuments({}, function(err, count) {
return res.json({'documentCount': count});
});
});
It is a simple code to do a count operation in MongoDB. My understanding about the above code is that I create a single MongoDB connection and assign it to db
, then reuse it where I need to execute queries.
But this Stack Overflow answer states:
Each
.connect()
creates a new connection pool, not a connection
Also, this article states:
The pool size is the option that determines how many queries may be run using the same connection in parallel, similar to the number of lanes in a tunnel.
If the connect()
method is creating a pool
instead of connection
, at what point are the connections getting created? Does each query
create a new connection (or reuse) in the specified pool?
If I execute .connect()
only once in my code with poolSize: 5
. Does it create 5 connections immediately?
2
Answers
When you call
mongodb.MongoClient.connect
, you’re essentially creating a connection pool, not just a single connection to MongoDB. This pool contains a number of connections that can be reused for different queries, which is an efficient way to handle database interactions in an environment where there might be many concurrent operations happening.In your code, when you call
mongodb.MongoClient.connect
, it initializes a connection pool, and thedb
variable holds a reference to this pool. Then, whenever you execute a query likedb.collection('test').countDocuments({}, function(err, count) {...}
, a connection is borrowed from the pool to execute the query, and returned to the pool once the query execution is complete.From the docs, the connect() methods connects the client you created with
mongodb.MongoClient
to aMongoDB Atlas deployment, a MongoDB instance, or a replica set the mongoDB driver, and this creates a connection pool.
The number of concurrent connections in the pool is then managed internally by the mongoDB driver, as required by the workload.
However, in the connection options you can override the default settings, including how many concurrent connections there can be for this client (with the
maxPoolSize
andminPoolSize
options; default value is a 100).But I think overriding default settings would only be recommended if you are collecting metrics and monitoring MongoDb closely. Then, it may be that you want to fine tune it with the override settings
Please refer to THIS very good answer in the mongoDb community forums, for more details.