对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

从游标访问数据

在本指南中,您可以学习如何使用 Ruby 驱动程序通过游标访问数据。

游标是一种以可迭代批处理方式返回读取操作结果的机制。由于游标在任何给定时间仅保存文档的子集,因此游标可减少内存消耗和驱动程序发送到服务器的请求数量。

您无法直接从应用程序代码访问权限Mongo::Cursor 类。当您使用Ruby驱动程序执行读取操作时,驱动程序会返回一个表示查询的Mongo::Collection::View对象。从 Collection::View对象请求查询结果后,驱动程序会在内部将这些结果存储在 Cursor对象中。然后,Collection::View 会公开由 Cursor 类支持的 Enumerable 接口,您可以从该接口访问权限结果。

The examples in this guide use the restaurants collection in the sample_restaurants database from the Atlas sample datasets. To access this collection from your Ruby application, create a Mongo::Client object that connects to an Atlas cluster and assign the following values to your database and collection variables:

database = client.use('sample_restaurants')
collection = database[:restaurants]

要学习如何创建免费的MongoDB Atlas 集群并加载示例数据集,请参阅MongoDB 入门指南。

要遍历游标的内容,请对读取操作返回的 Mongo::Collection::View对象调用 each 方法。这指示驱动程序执行操作并返回存储在 Mongo::Cursor 中的每个结果。

以下示例使用 find 方法检索name字段值为 "Dunkin' Donuts" 的所有文档。然后打印游标中存储的每个文档:

cursor = collection.find(name: "Dunkin' Donuts")
cursor.each do |doc|
puts doc
end

要从游标单独检索文档,请对读取操作返回的 Mongo::Collection::View对象调用 first 方法。

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

cursor = collection.find(name: "Dunkin' Donuts")
first_doc = cursor.first
puts first_doc

警告

If the number and size of documents returned by your query exceeds available application memory, your program will crash. If you expect a large result set, access your cursor iteratively.

要从游标检索所有文档,请对其相应的 Mongo::Collection::View对象使用 to_a 方法,将游标转换为大量。

以下示例调用 to_a 方法将游标结果存储在大量中:

cursor = collection.find(name: "Dunkin' Donuts")
array_results = cursor.to_a

When querying on a capped collection, you can use a tailable cursor that remains open after the client exhausts the results in a cursor. To create a tailable cursor, pass the cursor_type option to the find method. Set this option to :tailable.

示例,您可以创建一个名为 vegetables 的固定大小集合,如以下代码所示:

db = client.use('db')
collection = db[:vegetables, capped: true, size: 1024 * 1024]
collection.create
vegetables = [
{ name: 'cauliflower' },
{ name: 'zucchini' }
]
collection.insert_many(vegetables)

然后,可以使用以下代码检索vegetables集合中的所有文档,并将结果存储在可追加游标中。游标耗尽后,它将保持打开状态,直到检索到三个文档:

cursor = collection.find({}, cursor_type: :tailable)
docs_found = 0
cursor.each do |doc|
puts doc
docs_found += 1
break if docs_found >= 3
end

如果将另一个文档插入到 vegetables集合中,前面的代码将打印新文档,而不会从游标中检索更多结果。

To learn more about tailable cursors, see Tailable Cursors in the MongoDB Server manual.

要学习;了解有关本指南中讨论的任何函数的更多信息,请参阅以下API文档: