Overview
在本指南中,您可以了解如何使用 PyMongo 从游标访问数据。
游标是一种以可迭代批处理方式返回读取操作结果的机制。 由于游标在任何给定时间仅保存文档的子集,因此游标可减少内存消耗和网络带宽使用量。
每当 PyMongo 执行返回多个文档的读取操作时,它都会自动在游标中返回这些文档。
样本数据
本指南中的示例使用Atlas示例数据集中的sample_restaurants.restaurants集合。 要学习;了解如何创建免费的MongoDB Atlas 群集并加载示例数据集,请参阅PyMongo入门教程。
以迭代方式访问游标内容
要遍历游标的内容,请使用 for 循环,如以下示例所示。选择Synchronous或Asynchronous标签页以查看相应的代码:
results = collection.find()
for document in results: print(document)results = collection.find()
async for document in results: print(document)分别检索文档
通过调用next()方法从游标单独检索文档。
以下示例查找集合中 name 值为 "Dunkin' Donuts" 的所有文档。然后,它通过调用 next() 方法来打印游标中的第一个文档。选择Synchronous或Asynchronous标签页以查看相应的代码:
results = collection.find({ "name": "Dunkin' Donuts" })
print(results.next())results = collection.find({ "name": "Dunkin' Donuts" })
print(await results.next())检索所有文档
警告
如果查询返回的文档数量和大小超过可用的应用程序内存,程序就会崩溃。 如果需要大型结果集,请以迭代方式访问游标。
要从游标检索所有文档,请将游标转换为 list,如以下示例所示。选择Synchronous或Asynchronous标签页以查看相应的代码:
results = collection.find({ "name": "Dunkin' Donuts" })
all_results = list(results)
for document in all_results: print(document)results = collection.find({ "name": "Dunkin' Donuts" })
all_results = await to_list(results)
for document in all_results: print(document)关闭游标
默认下,当客户端用完游标中的所有结果时, MongoDB会关闭游标。要显式关闭游标,请调用 close() 方法,如以下示例所示。选择Synchronous或Asynchronous标签页以查看相应的代码:
results = collection.find()
...
results.close()results = collection.find()
...
await results.close()您还可以在 with声明中实例化游标,如以下示例所示。当区块终止时, PyMongo会自动关闭游标。
with collection.find() as cursor: for document in cursor: print(document)可追加游标
对固定大小固定大小集合进行查询时,可以使用可可追加游标,该游标在客户端用完游标中的结果后仍保持打开状态。 要使用固定大小固定大小集合创建可可追加游标,请在find()方法的cursor_type选项中指定CursorType.TAILABLE_AWAIT 。
以下示例使用可追加游标来跟踪副本集成员的oplog 。选择 Synchronous 或 Asynchronous标签页,查看相应的代码:
oplog = client.local.oplog.rsfirst = oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()print(first)ts = first['ts']
while True: cursor = oplog.find({'ts': {'$gt': ts}}, cursor_type=pymongo.CursorType.TAILABLE_AWAIT) while cursor.alive: for doc in cursor: ts = doc['ts'] print(doc)
# You end up here if the find() method returns no documents, or if # no new documents are added to the collection for more than 1 second. time.sleep(1)oplog = client.local.oplog.rsfirst = await oplog.find().sort('$natural', pymongo.ASCENDING).limit(-1).next()print(first)ts = first['ts']
while True: cursor = oplog.find({'ts': {'$gt': ts}}, cursor_type=pymongo.CursorType.TAILABLE_AWAIT) while cursor.alive: async for doc in cursor: ts = doc['ts'] print(doc)
# You end up here if the find() method returns no documents, or if # no new documents are added to the collection for more than 1 second. await asyncio.sleep(1)要了解有关可追加游标的更多信息,请参阅 MongoDB Server 手册中的可追加游标指南。
故障排除
“Cursor”对象没有“_Cursor__killed”属性
如果您向Cursor构造函数提供无效参数,PyMongo v 3.8或更早版本会引发TypeError和AttributeError 。 AttributeError无关紧要,但TypeError包含调试信息,如以下示例所示:
Exception ignored in: <function Cursor.__del__ at 0x1048129d8>...AttributeError: 'Cursor' object has no attribute '_Cursor__killed'...TypeError: __init__() got an unexpected keyword argument '<argument>'要解决此问题,请确保提供正确的关键字参数。 您还可以升级到 PyMongo v 3.9或更高版本,这将消除不相关错误。
"CursorNotFound 游标 id not valid at 服务器"
MongoDB 中的游标如果长时间打开且未对其执行任何操作,则可能会在服务器上超时。 当您尝试遍历游标时,这可能会导致CursorNotFound异常。