Mongodb – How to close mongodb idle connection(active: false)

mongodb

I have an application running on node and using the mongodb library to establish connection and closing it. But the problem is, from the mongo serverStatus() command i can see that there is still 2k+ current connections still available.

> db.serverStatus().connections
{ "current" : 2993, "available" : 835867, "totalCreated" : 220841 }

and most of it are having the active: false status.

My questions is, is there a way for me to force close these idle connections which after some time will affect my application with an timeout error.

I tried using the killOp() command but these only works if there is still opid value listed in these idle connections.

Appreciate some feedback on how can handle this kind of situations.

Best Answer

This can be avoided by setting up the maxIdleTimeMS parameter of Connection Pool Options

This maxIdleTimeMS parameter sets the maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed.

Set this parameter as per your requirement. So the idle connections will be closed once the time limit exceeds.