I am using MongoDB via its driver for node.js
I typically open a connection (via the connect()
method) any time I need to perform an operation and close it (via the close()
method) as soon as I am finished. In my programs, as natural, I need to perform many operations against the MongoDB and therefore it happens that I open and close many times the connection.
I am wondering whether this is a good practice or whether it would be better to open the connection as the first operation is executed, store it in a variable and use the already opened connections for the following operations closing it when the program ends.
Any advice is very much appreciated.
There is no need for closing the connection explicitly. This way the application avoids creating and closing connections (which is an expensive operation).
The most simple way to allow MongoDB to reconnect is to define a reconnectTries in an options when passing it into MongoClient . Any time a CRUD operation times out, it will use the parameters passed into MongoClient to decide how to retry (reconnect). Setting the option to Number.
You should close a mongoose connection when a Node POSIX signal is happening. SIGINT process is triggered when Ctrl-C has been pressed on terminal or a server shutdown. Another possible scenario is to close a connection when a data streaming is done.
MongoDB configuration Even MongoDB itself has an option to limit the maximum number of incoming connections. It defaults to 64k.
It is best practice to open the connection once, store it in a variable and close it at the end. MongoDB explicitly recommends this. This is the reason why opening and closing a connection is part of the MongoDB API rather than have it happen automatically for each query.
Opening and closing connections for each query will introduce a significant overhead both in terms of performance (CPU + latency), network traffic, memory management (creating and deleting objects), not only for the client but also for the server itself, which also impacts other clients.
About the terminology of connection: in some drivers like Java, what is actually created and stored in a variable is not a physical connection, but a MongoClient
instance. It looks like a connection from an abstract (API) perspective, but it actually encapsulates the actual physical connection(s) and hides complexity from the user.
Creating the MongoClient
instance only once, for the drivers that support this, will also allow you to benefit from connection pooling where the driver maintains active connections in parallel for you, so that you also only need to create one MongoClient
instance across multiple threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With