# `command_cursor` – Tools for iterating over MongoDB command results

CommandCursor class to iterate over command results.

class pymongo.command_cursor.CommandCursor(collection, cursor_info, address, batch_size=0, max_await_time_ms=None, session=None, comment=None)

  Create a new command cursor.

  Parameters:

    - collection (Collection[_DocumentType])

    - cursor_info (Mapping[str, Any])

    - address (Optional[_Address])

    - batch_size (int)

    - max_await_time_ms (Optional[int])

    - session (Optional[ClientSession])

    - comment (Any)

  property address: Tuple[str, int | None] | None

    The (host, port) of the server used, or None.

    Changed in version 3.0: Renamed from “conn_id”.

  property alive: bool

    Does this cursor have the potential to return more data?

    This is mostly useful with tailable cursors since they will stop iterating even though they may return more results in the future.

    With regular cursors, simply use an asynchronous for loop instead of `alive`:

        async for doc in collection.find():
            print(doc)

    Note

    Even if `alive` is True, `next()` can raise `StopIteration`. `alive` can also be True while iterating a cursor from a failed server. In this case `alive` will return False after `next()` fails to retrieve the next batch of results from the server.

  batch_size(batch_size)

    Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer.

    Note

    batch_size can not override MongoDB’s internal limits on the amount of data it will return to the client in a single batch (i.e if you set batch size to 1,000,000,000, MongoDB will currently only return 4-16MB of results per batch).

    Raises `TypeError` if batch_size is not an integer. Raises `ValueError` if batch_size is less than `0`.

    Parameters:

      batch_size (int) – The size of each batch of results requested.

    Return type:

      CommandCursor[_DocumentType]

  close()

    Explicitly close / kill this cursor.

    Return type:

      None

  property cursor_id: int | None

    Returns the id of the cursor.

    Added in version 2.2.

  next()

    Advance the cursor.

    Return type:

      _DocumentType

  property session: ClientSession | None

    The cursor’s `ClientSession`, or None.

    Added in version 3.6.

  to_list(length=None)

    Converts the contents of this cursor to a list more efficiently than `[doc for doc in cursor]`.

    To use:

        >>> cursor.to_list()

    Or, to read at most n items from the cursor:

        >>> cursor.to_list(n)

    If the cursor is empty or has no more results, an empty list will be returned.

    Added in version 4.9.

    Parameters:

      length (int | None)

    Return type:

      list[_DocumentType]

  try_next()

    Advance the cursor without blocking indefinitely.

    This method returns the next document without waiting indefinitely for data.

    If no document is cached locally then this method runs a single getMore command. If the getMore yields any documents, the next document is returned, otherwise, if the getMore returns no documents (because there is no additional data) then `None` is returned.

    Returns:

      The next document or `None` when no document is available after running a single getMore or when the cursor is closed.

    Return type:

      _DocumentType | None

    Added in version 4.5.

class pymongo.command_cursor.RawBatchCommandCursor(collection, cursor_info, address, batch_size=0, max_await_time_ms=None, session=None, comment=None)

  Create a new cursor / iterator over raw batches of BSON data.

  Should not be called directly by application developers - see `aggregate_raw_batches()` instead.

  See also

  The MongoDB documentation on cursors.

  Parameters:

    - collection (Collection[_DocumentType])

    - cursor_info (Mapping[str, Any])

    - address (Optional[_Address])

    - batch_size (int)

    - max_await_time_ms (Optional[int])

    - session (Optional[ClientSession])

    - comment (Any)

  property address: Tuple[str, int | None] | None

    The (host, port) of the server used, or None.

    Changed in version 3.0: Renamed from “conn_id”.

  property alive: bool

    Does this cursor have the potential to return more data?

    This is mostly useful with tailable cursors since they will stop iterating even though they may return more results in the future.

    With regular cursors, simply use an asynchronous for loop instead of `alive`:

        async for doc in collection.find():
            print(doc)

    Note

    Even if `alive` is True, `next()` can raise `StopIteration`. `alive` can also be True while iterating a cursor from a failed server. In this case `alive` will return False after `next()` fails to retrieve the next batch of results from the server.

  batch_size(batch_size)

    Limits the number of documents returned in one batch. Each batch requires a round trip to the server. It can be adjusted to optimize performance and limit data transfer.

    Note

    batch_size can not override MongoDB’s internal limits on the amount of data it will return to the client in a single batch (i.e if you set batch size to 1,000,000,000, MongoDB will currently only return 4-16MB of results per batch).

    Raises `TypeError` if batch_size is not an integer. Raises `ValueError` if batch_size is less than `0`.

    Parameters:

      batch_size (int) – The size of each batch of results requested.

    Return type:

      CommandCursor[_DocumentType]

  close()

    Explicitly close / kill this cursor.

    Return type:

      None

  property cursor_id: int | None

    Returns the id of the cursor.

    Added in version 2.2.

  next()

    Advance the cursor.

    Return type:

      _DocumentType

  property session: ClientSession | None

    The cursor’s `ClientSession`, or None.

    Added in version 3.6.

  to_list(length=None)

    Converts the contents of this cursor to a list more efficiently than `[doc for doc in cursor]`.

    To use:

        >>> cursor.to_list()

    Or, to read at most n items from the cursor:

        >>> cursor.to_list(n)

    If the cursor is empty or has no more results, an empty list will be returned.

    Added in version 4.9.

    Parameters:

      length (int | None)

    Return type:

      list[_DocumentType]

  try_next()

    Advance the cursor without blocking indefinitely.

    This method returns the next document without waiting indefinitely for data.

    If no document is cached locally then this method runs a single getMore command. If the getMore yields any documents, the next document is returned, otherwise, if the getMore returns no documents (because there is no additional data) then `None` is returned.

    Returns:

      The next document or `None` when no document is available after running a single getMore or when the cursor is closed.

    Return type:

      _DocumentType | None

    Added in version 4.5.