I use MongoDB and I connect to it through pymongo. Here's my code:
>>> import pymongo
>>> con=pymongo.Connection('localhost',27017)
>>> con.database_names()
['local', 'bookdb']
>>> con.close()
>>> con.database_names()
['local', 'bookdb']
I use con.close()
to disconnect to the MongoDB, but after that, I can still use con.database_names()
to see the list of the databases. Why? it never disconnect to the MongoDB server. Why the close()
not work?
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.
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. .. versionchanged:: 4.0 Once closed, the client cannot be used again and any attempt will raise :exc:`~pymongo. errors.
No, you do not need to close connections to DB - your only connection is via MongoClient and as the documentation states - it handles connection pooling for you. The only resource that you would want to clean up would be a cursor which you should close() when you're done with it.
open(function (err, db) { db. close(); }); // Open another connection db. open(function (err, db) { db. close(); });
Just read the docs, faster and more detailed.
If this instance is used again it will be automatically re-opened.
Link to docs
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