How to close a mongodb python connection?

Question:

I’m doing a python script that writes some data to a mongodb.
I need to close the connection and free some resources, when finishing.

How is that done in Python?

Asked By: lrente

||

Answers:

Use close() method on your MongoClient instance:

client = pymongo.MongoClient()

# some code here

client.close()

Cleanup client resources and disconnect from MongoDB.

End all server sessions created by this client by sending one or more endSessions commands.

Close all sockets in the connection pools and stop the monitor threads.

Answered By: alecxe

The safest way to close a pymongo connection would be to use it with ‘with’:

with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})
    print(item)
Answered By: Niraj Kale

Adding to @alexce’s answer, it’s not always true. If your connection is encrypted, MongoClient won’t reconnect:

    def close(self):
        ...
        if self._encrypter:
            # TODO: PYTHON-1921 Encrypted MongoClients cannot be re-opened.
            self._encrypter.close()

also, since version 4.0, after calling close() client won’t reconnect in any case.

   def close(self) -> None:
        """Cleanup client resources and disconnect from MongoDB.
        End all server sessions created by this client by sending one or more
        endSessions commands.
        Close all sockets in the connection pools and stop the monitor threads.
        .. versionchanged:: 4.0
           Once closed, the client cannot be used again and any attempt will
           raise :exc:`~pymongo.errors.InvalidOperation`.
Answered By: big_chongus
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.