如何关闭mongodb python连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18401015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:38:44  来源:igfitidea点击:

How to close a mongodb python connection?

pythonmongodbconnectionpymongo

提问by user1835591

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.

我正在做一个将一些数据写入 mongodb 的 python 脚本。完成后,我需要关闭连接并释放一些资源。

How is that done in Python?

这在 Python 中是如何完成的?

采纳答案by alecxe

Use close()method on your MongoClientinstance:

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

client = pymongo.MongoClient()

# some code here

client.close()

close()is an alias for disconnect()method:

close()disconnect()方法的别名:

Disconnecting will close all underlying sockets in the connection pool. If this instance is used again it will be automatically re-opened.

断开连接将关闭连接池中的所有底层套接字。如果再次使用此实例,它将自动重新打开。

回答by Niraj Kale

the safest way to close pymongo connection would be to use it with 'with'

关闭 pymongo 连接的最安全方法是将它与“with”一起使用

with pymongo.MongoClient(db_config['HOST']) as client:
    db = client[ db_config['NAME']]
    item = db["document"].find_one({'id':1})
    print(item)