title: How to get the number of connections used (and free) to the MongoDB (from a client perspective)?
body: <p>I'm posting the question here just to be sure I'm not barking on the wrong tree.</p>
  
  <p>How to get the <strong>number of connections</strong> <em>used</em> (and <em>free</em>) to the MongoDB, but from a client perspective (eg. Java client), using the 4.x driver?</p>
  
  <p>There are posts regarding using the serverStatus(<a href="https://stackoverflow.com/questions/21258696/get-the-number-of-open-connections-in-mongodb-using-java">Get the number of open connections in mongoDB using java</a>), but it presumes having 'admin' access to the MongoDB. Using a 'regular user'(an db user with lower privileges (e.g access to only one database)) cannot run the serverStatus(). But this provides only a view from the server-side (there are <em>N</em> connections from IP <em>x</em>).</p>
  
  <p>Other posts mentioned how to setup the connection pool size (eg. using the <code>MongoClients.create​(MongoClientSettings settings)</code> (see the 4.x API reference (<a href="https://mongodb.github.io/mongo-java-driver/4.0/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClients.html" rel="nofollow noreferrer">https://mongodb.github.io/mongo-java-driver/4.0/apidocs/mongodb-driver-sync/com/mongodb/client/MongoClients.html</a>)):</p>
  
  <pre><code>        MongoCredential credential = MongoCredential.createCredential(
                      username,
                      "admin",
                      password.toCharArray());
  
          MongoClient mongoClient = MongoClients.create(MongoClientSettings.builder()
                  .applyToClusterSettings(
                          builder -&gt; builder.hosts(Arrays.asList(new ServerAddress(hostname, portNumber))))
                  .credential(credential)
                  .applyToConnectionPoolSettings(builder -&gt; builder
                                                                  .minSize(connectionPoolMinimumSize)
                                                                  .maxSize(connectionPoolMaximumSize))
                  .readConcern(readConcern)
                  .readPreference(readPreference)
                  .writeConcern(writeConcern)
                  .build());
  </code></pre>
  
  <p>But none provided means to get the used and available connections the connection pool.</p>
  
  <p>As mentioned by Oleg, using the ConnectionPoolListener would be a way, but that is available only in the 3.x drivers. The ConnectionPoolListener methods are marked as deprecated on 4.x (although it is still mentioned in the JMX Monitoring section (<a href="http://mongodb.github.io/mongo-java-driver/4.0/driver-reactive/reference/monitoring/" rel="nofollow noreferrer">http://mongodb.github.io/mongo-java-driver/4.0/driver-reactive/reference/monitoring/</a>).</p>