MongoDB - open and closed connection - recommended for good practice

I use MongoDB through my driver for node.js

I usually open a connection (using the connect() method) anytime I need to perform an operation and close it (using the close() method) as soon as I finish. In my programs, as natural, I need to perform many operations against MongoDB, and so it happens that I open and close the connection many times.

I am wondering if this is good practice or whether it would be better to open the connection on the first operation, save it in a variable, and use already open connections for the following operations that close it when the program ends.

Any advice is greatly appreciated.

+5
source share
1 answer

It is best to open the connection once, save it in a variable, and close it at the end. MongoDB directly recommends this. For this reason, opening and closing a connection is part of the MongoDB API, and not automatically for each request.

Opening and closing connections for each request will lead to significant overhead both in terms of performance (latency with the processor + latency), network traffic, memory management (creating and deleting objects) not only for the client, but also for the server itself, which also affects to other customers.

About connection terminology: in some drivers, such as Java, what is actually created and stored in a variable is not a physical connection, but an instance of MongoClient . This is similar to an abstract perspective (API) connection, but it actually encapsulates the actual physical connection and hides the complexity from the user.

Creating an instance of MongoClient only once, for drivers that support this, will also allow you to use a connection pool where the driver supports active connections in parallel for you, so you also only need to create one instance of MongoClient for multiple threads.

+6
source

All Articles