Cursors and time limits

When a result is large it arrives in batches; each query also accepts a time limit.

Go through large results in batches with a cursor and put a time limit on each query with maxTimeMS.

Requirements

  • A connection with a user that has read on the database.

Go through in batches

JavaScript
const cursor = db.orders.find({ status: "paid" }).batchSize(500);
for await (const order of cursor) {
  handle(order);
}

The driver asks for each next batch with getMore to the same node that opened the cursor.

Put a time limit

JavaScript
db.orders.find({ status: "paid" }).maxTimeMS(2000);

Check

A query over the time limit fails with MaxTimeMSExpired (50) and stops keeping the node busy.

Common problems

  • getMore fails with CursorNotFound (43) because the cursor expired, was closed or was asked of another node.

See also