Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a mongodb python connection?

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?

like image 497
lrente Avatar asked Aug 23 '13 10:08

lrente


People also ask

How do I close a MongoDB connection?

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.

Do I need to close a PyMongo connection?

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.

How do I know if Python is running MongoDB?

Call the method server_info() of the client instance to check MongoDB server running Pymongo Python with the exception called ServerSelectionTimeoutError .

How does Python connect to MongoDB?

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.


Video Answer


2 Answers

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.

like image 199
alecxe Avatar answered Oct 01 '22 01:10

alecxe


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)
like image 33
Niraj Kale Avatar answered Sep 30 '22 01:09

Niraj Kale