如何关闭Python中的MongoDB连接?

87

我正在编写一个 Python 脚本,用于向 MongoDB 写入一些数据。 当完成时,需要关闭连接并释放一些资源。

在 Python 中应该如何实现呢?

3个回答

162

在您的MongoClient实例上使用close()方法:

client = pymongo.MongoClient()

# some code here

client.close()
清理客户端资源并断开与MongoDB的连接。 通过发送一个或多个endSessions命令来结束由该客户端创建的所有服务器会话。 关闭连接池中的所有套接字并停止监视器线程。

24
从pymongo 3.x开始,disconnect已不再提供。 - sri85
1
@alecxe,有没有办法或形式可以知道数据库连接是否关闭? - julian salas
4
在Jupyter Notebook中,即使执行了.close()方法,我仍然能够查询数据库。这是自动重新连接的吗? - Nikhil VJ
5
在上面的“回答”中,它说:“断开连接将关闭连接池中的所有底层套接字。如果再次使用此实例,它将自动重新打开。” - NYCeyes

31
使用'with'语句是关闭pymongo连接最安全的方式:
with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})
    print(item)

1
当你有一个实时应用程序可以在几分钟内执行数十万次操作时,这是否会导致太多的流量? - Ionut-Alexandru Baltariu

1
增加到@alexce的回答中,这并不总是正确的。如果您的连接是加密的,MongoClient将不会重新连接:
    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`.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接