MongoDB - open and close connection - advise for good practice

后端 未结 1 671
深忆病人
深忆病人 2021-02-20 05:36

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

1条回答
  •  长情又很酷
    2021-02-20 06:01

    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.

    0 讨论(0)
提交回复
热议问题