A cursor points to the results of a query. Cursors let you iterate over database results one batch at a time.
Use Cases
The find() and aggregate() methods return a cursor with a batch
of results. Iterate the cursor manually or use toArray()
to access documents. For more information, see
Iterate a Cursor in mongosh.
For capped collections, use a tailable cursor to retrieve documents as they are inserted. For more information, see Tailable Cursors.
Behavior
MongoDB closes cursors created within a client session when:
The client exhausts the cursor.
You manually close the cursor.
You manually terminate the session.
The session times out.
cursorTimeoutMillis sets the timeout for idle cursors
(default: 10 minutes). MongoDB closes idle cursors outside sessions
after this time. Returning a batch extends the timeout. Use
killCursors to close cursors manually.
localLogicalSessionTimeoutMinutes sets the session timeout
(default: 30 minutes). Use refreshSessions to extend a
session and killSessions to end it.
Drivers and mongosh create implicit sessions for cursors
opened outside explicit sessions.
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
Starting in MongoDB 7.2, aggregation pipeline queries that attempt to use non-existent databases on mongos deployments return validation errors.
In previous versions, these aggregation queries return empty cursors.
Get Started
Details
find and aggregate operations execute until
they fill a batch. The query then pauses. This
paused query is a cursor, identified by a cursor ID.
The database returns the batch and cursor ID. Drivers and mongosh
store this in a client-side cursor. If more documents exist, the cursor
retrieves the next batch via getMore. Use
cursor.objsLeftInBatch() to check remaining batch results and
cursor.hasNext() to check for more results.
Cursor Batches
Cursors return results in batches, limited by the 16 MiB maximum
BSON document size. Use
cursor.batchSize() to set the document limit. find() and
aggregate() default to a batch size of 101. Subsequent
getMore operations have no default limit, only the 16 MiB
message size.
Sorting
Queries with a sort operation without an index must load all documents into memory before returning results.
Cursor Information
db.serverStatus() returns cursor metrics in the
metrics.cursor field. See metrics.cursor.