我正在编写一个 Python 脚本,用于向 MongoDB 写入一些数据。 当完成时,需要关闭连接并释放一些资源。
在 Python 中应该如何实现呢?
我正在编写一个 Python 脚本,用于向 MongoDB 写入一些数据。 当完成时,需要关闭连接并释放一些资源。
在 Python 中应该如何实现呢?
在您的MongoClient
实例上使用close()
方法:
client = pymongo.MongoClient()
# some code here
client.close()
清理客户端资源并断开与MongoDB的连接。
通过发送一个或多个endSessions命令来结束由该客户端创建的所有服务器会话。
关闭连接池中的所有套接字并停止监视器线程。with pymongo.MongoClient(db_config['HOST']) as client:
db = client[ db_config['NAME']]
item = db["document"].find_one({'id':1})
print(item)
def close(self):
...
if self._encrypter:
# TODO: PYTHON-1921 Encrypted MongoClients cannot be re-opened.
self._encrypter.close()
另外,自4.0版本以来,在调用close()
之后,客户端不会在任何情况下重新连接。
def close(self) -> None:
"""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.
.. versionchanged:: 4.0
Once closed, the client cannot be used again and any attempt will
raise :exc:`~pymongo.errors.InvalidOperation`.
disconnect
已不再提供。 - sri85