Is there any way to get the number of opened connections in a pool?

I thought it was connection.base.connections.length but it’s not.

Hey @fberrez,

Connection pool details aren’t exposed via any public APIs, however we do document an example of how you can do this in our connection pool monitoring examples:

function connectionPoolStatus(client) {
  let checkedOut = 0;
  function onCheckout() {
    checkedOut++;
  }
  function onCheckin() {
    checkedOut--;
  }
  function onClose() {
    client.removeListener('connectionCheckedOut', onCheckout);
    client.removeListener('connectionCheckedIn', onCheckin);
    checkedOut = NaN;
  }
  // Decreases count of connections checked out of the pool when connectionCheckedIn event is triggered
  client.on('connectionCheckedIn', onCheckin);
  // Increases count of connections checked out of the pool when connectionCheckedOut event is triggered
  client.on('connectionCheckedOut', onCheckout);
  // Cleans up event listeners when client is closed
  client.on('close', onClose);
  return {
    count: () => checkedOut,
    cleanUp: onClose
  };
}
2 Likes

Hi @alexbevi ,

Thank you. for your “homemade” way to go.

I have now more data about my connection pools on my different apps. I have maybe one question about it.

I have this application that performs a lot of finds, inserts, updates and deletes on db1 and it performs finds only on db2 and db3.

According to this graph, we can see that db1 has a median of 20 connections opened constantly (out of 20) while db2 and db3 has a median of 1 connection opened (out of 20).

With the informations I gave here, could it be considered as correct?

Thanks.

The connection pool is associated with the MongoClient instance; not a particular database, so it would be difficult to judge accuracy without more information :wink:

It would really depend on how you’re capturing/recording telemetry …

Yes sorry I forgot to add that each MongoClient is connected to one specific database (the uri would be mongodb+srv://username:password@host.com/db1).

Also, I only log when a connection is checking out like:

// this.conn is a mongoose connection
// this.conn.getClient() returns the mongodbclient instance
// this.checkedout is initialised at 0 in my constructor
this.conn.getClient().on('connectionCheckedIn', () => {
  this.checkedout -= 1;
});

this.conn.getClient().on('connectionCheckedOut', (e) => {
  this.checkedout += 1;
  // logs only the used connections
  this.logger.info(`MongoDB[${this.name}] Connection is checked out.`, MONGO_INFOS.MONGODB_CHECKED_OUT, { checkedout: this.checkedout });
});