1

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.

Marv
  • 33
  • 3
  • Does this answer your question? [Python MySQLdb: connection.close() VS. cursor.close()](https://stackoverflow.com/questions/5504340/python-mysqldb-connection-close-vs-cursor-close) – Blue Robin Feb 16 '23 at 02:43
  • @BlueRobin No, it is for another database and package. What I really want to know is if client.close() affect PyMongo's connection polling features. – Marv Feb 16 '23 at 02:53
  • I don't believe it would affect the pooling features as you are freeing up allocated resources and not the connection entirely. I may be wrong, however. – Blue Robin Feb 16 '23 at 03:17

1 Answers1

0

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.

Blue Robin
  • 847
  • 2
  • 11
  • 31