OpenQuizz
Une application de gestion des contenus pédagogiques
Cursor Class Reference
Inheritance diagram for Cursor:
Collaboration diagram for Cursor:

Public Member Functions

def __init__ (self, collection, filter=None, projection=None, skip=0, limit=0, no_cursor_timeout=False, cursor_type=CursorType.NON_TAILABLE, sort=None, allow_partial_results=False, oplog_replay=False, modifiers=None, batch_size=0, manipulate=True, collation=None, hint=None, max_scan=None, max_time_ms=None, max=None, min=None, return_key=False, show_record_id=False, snapshot=False, comment=None, session=None, allow_disk_use=None)
 
def collection (self)
 
def retrieved (self)
 
def __del__ (self)
 
def rewind (self)
 
def clone (self)
 
def close (self)
 
def add_option (self, mask)
 
def remove_option (self, mask)
 
def allow_disk_use (self, allow_disk_use)
 
def limit (self, limit)
 
def batch_size (self, batch_size)
 
def skip (self, skip)
 
def max_time_ms (self, max_time_ms)
 
def max_await_time_ms (self, max_await_time_ms)
 
def __getitem__ (self, index)
 
def max_scan (self, max_scan)
 
def max (self, spec)
 
def min (self, spec)
 
def sort (self, key_or_list, direction=None)
 
def count (self, with_limit_and_skip=False)
 
def distinct (self, key)
 
def explain (self)
 
def hint (self, index)
 
def comment (self, comment)
 
def where (self, code)
 
def collation (self, collation)
 
def alive (self)
 
def cursor_id (self)
 
def address (self)
 
def session (self)
 
def __iter__ (self)
 
def next (self)
 
def __enter__ (self)
 
def __exit__ (self, exc_type, exc_val, exc_tb)
 
def __copy__ (self)
 
def __deepcopy__ (self, memo)
 

Detailed Description

A cursor / iterator over Mongo query results.

Constructor & Destructor Documentation

◆ __init__()

def __init__ (   self,
  collection,
  filter = None,
  projection = None,
  skip = 0,
  limit = 0,
  no_cursor_timeout = False,
  cursor_type = CursorType.NON_TAILABLE,
  sort = None,
  allow_partial_results = False,
  oplog_replay = False,
  modifiers = None,
  batch_size = 0,
  manipulate = True,
  collation = None,
  hint = None,
  max_scan = None,
  max_time_ms = None,
  max = None,
  min = None,
  return_key = False,
  show_record_id = False,
  snapshot = False,
  comment = None,
  session = None,
  allow_disk_use = None 
)
Create a new cursor.

Should not be called directly by application developers - see
:meth:`~pymongo.collection.Collection.find` instead.

.. mongodoc:: cursors

◆ __del__()

def __del__ (   self)

Member Function Documentation

◆ __copy__()

def __copy__ (   self)
Support function for `copy.copy()`.

.. versionadded:: 2.4

◆ __deepcopy__()

def __deepcopy__ (   self,
  memo 
)
Support function for `copy.deepcopy()`.

.. versionadded:: 2.4

◆ __enter__()

def __enter__ (   self)

◆ __exit__()

def __exit__ (   self,
  exc_type,
  exc_val,
  exc_tb 
)

◆ __getitem__()

def __getitem__ (   self,
  index 
)
Get a single document or a slice of documents from this cursor.

Raises :class:`~pymongo.errors.InvalidOperation` if this
cursor has already been used.

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

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

An :class:`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
:class:`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

Reimplemented in RawBatchCursor.

◆ __iter__()

def __iter__ (   self)

◆ add_option()

def add_option (   self,
  mask 
)
Set arbitrary query flags using a bitmask.

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

◆ address()

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

.. versionchanged:: 3.0
   Renamed from "conn_id".

◆ alive()

def alive (   self)
Does this cursor have the potential to return more data?

This is mostly useful with `tailable cursors
<http://www.mongodb.org/display/DOCS/Tailable+Cursors>`_
since they will stop iterating even though they *may* return more
results in the future.

With regular cursors, simply use a for loop instead of :attr:`alive`::

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

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

◆ allow_disk_use()

def allow_disk_use (   self,
  allow_disk_use 
)
Specifies whether MongoDB can use temporary disk files while
processing a blocking sort operation.

Raises :exc:`TypeError` if `allow_disk_use` is not a boolean.

.. note:: `allow_disk_use` requires server version **>= 4.4**

:Parameters:
  - `allow_disk_use`: if True, MongoDB may use temporary
    disk files to store data exceeding the system memory limit while
    processing a blocking sort operation.

.. versionadded:: 3.11

◆ batch_size()

def batch_size (   self,
  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 :exc:`TypeError` if `batch_size` is not an integer.
Raises :exc:`ValueError` if `batch_size` is less than ``0``.
Raises :exc:`~pymongo.errors.InvalidOperation` if this
:class:`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.

◆ clone()

def clone (   self)
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()

def close (   self)
Explicitly close / kill this cursor.

◆ collation()

def collation (   self,
  collation 
)
Adds a :class:`~pymongo.collation.Collation` to this query.

This option is only supported on MongoDB 3.4 and above.

Raises :exc:`TypeError` if `collation` is not an instance of
:class:`~pymongo.collation.Collation` or a ``dict``. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor` has
already been used. Only the last collation applied to this cursor has
any effect.

:Parameters:
  - `collation`: An instance of :class:`~pymongo.collation.Collation`.

◆ collection()

def collection (   self)
The :class:`~pymongo.collection.Collection` that this
:class:`Cursor` is iterating.

◆ comment()

def comment (   self,
  comment 
)
Adds a 'comment' to the cursor.

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

:Parameters:
  - `comment`: A string to attach to the query to help interpret and
    trace the operation in the server logs and in profile data.

.. versionadded:: 2.7

◆ count()

def count (   self,
  with_limit_and_skip = False 
)
**DEPRECATED** - Get the size of the results set for this query.

The :meth:`count` method is deprecated and **not** supported in a
transaction. Please use
:meth:`~pymongo.collection.Collection.count_documents` instead.

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

When used with MongoDB >= 2.6, :meth:`~count` uses any :meth:`~hint`
applied to the query. In the following example the hint is passed to
the count command:

  collection.find({'field': 'value'}).hint('field_1').count()

The :meth:`count` method obeys the
:attr:`~pymongo.collection.Collection.read_preference` of the
:class:`~pymongo.collection.Collection` instance on which
:meth:`~pymongo.collection.Collection.find` was called.

:Parameters:
  - `with_limit_and_skip` (optional): take any :meth:`limit` or
    :meth:`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-**

.. versionchanged:: 3.7
   Deprecated.

.. versionchanged:: 2.8
   The :meth:`~count` method now supports :meth:`~hint`.

◆ cursor_id()

def cursor_id (   self)
Returns the id of the cursor

Useful if you need to manage cursor ids and want to handle killing
cursors manually using
:meth:`~pymongo.mongo_client.MongoClient.kill_cursors`

.. versionadded:: 2.2

◆ distinct()

def distinct (   self,
  key 
)
Get a list of distinct values for `key` among all documents
in the result set of this query.

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

The :meth:`distinct` method obeys the
:attr:`~pymongo.collection.Collection.read_preference` of the
:class:`~pymongo.collection.Collection` instance on which
:meth:`~pymongo.collection.Collection.find` was called.

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

.. seealso:: :meth:`pymongo.collection.Collection.distinct`

◆ explain()

def explain (   self)
Returns an explain plan record for this cursor.

.. note:: Starting with MongoDB 3.2 :meth:`explain` uses
  the default verbosity mode of the `explain command
  <https://docs.mongodb.com/manual/reference/command/explain/>`_,
  ``allPlansExecution``. To use a different verbosity use
  :meth:`~pymongo.database.Database.command` to run the explain
  command directly.

.. mongodoc:: explain

Reimplemented in RawBatchCursor.

◆ hint()

def hint (   self,
  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. Raises :class:`~pymongo.errors.OperationFailure` if the
provided hint requires an index that does not exist on this collection,
and raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used.

`index` should be an index as passed to
:meth:`~pymongo.collection.Collection.create_index`
(e.g. ``[('field', ASCENDING)]``) or the name of the index.
If `index` is ``None`` any existing hint for this query is
cleared. The last hint applied to this cursor takes precedence
over all others.

:Parameters:
  - `index`: index to hint on (as an index specifier)

.. versionchanged:: 2.8
   The :meth:`~hint` method accepts the name of the index.

◆ limit()

def limit (   self,
  limit 
)
Limits the number of results to be returned by this cursor.

Raises :exc:`TypeError` if `limit` is not an integer. Raises
:exc:`~pymongo.errors.InvalidOperation` if this :class:`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

.. mongodoc:: limit

◆ max()

def max (   self,
  spec 
)
Adds ``max`` operator that specifies upper bound for specific index.

When using ``max``, :meth:`~hint` should also be configured to ensure
the query uses the expected index and starting in MongoDB 4.2
:meth:`~hint` will be required.

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

.. versionchanged:: 3.8
   Deprecated cursors that use ``max`` without a :meth:`~hint`.

.. versionadded:: 2.7

◆ max_await_time_ms()

def max_await_time_ms (   self,
  max_await_time_ms 
)
Specifies a time limit for a getMore operation on a
:attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` cursor. For all other
types of cursor max_await_time_ms is ignored.

Raises :exc:`TypeError` if `max_await_time_ms` is not an integer or
``None``. Raises :exc:`~pymongo.errors.InvalidOperation` if this
:class:`Cursor` has already been used.

.. note:: `max_await_time_ms` requires server version **>= 3.2**

:Parameters:
  - `max_await_time_ms`: the time limit after which the operation is
    aborted

.. versionadded:: 3.2

◆ max_scan()

def max_scan (   self,
  max_scan 
)
**DEPRECATED** - Limit the number of documents to scan when
performing the query.

Raises :class:`~pymongo.errors.InvalidOperation` if this
cursor has already been used. Only the last :meth:`max_scan`
applied to this cursor has any effect.

:Parameters:
  - `max_scan`: the maximum number of documents to scan

.. versionchanged:: 3.7
  Deprecated :meth:`max_scan`. Support for this option is deprecated in
  MongoDB 4.0. Use :meth:`max_time_ms` instead to limit server side
  execution time.

◆ max_time_ms()

def max_time_ms (   self,
  max_time_ms 
)
Specifies a time limit for a query operation. If the specified
time is exceeded, the operation will be aborted and
:exc:`~pymongo.errors.ExecutionTimeout` is raised. If `max_time_ms`
is ``None`` no limit is applied.

Raises :exc:`TypeError` if `max_time_ms` is not an integer or ``None``.
Raises :exc:`~pymongo.errors.InvalidOperation` if this :class:`Cursor`
has already been used.

:Parameters:
  - `max_time_ms`: the time limit after which the operation is aborted

◆ min()

def min (   self,
  spec 
)
Adds ``min`` operator that specifies lower bound for specific index.

When using ``min``, :meth:`~hint` should also be configured to ensure
the query uses the expected index and starting in MongoDB 4.2
:meth:`~hint` will be required.

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

.. versionchanged:: 3.8
   Deprecated cursors that use ``min`` without a :meth:`~hint`.

.. versionadded:: 2.7

◆ next()

def next (   self)
Advance the cursor.

Reimplemented in GridOutCursor.

◆ remove_option()

def remove_option (   self,
  mask 
)
Unset arbitrary query flags using a bitmask.

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

◆ retrieved()

def retrieved (   self)
The number of documents retrieved so far.

◆ rewind()

def rewind (   self)
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.

◆ session()

def session (   self)
The cursor's :class:`~pymongo.client_session.ClientSession`, or None.

.. versionadded:: 3.6

◆ skip()

def skip (   self,
  skip 
)
Skips the first `skip` results of this cursor.

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

:Parameters:
  - `skip`: the number of results to skip

◆ sort()

def sort (   self,
  key_or_list,
  direction = None 
)
Sorts this cursor's results.

Pass a field name and a direction, either
:data:`~pymongo.ASCENDING` or :data:`~pymongo.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)

For more advanced text search functionality, see MongoDB's
`Atlas Search <https://docs.atlas.mongodb.com/atlas-search/>`_.

Raises :class:`~pymongo.errors.InvalidOperation` if this cursor has
already been used. Only the last :meth:`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 :data:`~pymongo.ASCENDING` is assumed

◆ where()

def where (   self,
  code 
)
Adds a `$where`_ clause to this query.

The `code` argument must be an instance of :class:`basestring`
(:class:`str` in python 3) or :class:`~bson.code.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. For example::

    # Find all documents where field "a" is less than "b" plus "c".
    for doc in db.test.find().where('this.a < (this.b + this.c)'):
print(doc)

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

.. note:: MongoDB 4.4 drops support for :class:`~bson.code.Code`
  with scope variables. Consider using `$expr`_ instead.

:Parameters:
  - `code`: JavaScript expression to use as a filter

.. _$expr: https://docs.mongodb.com/manual/reference/operator/query/expr/
.. _$where: https://docs.mongodb.com/manual/reference/operator/query/where/

The documentation for this class was generated from the following file: