如何在PyMongo中人工触发Cursor Not Found错误?
如何在PyMongo中人工触发Cursor Not Found错误
你的代码没触发预期错误的核心原因是:PyMongo的Cursor对象在开始迭代(比如调用next()或进入for循环)之前,不会向MongoDB服务器发送实际的查询请求。你在time.sleep(9000)时,服务器端还没创建游标,自然不会触发超时机制。
要成功触发错误,需要先让服务器生成游标,再让游标闲置超过超时时间,之后继续遍历剩余结果。以下是两种可行方案:
方案1:利用默认10分钟超时
先读取一个文档触发服务器创建游标,等待超过10分钟后继续遍历:
import time from pymongo import MongoClient client = MongoClient() db = client.test_db coll = db.test_coll # 确保集合中有至少2个文档(需要遍历剩余结果) coll.insert_many([{"scores": 1}, {"scores": 2}, {"scores": 3}]) cursor = coll.find() # 获取第一个文档,触发服务器创建游标 first_doc = next(cursor) print("已读取第一个文档:", first_doc) # 等待超过10分钟(600秒),这里设为601秒确保超时 time.sleep(601) # 继续遍历剩余文档,此时游标已被服务器关闭 try: for row in cursor: print(row['scores']) except Exception as e: print("触发错误:", e)
方案2:手动缩短超时时间(快速测试)
用max_time_ms参数设置游标在服务器端的存活时间,不用等10分钟就能测试:
import time from pymongo import MongoClient client = MongoClient() db = client.test_db coll = db.test_coll coll.insert_many([{"scores": 1}, {"scores": 2}]) # 设置游标仅存活5秒 cursor = coll.find().max_time_ms(5000) next(cursor) # 触发游标创建 # 等待超过5秒 time.sleep(6) try: next(cursor) except Exception as e: print("触发错误:", e)
执行以上代码后,你会看到pymongo.errors.CursorNotFound错误,符合预期。
内容的提问来源于stack exchange,提问作者osas
相关产品推荐
相关产品推荐

