OJT
OJT

Reputation: 899

PyMongo client close in class framework

I have a Python class in which I create PyMongo MongoDB connections during init (see code below). I want to instantiate this class in another script and then ensure that all connections are closed at the end of the script. If I do so, then run self.client.close() as below and then check on open connections, I get back a return that looks as if there are still active connections. Am I overthinking this, and all connections are actually closed?

class BaseClass():

    def __init__(self):
        self.client = MongoClient("url")
        self.cursor1 = self.client.get_database('db1').get_collection('col1')
        self.cursor2 = self.client.get_database('db2').get_collection('col2')

test = BaseClass()
test.client.close()
test.client.connections
Database(MongoClient(host=['url'], document_class=dict, tz_aware=False, connect=True, retrywrites=True, w='majority', authsource='admin', replicaset='url', ssl=True), 'connections')

Upvotes: 0

Views: 218

Answers (1)

Belly Buster
Belly Buster

Reputation: 8814

Yes you are overthinking it; there's no need to close connections, pymongo's connection pooling will take care of this for you.

If you are needing to create lots of these objects, it will be more efficient to create one MongoClient connection and then pass that as a parameter to each class.

Upvotes: 1

Related Questions