如果连接断开,如何强制pymongo重新连接并进行操作?

how to force pymongo to reconnect if the connection is down , and do the operation?

我正在尝试弄清楚如何处理 pymongo.errors.ServerSelectionTimeoutError 如果数据已关闭或以某种方式连接到 studio 3T (mongogui) 导致数据库关闭。所以我想重新连接到 mongo .

if __name__ == '__main__':
    client = pymongo.MongoClient(host='localhost', port=27017)
    db = client.info_collect
    collection = db['info']
    if collection.count_documents({'link': url}) < 1:
        collection.insert_one(add_dict)

您应该将您的代码包装在一个 try-except 块中,在该块中您通过重试重新连接并再次在 except 块中执行相同的查询来处理 ServerSelectionTimeoutError 异常。 类似于:

if __name__ == '__main__':

try:
    client = pymongo.MongoClient(host='localhost', port=27017)
    db = client.info_collect
    collection = db['info']
    if collection.count_documents({'link': url}) < 1:
        collection.insert_one(add_dict)

except pymongo.errors.ServerSelectionTimeoutError as e:

    client = pymongo.MongoClient(host='localhost', port=27017)
    db = client.info_collect
    collection = db['info']
    if collection.count_documents({'link': url}) < 1:
        collection.insert_one(add_dict)