itaied
itaied

Reputation: 7107

how to get connected clients in MongoDB

I'm writing an app using mongo as its db. I want to print the clients connected to the db, for example, print their ip. How can I get that info?

I tried using

db.serverStatus().connections

But it gives me the number of computers with access to my db.

Upvotes: 16

Views: 27733

Answers (4)

M. Gleria
M. Gleria

Reputation: 513

I got a list of open connections in the following format:

{
  client: '10.1.222.213:16088',
  description: 'conn190295'
}

executing this command from a mongosh connection with Admin privileges:

​db.currentOp(true).inprog.forEach( function(op) {     if(op.active = true && op.client != undefined) {         var miniOp = { client : op.client, description : op.desc };         printjson(miniOp);     }  } );  

source: https://intercom-help.mongodb.com/en/articles/1565007-how-many-connections-for-a-cluster

Upvotes: 0

Joshua Huber
Joshua Huber

Reputation: 3533

This is a bit hacky, but you can actually get this via netstat, even without connecting to the db. This would be done in a (bash) shell script on the DB server. I actually have this in my login script (~/.bash_profile), so that I can easily (& quickly) find network connections into MongoDB and any other service that runs on TCP.

First, you would run this in the shell, which defines a function.

function whoIsConnectedToPort () {
    PORT=$1
    netstat -an | grep ":${PORT}.*ESTAB" | awk '{print $4":"$5}' | cut -d: -f2- | grep "^${PORT}:" | cut -d: -f2 | grep -v '^127' | sort | uniq | xargs -n1 nslookup | grep 'name =' | awk {'print $NF'} | sed 's/.$//' | sort | uniq
}

Then invoke the function.

whoIsConnectedToPort 27017

This should return a list of hosts connected to the given port.

You can reuse it for other familiar ports. Try for example:

whoIsConnectedToPort 22
whoIsConnectedToPort 3306
whoIsConnectedToPort 1521

Upvotes: 0

John Petrone
John Petrone

Reputation: 27487

You should be able to run this command and get a list of connected IP addresses:

db.currentOp(true).inprog.forEach(function(d){if (d.client)printjson(d.client)})

db.currentOp is actually built on top of the special collection $cmd.sys.inprog so you can also query that directly. You can get an idea of the how to do that by typing in db.currentOp without the parentheses into the mongo shell and it will print out the source for the function:

> db.currentOp
function ( arg ){
    var q = {}
    if ( arg ) {
        if ( typeof( arg ) == "object" )
            Object.extend( q , arg );
        else if ( arg )
            q["$all"] = true;
    }
    return this.$cmd.sys.inprog.findOne( q );
}

Upvotes: 20

Markus W Mahlberg
Markus W Mahlberg

Reputation: 20703

You can use db.currentOp(true) and iterate over the inprog array of the result set, using the client field.

Upvotes: 14

Related Questions