Docs 菜单
Docs 主页
/ / /
pymongo
/

从游标访问数据

在此页面上

  • Overview
  • 以迭代方式访问游标内容
  • 分别检索文档
  • 检索所有文档
  • 关闭游标
  • 可追加游标
  • 故障排除

在本指南中,您可以了解如何使用 PyMongo 从游标访问数据。

游标是一种以可迭代批处理方式返回读取操作结果的机制。 由于游标在任何给定时间仅保存文档的子集,因此游标可减少内存消耗和网络带宽使用量。

每当 PyMongo 执行返回多个文档的读取操作时,它都会自动在游标中返回这些文档。

本指南中的示例使用 Atlas 样本数据集中 sample_restaurants.restaurants集合。要了解如何创建免费的 MongoDB Atlas 集群并加载样本数据集,请参阅 PyMongo 入门。

要遍历游标的内容,请使用for循环,如以下示例所示:

results = collection.find()
for document in results:
print(document)

通过调用next()方法从游标单独检索文档。

以下示例查找集合中name值为"Dunkin' Donuts"的所有文档。 然后,它通过调用next()方法来打印游标中的第一个文档。

results = collection.find({ "name": "Dunkin' Donuts" })
print(results.next())
{'_id': ObjectId('...'), 'address': { ... }, 'borough': 'Bronx', 'cuisine': 'Donuts', 'grades': [...], 'name': "Dunkin' Donuts", 'restaurant_id': '40379573'}

警告

如果查询返回的文档数量和大小超过可用的应用程序内存,程序就会崩溃。 如果需要大型结果集,请以迭代方式访问游标。

要从游标检索所有文档,请将游标转换为list ,如以下示例所示:

results = collection.find({ "name": "Dunkin' Donuts" })
all_results = list(results)
for document in all_results:
print(document)

默认情况下,当客户端用完游标中的所有结果时,MongoDB 会关闭游标。 要显式关闭游标,请调用close()方法,如以下示例所示:

results = collection.find()
...
results.close()

对固定大小集合进行查询时,可以使用可追加游标,该游标在客户端用完游标中的结果后仍保持打开状态。要使用固定大小集合创建可追加游标,请在find()方法的cursor_type选项中指定CursorType.TAILABLE_AWAIT

以下示例使用可追加游标来跟踪副本集成员的 oplog:

oplog = client.local.oplog.rs
first = 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)

要了解有关可追加游标的更多信息,请参阅 MongoDB Server 手册中的可追加游标指南

如果您向Cursor构造函数提供无效参数,PyMongo v 3.8或更早版本会引发TypeErrorAttributeErrorAttributeError无关紧要,但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或更高版本,这将消除不相关错误。

MongoDB 中的游标如果长时间打开且未对其执行任何操作,则可能会在服务器上超时。 当您尝试遍历游标时,这可能会导致CursorNotFound异常。

后退

检索不同字段值