The question is simple: should I keep all operations to a single MongoClient
? Is single client or multiple clients better than the other?
PyMongo is thread-safe and provides built-in connection pooling for threaded applications.
Typically yes, it is a good practice to make MongoClient a singleton. As mentioned in the MongoDB Java driver: The MongoClient instance represents a pool of connections to the database; you will only need one instance of class MongoClient even with multiple threads.
PyMongo is the official native driver for MongoDB. It includes all the functionalities of the MongoDB Query API. It is a powerful way to perform CRUD (Create-Read-Update-Delete) operations on a database and provides an easy way to build aggregation pipelines.
There's no need to close a Connection instance, it will clean up after itself when Python garbage collects it. You should use MongoClient instead of Connection ; Connection is deprecated. To take advantage of connection pooling, you could create one MongoClient that lasts for the entire life of your process.
The MongoClient actually maintains a connection pool. So having multiple clients does not have any advantages. Quite the contrary, since a new client has to connect to MongoDB first, which requires a three way handshake and other overhead each time a new client is created.
Since multiple clients only have disadvantages for a single application, the answer is: Only create one client and use it everywhere you need to make a connection.
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