How do we identify the idle connections in MongoDB across all dbs

Connections in MongoDB are not bound to a specific namespace (a database and/or a collection). While there is no separate command that would allow an operator to list all of the client connections established to a particular MongoDB instance, you can use the db.currentOp() command for that purpose. Normally (by default) it is used to list the active threads only, however if it’s executed as db.currentOp(true) it will list the information about all of the threads the MongoDB server has spawned. And, since for each client connection there is a corresponding “conn” thread, such threads would also be listed there.

For instance this is how you could filter out the “conn” threads:

var res = db.currentOp(true);
res.inprog.forEach(function(t) {
	if(t.desc == "conn") {

You can then process the output as you feel is necessary – to group the connections by the “client”, to aggregate and count the number of connections in each group etc. You can either implement it as a script or, potentially, you could write the output of my short script into a collection and then run some Aggregation queries on that.

You may also be interested to know that in MongoDB v3.6 a new Aggregation operator was introduced called $currentOp – it allows users to process the output of the currentOp command in the Aggregation framework without having an intermediary step of writing the db.currentOp() output into a collection.

Consider this example that counts the number of connections per client IP address:

db.getSiblingDB("admin").aggregate( [ {
   $currentOp : { allUsers: true, idleConnections: true } }, 
	{ $match : { desc: "conn" } },
	{ $project : { ip : { $split: ["$client", ":"] }, connId: "$connectionId"} },
	{ $group: {
		_id: { $arrayElemAt: [ "$ip", 0 ] },
		count: { $sum: 1 }
] );
  • Ask Question