liveBook · Manning

Cursor

As explained in MongoDB 8.0 in Action, Third Edition

A cursor is an object representing an incremental result set from a database query and providing methods for traversing its documents.

A cursor represents the incremental result set from a database query. Rather than loading every matching document immediately, it fetches documents in batches as needed, reducing memory use and network bandwidth. section 4.13 section 4.6

Use cursors according to the required level of control:

  • Run db.routes.find() to obtain a cursor for all matching route documents. section 4.13
  • Iterate automatically when displaying or processing results; mongosh displays up to the first 20 documents and continues when requested. section 4.6
  • Use hasNext() and next() for manual, document-by-document iteration when processing between retrievals requires fine control. section 4.13.1
  • Apply a read-operation time limit with MongoDB 8.0 defaultMaxTimeMS; exceeding the limit terminates the operation with an error. section 4.6

Manual cursor iteration

Define an asynchronous function that creates a routes cursor, checks hasNext(), and logs each document returned by next(). This approach exposes retrieval control while still fetching results incrementally. section 4.13.1

 async function manualIteration() {
  const cursorVariable = db.routes.find()

  // Loop while there are documents available in the cursor
  while (await cursorVariable.hasNext()) {
    // Log each document to the console as it's fetched
    console.log(await cursorVariable.next())
  }
}

// Call the function to perform the iteration
manualIteration()

Inspect the complete mongosh pattern for asynchronous manual iteration with hasNext() and next(). section 4.13.1

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Explains cursor creation, batching, lazy loading, automatic display, manual iteration, and read timeouts without detailing driver internals.
Examples
Uses routes queries, mongosh display behavior, manualIteration(), and a sample_mflix change-stream cursor.
What you can do after
Apply it via mongosh to retrieve query results incrementally, choose manual traversal, and monitor change-stream events.
How it connects
Connects query results with batching, lazy loading, manual iteration, change streams, and resume tokens.

Also explained in

Compare how 7 books explain cursor →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.