检查当前连接到MongoDb的数量
检查MongoDb当前连接数的原因是为了在调试问题时查看连接数。下面是使用Mongo Shell查询当前连接数的代码:
db.currentOp(true).inprog.reduce((accumulator, connection) => { ipaddress = connection.client ? connection.client.split(":")[0] : "Internal"; accumulator[ipaddress] = (accumulator[ipaddress] || 0) + 1; accumulator["TOTAL_CONNECTION_COUNT"]++; return accumulator; }, { TOTAL_CONNECTION_COUNT: 0 })
这段代码返回了一个对象,其中包含了每个IP地址的连接数以及总连接数。例如:
{ "TOTAL_CONNECTION_COUNT" : 331, "192.168.253.72" : 8, "192.168.254.42" : 17, "127.0.0.1" : 3, "192.168.248.66" : 2, "11.178.12.244" : 2, "Internal" : 41, "3.100.12.33" : 86, "11.148.23.34" : 168, "81.127.34.11" : 1, "84.147.25.17" : 3 }
其中,"Internal"表示内部进程,没有外部客户端。可以使用以下代码查看这些进程的列表:
db.currentOp(true).inprog.filter(connection => !connection.client).map(connection => connection.desc);
在Atlas实例上运行以上示例时,可能会出现以下错误:`E QUERY [js] TypeError: db.currentOp(...).inprog is undefined :`。这是因为在Atlas上的某些层级中不允许使用`$all`操作符查询当前操作。解决方法是将`connection.client`改为`connection.client_s`。