使用$in查询时无法遍历完整PyMongo游标(CosmosDB MongoDB API场景)
解决CosmosDB MongoDB API游标仅遍历101条数据的问题
这个问题我之前也碰到过,大概率是Cosmos DB的MongoDB API默认的游标批次限制导致的——它默认的初始批次大小是100条,加上游标初始化时拿到的第一条,刚好是101条。如果迭代时没有自动触发下一批数据的获取,就会出现遍历到101条就停止的情况。下面给你几个可行的解决方案:
1. 开启游标无超时并手动关闭
有时候游标会因为闲置超时导致无法获取后续批次,你可以在查询时添加no_cursor_timeout=True参数,同时记得最后手动关闭游标避免资源泄漏:
# 构造查询时开启无超时 items = item_collection.find( filter={'store_id': 151, 'dept_id': {'$in': [17, 19]}}, no_cursor_timeout=True ) tally = 0 try: for item in items: tally += 1 print(f'Cursor total: {items.count()} --- Tally: {tally}') finally: # 手动关闭游标释放资源 items.close()
2. 显式设置更大的批次大小
你可以通过batch_size()方法指定更大的批次,让游标一次性获取更多数据,减少批次请求的次数:
# 设置批次大小为500(根据你的需求调整) items = item_collection.find( filter={'store_id': 151, 'dept_id': {'$in': [17, 19]}} ).batch_size(500) tally = 0 for item in items: tally += 1 print(f'Cursor total: {items.count()} --- Tally: {tally}')
3. 使用更准确的文档计数方式
注意:PyMongo 3.7及以上版本中,游标上的count()方法已经被标记为过时,建议直接用集合的count_documents()来获取准确的总文档数,避免游标计数的误差:
# 获取准确的总文档数 total_count = item_collection.count_documents( filter={'store_id': 151, 'dept_id': {'$in': [17, 19]}} ) items = item_collection.find( filter={'store_id': 151, 'dept_id': {'$in': [17, 19]}} ).batch_size(500) tally = 0 for item in items: tally += 1 print(f'Total documents: {total_count} --- Tally: {tally}')
另外,你也可以检查一下Cosmos DB的配置,确认有没有设置全局的查询结果限制,不过一般默认是没有的。按照上面的方法调整后,应该就能遍历到所有符合条件的数据了。
内容的提问来源于stack exchange,提问作者providence
相关产品推荐
相关产品推荐

