You set the max connection idle time to 5 seconds. Quoting from ClientOptions.SetMaxConnIdleTime()
:
SetMaxConnIdleTime specifies the maximum amount of time that a connection will remain idle in a connection pool before it is removed from the pool and closed. This can also be set through the "maxIdleTimeMS" URI option (e.g. "maxIdleTimeMS=10000"). The default is 0, meaning a connection can remain unused indefinitely.
The 5 seconds you set means that if a connection is in the pool and is not used for 5 seconds, it can be removed from the pool.
And you said you waited 5 seconds, and you experienced that connections in the pool were closed. This is the intended / allowed behavior.
If you want the connections to stay alive indefinitely, don't set the max connection idle time, or set 0
explicitly:
cli, err := mongo.Connect(ctx, options.Client()
.ApplyURI(uri)
.SetMinPoolSize(20)
.SetMaxConnIdleTime(0))
You could ask what's the point of setting min pool size if connections can still be dropped from it. Yes, that's true, but only after the idle time has expired. The pool size may peak above the allowed minimum, e.g. if you set 20 as the minimum, and there's a need for a 100 connections, then 100 connections may be created. If all those 100 connections become idle, you can be sure at least 20 will be kept alive, for the idle time duration. If min pool size would be set to 10, you would have only guarantee for 10 being kept alive.