Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyMongo: Should I use single or multiple clients?

The question is simple: should I keep all operations to a single MongoClient? Is single client or multiple clients better than the other?

like image 466
laike9m Avatar asked Apr 25 '15 09:04

laike9m


People also ask

Is PyMongo client thread safe?

PyMongo is thread-safe and provides built-in connection pooling for threaded applications.

Is MongoClient a singleton?

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.

Is PyMongo the same as MongoDB?

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.

Do I need to close PyMongo connection?

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.


1 Answers

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.

like image 74
Markus W Mahlberg Avatar answered Sep 28 '22 06:09

Markus W Mahlberg