在使用PyMongo时,我需要在使用后关闭MongoClient吗?

huangapple go评论66阅读模式
英文:

I am using PyMongo. Do I have to close a MongoClient after use?

问题

A. 关于游标(cursor),我是否需要手动关闭它?我想知道这一点,因为我真的希望像这样做。

for s in collection.find():
   print(s)

B. 关于 MongoClient,我是否需要手动关闭它?这会影响 PyMongo 的连接池功能吗?

from pymongo import MongoClient

url = 'mongodb://localhost:27017'
client = MongoClient(url)               

db = client['test']                    
collection = db['students']             

# 查询
cursor = collection.find()
for s in cursor:
    print(s)

cursor.close()         # 这是否需要?
client.close()         # 这是否需要?

我不确定是否有任何区别。

英文:

I am using PyMongo, and I have some questions about connection and cursor.

A. Do I have to close a cursor? I want to know because I really want to do something like this.

for s in collection.find():
   print(s)

B. Do I have to close a MongoClient manually? Will it affect the connection polling feature of PyMongo?

from pymongo import MongoClient

url = 'mongodb://localhost:27017'
client = MongoClient(url)               

db = client['test']                    
collection = db['students']             

# QUERY
cursor = collection.find()
for s in cursor:
    print(s)

cursor.close()         # Is this required?
client.close()         # Is this required?

I am not sure if there are any differences.

答案1

得分: 1

如文档中所示,cursor.close() 释放了为该游标分配的资源。但是,服务器将在一段时间后自动执行此操作,这并不是(完全)必要的。

如此帖子中所示,关闭游标可能是一个好的实践。

如此帖子中建议最好重用连接而不关闭客户端。

英文:

As shown in the documentation
cursor.close() frees allocated resources to that cursor. However, the server will automatically do this after a time period, and it is not (entirely) needed.

As shown in this post it is probably good practice to close cursors.

As shown in this post it would be best to reuse connections and to not close the client.

huangapple
  • 本文由 发表于 2023年2月16日 10:42:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/75467322.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定