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






