How to close a mongodb python connection?

PythonMongodbConnectionPymongo

Python 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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionlrenteView Question on Stackoverflow
Solution 1 - PythonalecxeView Answer on Stackoverflow
Solution 2 - PythonNiraj KaleView Answer on Stackoverflow