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?
javascript, node.js, database, mongodb The MongoClient#close() method API documentation says: Close the client, which will close all underlying cached resources, including, for example, sockets and background monitoring threads.
There's no need to close a Connection instance, it will clean up after itself when Python garbage collects it. You should use MongoClient instead of Connection ; Connection is deprecated. To take advantage of connection pooling, you could create one MongoClient that lasts for the entire life of your process.
Call the method server_info() of the client instance to check MongoDB server running Pymongo Python with the exception called ServerSelectionTimeoutError .
The first step to connect python to Atlas is MongoDB cluster setup. Next, create a file named pymongo_test_insert.py in any folder to write pymongo code. You can use any simple text editor like Textpad/Notepad. Use the connection_string to create the mongoclient and get the MongoDB database connection.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With