87

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?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
lrente
  • 1,070
  • 1
  • 9
  • 27

3 Answers3

161

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.

Gianfranco P.
  • 10,049
  • 6
  • 51
  • 68
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 24
    And also `disconnect ` is no longer available from pymongo 3.x – sri85 Sep 23 '15 at 12:45
  • 1
    @alecxe, there any way or form of know if the connect daba base closed? – julian salas Aug 02 '16 at 22:24
  • 4
    in Jupyter Notebook, after .close() I'm still able to query the DB. Is it auto-reconnecting? – Nikhil VJ Jul 18 '20 at 05:18
  • 4
    @NikhilVJ In the above `answer`, it says: `Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened.` – NYCeyes Apr 27 '21 at 02:03
30

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)
Clinton
  • 2,296
  • 4
  • 19
  • 21
Niraj Kale
  • 459
  • 4
  • 5
0

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`.