cursor – Tools for iterating over MongoDB query results — PyMongo 2.7.2 documentation

# `cursor` – Tools for iterating over MongoDB query results

Cursor class to iterate over Mongo query results.

class `pymongo.cursor.` `Cursor`(collection, spec=None, fields=None, skip=0, limit=0, timeout=True, snapshot=False, tailable=False, sort=None, max_scan=None, as_class=None, slave_okay=False, await_data=False, partial=False, manipulate=True, read_preference=ReadPreference.PRIMARY, tag_sets=[{}], secondary_acceptable_latency_ms=None, exhaust=False, network_timeout=None)

  Create a new cursor.

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

  See also

  See general MongoDB documentation

  cursors

  `c[index]`

    See `__getitem__()`.

  `__getitem__`(index)

    Get a single document or a slice of documents from this cursor.

    Raises `InvalidOperation` if this cursor has already been used.

    To get a single document use an integral index, e.g.:

        >>> db.test.find()[50]

    An `IndexError` will be raised if the index is negative or greater than the amount of documents in this cursor. Any limit previously applied to this cursor will be ignored.

    To get a slice of documents use a slice index, e.g.:

        >>> db.test.find()[20:25]

    This will return this cursor with a limit of `5` and skip of `20` applied. Using a slice index will override any prior limits or skips applied to this cursor (including those applied through previous calls to this method). Raises `IndexError` when the slice has a step, a negative start value, or a stop value less than or equal to the start value.

    Parameters: | index: An integer or slice index to be applied to this cursor

  `add_option`(mask)

    Set arbitrary query flags using a bitmask.

    To set the tailable flag: cursor.add_option(2)

  `alive`

    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.

    New in version 1.5.

  `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`. Raises `InvalidOperation` if this `Cursor` has already been used. The last batch_size applied to this cursor takes precedence.

    Parameters: | batch_size: The size of each batch of results requested.

    New in version 1.9.

  `clone`()

    Get a clone of this cursor.

    Returns a new Cursor instance with options matching those that have been set on the current instance. The clone will be completely unevaluated, even if the current instance has been partially or completely evaluated.

  `close`()

    Explicitly close / kill this cursor. Required for PyPy, Jython and other Python implementations that don’t use reference counting garbage collection.

  `collection`

    The `Collection` that this `Cursor` is iterating.

    New in version 1.1.

  `comment`(comment)

    Adds a ‘comment’ to the cursor.

    http://docs.mongodb.org/manual/reference/operator/comment/

    Parameters: | comment: A string or document

    New in version 2.7.

  `conn_id`

    The server/client/pool this cursor lives on.

    Could be (host, port), -1, or None depending on what client class executed the initial query or this cursor being advanced at all.

  `count`(with_limit_and_skip=False)

    Get the size of the results set for this query.

    Returns the number of documents in the results set for this query. Does not take `limit()` and `skip()` into account by default - set with_limit_and_skip to `True` if that is the desired behavior. Raises `OperationFailure` on a database error.

    With `MongoReplicaSetClient` or `MasterSlaveConnection`, if read_preference is not `pymongo.read_preferences.ReadPreference.PRIMARY` or `pymongo.read_preferences.ReadPreference.PRIMARY_PREFERRED`, or (deprecated) slave_okay is True, the count command will be sent to a secondary or slave.

    Parameters: | with_limit_and_skip (optional): take any `limit()` or `skip()` that has been applied to this cursor into account when getting the count

    Note

    The with_limit_and_skip parameter requires server version >= 1.1.4-

    Note

    `count` ignores `network_timeout`. For example, the timeout is ignored in the following code:

        collection.find({}, network_timeout=1).count()

    New in version 1.1.1: The with_limit_and_skip parameter. `__len__()` was deprecated in favor of calling `count()` with with_limit_and_skip set to `True`.

  `cursor_id`

    Returns the id of the cursor

    Useful if you need to manage cursor ids and want to handle killing cursors manually using `kill_cursors()`

    New in version 2.2.

  `distinct`(key)

    Get a list of distinct values for key among all documents in the result set of this query.

    Raises `TypeError` if key is not an instance of `basestring` (`str` in python 3).

    With `MongoReplicaSetClient` or `MasterSlaveConnection`, if read_preference is not `pymongo.read_preferences.ReadPreference.PRIMARY` or (deprecated) slave_okay is True the distinct command will be sent to a secondary or slave.

    Parameters: | key: name of key for which we want to get the distinct values

    Note

    Requires server version >= 1.1.3+

    See also

    `pymongo.collection.Collection.distinct()`

    New in version 1.2.

  `explain`()

    Returns an explain plan record for this cursor.

    See also

    See general MongoDB documentation

    explain

  `hint`(index)

    Adds a ‘hint’, telling Mongo the proper index to use for the query.

    Judicious use of hints can greatly improve query performance. When doing a query on multiple fields (at least one of which is indexed) pass the indexed field as a hint to the query. Hinting will not do anything if the corresponding index does not exist. Raises `InvalidOperation` if this cursor has already been used.

    index should be an index as passed to `create_index()` (e.g. `[('field', ASCENDING)]`). If index is `None` any existing hints for this query are cleared. The last hint applied to this cursor takes precedence over all others.

    Parameters: | index: index to hint on (as an index specifier)

  `limit`(limit)

    Limits the number of results to be returned by this cursor.

    Raises `TypeError` if limit is not an integer. Raises `InvalidOperation` if this `Cursor` has already been used. The last limit applied to this cursor takes precedence. A limit of `0` is equivalent to no limit.

    Parameters: | limit: the number of results to return

    See also

    See general MongoDB documentation

    limit

  `max`(spec)

    Adds max operator that specifies upper bound for specific index.

    Parameters: | spec: a list of field, limit pairs specifying the exclusive upper bound for all keys of a specific index in order.

    New in version 2.7.

  `max_scan`(max_scan)

    Limit the number of documents to scan when performing the query.

    Raises `InvalidOperation` if this cursor has already been used. Only the last `max_scan()` applied to this cursor has any effect.

    Parameters: | max_scan: the maximum number of documents to scan

    Note

    Requires server version >= 1.5.1

    New in version 1.7.

  `max_time_ms`(max_time_ms)

    Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and `ExecutionTimeout` is raised. If max_time_ms is `None` no limit is applied.

    Raises `TypeError` if max_time_ms is not an integer or `None`. Raises `InvalidOperation` if this `Cursor` has already been used.

    Parameters: | max_time_ms: the time limit after which the operation is aborted

  `min`(spec)

    Adds min operator that specifies lower bound for specific index.

    Parameters: | spec: a list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order.

    New in version 2.7.

  `remove_option`(mask)

    Unset arbitrary query flags using a bitmask.

    To unset the tailable flag: cursor.remove_option(2)

  `retrieved`

    The number of documents retrieved so far.

  `rewind`()

    Rewind this cursor to its unevaluated state.

    Reset this cursor if it has been partially or completely evaluated. Any options that are present on the cursor will remain in effect. Future iterating performed on this cursor will cause new queries to be sent to the server, even if the resultant data has already been retrieved by this cursor.

  `skip`(skip)

    Skips the first skip results of this cursor.

    Raises `TypeError` if skip is not an integer. Raises `ValueError` if skip is less than `0`. Raises `InvalidOperation` if this `Cursor` has already been used. The last skip applied to this cursor takes precedence.

    Parameters: | skip: the number of results to skip

  `sort`(key_or_list, direction=None)

    Sorts this cursor’s results.

    Pass a field name and a direction, either `ASCENDING` or `DESCENDING`:

        for doc in collection.find().sort('field', pymongo.ASCENDING):
            print(doc)

    To sort by multiple fields, pass a list of (key, direction) pairs:

        for doc in collection.find().sort([
                ('field1', pymongo.ASCENDING),
                ('field2', pymongo.DESCENDING)]):
            print(doc)

    Beginning with MongoDB version 2.6, text search results can be sorted by relevance:

        cursor = db.test.find(
            {'$text': {'$search': 'some words'}},
            {'score': {'$meta': 'textScore'}})

        # Sort by 'score' field.
        cursor.sort([('score', {'$meta': 'textScore'})])

        for doc in cursor:
            print(doc)

    Raises `InvalidOperation` if this cursor has already been used. Only the last `sort()` applied to this cursor has any effect.

    Parameters: | key_or_list: a single key or a list of (key, direction) pairs specifying the keys to sort on direction (optional): only used if key_or_list is a single key, if not given `ASCENDING` is assumed

  `where`(code)

    Adds a $where clause to this query.

    The code argument must be an instance of `basestring` (`str` in python 3) or `Code` containing a JavaScript expression. This expression will be evaluated for each document scanned. Only those documents for which the expression evaluates to true will be returned as results. The keyword this refers to the object currently being scanned.

    Raises `TypeError` if code is not an instance of `basestring` (`str` in python 3). Raises `InvalidOperation` if this `Cursor` has already been used. Only the last call to `where()` applied to a `Cursor` has any effect.

    Parameters: | code: JavaScript expression to use as a filter