Creating a persistent MongDB connection with PyMongo

2.7k views Asked by At

What are methods of having persistent connections to a MongoDB, instead of creating a MongoClient instance and using it when constructing queries? I noted that it opens/closes a connection on each query operation.

I'm using Python, and have pymongo installed. I've looked around and didn't find much information on connection management. In light of this, what are general recommendations on database management?

1

There are 1 answers

0
A. Jesse Jiryu Davis On

Just have a global MongoClient at the top level of a Python module:

client = MongoClient(my_connection_string)

It's critical that you create one client at your application's startup. Use that one same client for every operation for the lifetime of your application and never call "close" on it. This will provide optimal performance.

The client manages a connection pool, and reuses connections as much as possible. It does not open and close a new connection per query, that would be awful. See PyMongo's docs for connection pooling.