6

In the following code, the mongoClient.connect call (by default) opens a pool of 5 connections. Since Node is single threaded, only one call (either func1 or func2 can be processed at any time (The second call waits till the first completes). So only one of the five connections from the pool is ever used.

Using Nodejs cluster, if we fork multiple instances, each instance opens it's own connection pool (5 connections per instance).

The question is - how does MongoDB connection pool work in the Node environment. How can we test this to demonstrate the use of multiple connections from the same pool at the same time?

mongoClient.connect('mongodb://localhost', function(err, db){
  app.get('/func1', function(req, res){
    for (var i=0; i<100000; i++){
      db.collection('test').insert({a:i});
    }
    res.end();
  });

  app.get('/func2', function(req, res){
    for (var i=0; i<100000; i++){
      db.collection('test').insert({a:i});
    }
    res.end();
  });
});

1 Answer 1

1

insert is async so the /func1 and /func2 handlers both just queue up 100000 inserts and then return. The connection pool then operates in the background to execute those inserts no more than 5 at a time (1 per connection in the pool).

Sign up to request clarification or add additional context in comments.

3 Comments

So the pool is only used internally by mongo and cannot be used in the main node application code (since node is single threaded) ?
@Raj No, the connection pool exists within the node application code, using multiple network connections to the MongoDB server to asynchronously execute queries in parallel, while still using just the single thread.
Thanks. Is there any stats in mongodb to tell us the max connection used in a pool ? To see if we are close to the allowed max and to bump it up if needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.