Database Manual / CRUD Operations / CRUD Concepts

Cursors游标

A cursor is a pointer to the results of a query. Cursors allow you to iterate over database results one batch at a time.游标是指向查询结果的游标。游标允许您一次迭代一批数据库结果。

Use Cases用例

When you execute find() and aggregate() methods using mongosh or a driver, they return a cursor containing a batch of results. 当你使用mongosh驱动程序执行find()aggregate()方法时,它们会返回一个包含一批结果的游标。You can access the resulting documents by manually iterating the cursor or using the toArray() method. 您可以通过手动迭代游标或使用toArray()方法来访问结果文档。For more information, see Iterate a Cursor in mongosh.有关更多信息,请参阅mongosh中迭代游标

If you are accessing a capped collection, you can use a tailable cursor that retrieves new documents as they are inserted into the collection. 如果您正在访问一个封顶集合,您可以使用一个可伸缩的游标,在新文档插入集合时检索它们。For more information, see Tailable Cursors.有关更多信息,请参阅可尾随游标

Behavior行为

Cursors created within a client session are closed in the following scenarios:在以下情况下,在客户端会话中创建的游标将关闭:

  • The client exhausts the cursor.客户端耗尽游标。
  • A user manually closes the cursor.用户手动关闭游标。
  • A user manually terminates the session.用户手动终止会话。
  • The session times out.会话超时。

The cursorTimeoutMillis parameter specifies the timeout for idle cursors and has a default value of 10 minutes. cursorTimeoutMillis参数指定空闲游标的超时时间,默认值为10分钟。MongoDB times out idle cursors created outside of sessions after this threshold. MongoDB extends the cursor timeout each time the cursor returns a new batch. 在此阈值之后,MongoDB会超时在会话外创建的空闲游标。每次游标返回新批时,MongoDB都会延长游标超时时间。To manually close a cursor, use killCursors.要手动关闭游标,请使用killCursors

The server session timeout is specified by the localLogicalSessionTimeoutMinutes parameter and has a default value of 30 minutes. 服务器会话超时由localLogicalSessionTimeoutMinutes参数指定,默认值为30分钟。To extend a session beyond 30 minutes, use refreshSessions. 要将会话延长到30分钟以上,请使用refreshSessionsTo manually terminate a session, use killSessions.要手动终止会话,请使用killSessions

If a cursor is opened outside of a session, MongoDB drivers and mongosh create an implicit session and associate it with the operation.如果游标在会话之外打开,MongoDB驱动程序和mongosh会创建一个隐式会话并将其与操作相关联。

Concurrent Updates While Using a Cursor使用游标时的并发更新

As a cursor returns documents, other operations may run in the background and affect the results, depending on the read concern level. For details, see Read Isolation, Consistency, and Recency.当游标返回文档时,其他操作可能会在后台运行并影响结果,具体取决于读取关注级别。有关详细信息,请参阅读取隔离、一致性和最近性

Cursor Results for Non-Existent mongos Databases不存在mongos数据库的游标结果

Starting in MongoDB 7.2, aggregation pipeline queries that attempt to use non-existent databases on mongos deployments return validation errors.从MongoDB 7.2开始,试图在mongos部署上使用不存在的数据库的聚合管道查询会返回验证错误。

In previous versions, these aggregation queries return empty cursors.在以前的版本中,这些聚合查询返回空游标。

Get Started开始使用

Details详情

When you run a find or aggregate operation, the database executes a query until it finds enough documents to fill a batch. 当您运行findaggregate操作时,数据库会执行查询,直到找到足够的文档来填充一When a batch is filled, the query pauses. The paused query on the server is referred to as a cursor and the ID associated with the paused query is a cursor ID.当一个批次被填充时,查询会暂停。服务器上的暂停查询称为游标,与暂停查询相关联的ID是游标ID

The database returns the resulting batch and cursor ID to the client. MongoDB drivers and mongosh store this data in a client-side cursor instance. 数据库将生成的批处理和游标ID返回给客户端。MongoDB驱动程序和mongosh将此数据存储在客户端游标实例中。If there are more matching documents when you reach the end of a batch, the client-side cursor automatically retrieves the next batch from the server using getMore. 如果在批处理结束时有更多匹配的文档,则客户端游标会使用getMore自动从服务器检索下一批。To see how many results remain in the current batch, use cursor.objsLeftInBatch(). 要查看当前批中还剩多少结果,请使用cursor.objsLeftInBatch()To check if there are any results remaining in the current batch or on the server, use cursor.hasNext().要检查当前批处理中或服务器上是否还有任何结果,请使用cursor.hasNext()

Cursor Batches游标批次

Cursors return results in batches. The amount of data in a batch must be smaller than the maximum BSON document size (16 MiB). 游标分批返回结果。批处理中的数据量必须小于最大BSON文档大小(16 MiB)。To specify the maximum number of documents allowed in a batch, see cursor.batchSize(). 要指定批处理中允许的最大文档数,请参阅cursor.batchSize()By default, the batch size for find() and aggregate() operations is 101. 默认情况下,find()aggregate()操作的批大小为101Subsequent getMore operations issued against the resulting cursor have no default batch size, so they are limited only by the 16 mebibyte message size.对结果游标发出的后续getMore操作没有默认的批大小,因此它们仅受16兆字节消息大小的限制。

Sorting排序

For queries that include a sort operation without an index, the server must load all the documents in memory to perform the sort before returning any results.对于包含没有索引的排序操作的查询,服务器必须在返回任何结果之前加载内存中的所有文档以执行排序。

Cursor Information游标信息

The db.serverStatus() method returns a document that includes a metrics field. db.serverStatus()方法返回一个包含度量字段的文档。The metrics field contains a metrics.cursor field with detailed cursor information. To learn more, see metrics.cursor.metrics(度量)字段包含一个带有详细游标信息的metrics.cursor(度量游标)字段。要了解更多信息,请参阅metrics.cursor

Learn More了解更多