Periodic Connections to Mongodb

I have a Phoenix app that contains a single page that has to do Mongodb searches. I believe what I’d want is to connect to the Mongodb collection, query and then disconnect. But there’s no disconnect in the API. So that seems to indicate that I’m just approaching this in a way that the designers of the library didn’t intend. Did they expect that you’d send a Process.exit to it to close the connection? How can I use Mongodb but not eat up connection to the server when its unused 99% of the time?

Which driver do you use?

If you are even using ecto to do the querying, then in fact it’s the way you use it. Ecto and it’s database adapters use a shared connection pool. If you are sure there are not more than one or two requests at the same time, just use a small pool size.

What I did was write a GenServer, It doesn’t connect until the first query comes in. It keeps the pid returned by Mongo.start_link(database: dbname, seeds: hosts) as part of its state. But after n minutes I’d like to shutdown the process to remove the Mongo connection. I may be working too hard at this but I just hate having a connection that is just hanging around and not doing anything useful.

As I read the issue below, it should be possible to close the connection using GenServer.stop(mongo_pid).

1 Like