cursor.isExhausted()

  • cursor.isExhausted()

mongo Shell Method

This page documents the mongo shell method, and doesnot refer to the MongoDB Node.js driver (or any other driver)method. For corresponding MongoDB driver API, refer to your specificMongoDB driver documentation instead.

Returns:Boolean.

cursor.isExhausted() returns true if the cursoris closed and there are no remaining objects in the batch.

Use isExhausted() to support iterating cursorsthat remain open even if there are no documents remaining in thecurrent batch, such as tailable orchange stream cursors.

Example

Consider the following while loop iterating through updates toa change stream cursor:

  1. watchCursor = db.collection.watch();
  2.  
  3. while (watchCursor.hasNext()) {
  4. watchCursor.next();
  5. }

A change stream cursor can return an empty batch if no new data changeshave occured within a set period of time. This causes the while loopto exit prematurely as cursor.hasNext() returns falsewhen it detects the empty batch. However, the change stream cursoris still open and able to return more documents in the future.

Use cursor.isExhausted() to ensure the while loop only exitswhen the cursor is closed and there are no documents remaining in thebatch:

  1. watchCursor = db.collection.watch();
  2.  
  3. while (!watchCursor.isExhausted()) {
  4. if (watchCursor.hasNext()){
  5. watchCursor.next();
  6. }
  7. }