How to close a mongodb python connection?

lrente picture lrente · Aug 23, 2013 · Viewed 51.6k times · Source

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?

Answer

alecxe picture alecxe · Aug 23, 2013

Use close() method on your MongoClient instance:

client = pymongo.MongoClient()

# some code here

client.close()

close() is an alias for disconnect() method:

Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened.