How to close a mongodb python connection?
PythonMongodbConnectionPymongoPython Problem Overview
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?
Python Solutions
Solution 1 - Python
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.
Solution 2 - Python
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)