
    h                     .   d Z ddlZddlZddlmZ ddlmZ ddlmZ ddl	m
Z
mZmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZmZmZmZ ddlmZmZmZmZm Z  ddl!m"Z" ddddddddZ# G d de$      Z% G d d      Z& G d de$      Z' G d de'      Z(y)z1Cursor class to iterate over Mongo query results.    N)deque)RE_TYPE)Code)	iteritemsinteger_typesstring_type)SON)helpers)validate_booleanvalidate_is_mapping)validate_collation_or_none)ConnectionFailureInvalidOperationNotMasterErrorOperationFailure)_CursorAddress_GetMore_RawBatchGetMore_Query_RawBatchQuery)ConnectionClosedReason                @      )tailable_cursor
slave_okayoplog_replay
no_timeout
await_dataexhaustpartialc                   :    e Zd ZdZ	 ed   Z	 eed   z  Z	 ed   Zy)
CursorTyper   r   r#   r$   N)__name__
__module____qualname__NON_TAILABLE_QUERY_OPTIONSTAILABLETAILABLE_AWAITEXHAUST     Q/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/cursor.pyr'   r'   5   sA    L#/0H | <<N Y'Gr1   r'   c                   "    e Zd ZdZd Zd Zd Zy)_SocketManagerz@Used with exhaust cursors to ensure the socket is returned.
    c                 .    || _         || _        d| _        y NF)sockpool_SocketManager__closed)selfr7   r8   s      r2   __init__z_SocketManager.__init__W   s    		r1   c                 $    | j                          y Ncloser:   s    r2   __del__z_SocketManager.__del__\       

r1   c                     | j                   s<d| _         | j                  j                  | j                         d\  | _        | _        yy)z>Return this instance's socket to the connection pool.
        T)NNN)r9   r8   return_socketr7   r@   s    r2   r?   z_SocketManager.close_   s;     }} DMII##DII.#- DIty r1   N)r(   r)   r*   __doc__r;   rA   r?   r0   r1   r2   r4   r4   T   s    
.r1   r4   c                      e Zd ZdZeZeZdddddej                  ddddddddddddddddddfdZ
ed        Zed        Zd	 Zd
 Zd Zd6dZd Zd7dZd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z d Z!d Z"d8dZ#d7dZ$d  Z%d! Z&d" Z'd# Z(d$ Z)d% Z*d& Z+d' Z,	 d9d(Z-d) Z.d* Z/ed+        Z0ed,        Z1ed-        Z2ed.        Z3d/ Z4d0 Z5e5Z6d1 Z7d2 Z8d3 Z9d4 Z:d8d5Z;y):Cursorz2A cursor / iterator over Mongo query results.
    Nr   FTc                    d| _         d| _        d| _        d| _        |r|| _        d| _        nd| _        d| _        |}|i }t        d|       t        |t              st        d      t        |t              st        d      t        d|       |t        j                  t        j                  t        j                  t        j                  fvrt!        d      t        d	|	       t        d
|
       |(t#        j$                  dt&        d       t        d|       t        |t(              st        d      |dk  rt!        d      |t        d|      }||sddi}t+        j,                  |d      }|| _        || _        || _        || _        || _        || _        |xr |j;                         xs i | _        |xr t+        j>                  |      xs d| _         || _!        d| _"        || _#        || _$        d| _%        || _&        || _'        || _(        tS        |      | _*        || _+        || _,        || _-        || _.        | j_                  |       |t        j                  k(  rI| j.                  j`                  jb                  jd                  rtg        d      |rtg        d      d| _        d| _4        tk               | _6        d| _7        d| _8        |jr                  | _:        d| _;        |jx                  | _=        || _>        |r| xj|                  t~        d   z  c_>        |	r| xj|                  t~        d   z  c_>        |
r| xj|                  t~        d
   z  c_>        |j`                  j                  | _A        |j                  | _B        y)zCreate a new cursor.

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

        .. mongodoc:: cursors
        NFTfilterzskip must be an instance of intz limit must be an instance of intno_cursor_timeoutz!not a valid value for cursor_typeallow_partial_resultsr!   z'the 'modifiers' parameter is deprecatedr   
stacklevel	modifiersbatch_size must be an integerr   batch_size must be >= 0allow_disk_use_id   
projection+Exhaust cursors are not supported by mongos%Can't use limit and exhaust together.r"   r%   )C_Cursor__id_Cursor__exhaust_Cursor__exhaust_mgr_Cursor__killed_Cursor__session_Cursor__explicit_sessionr   
isinstanceint	TypeErrorr   r'   r+   r-   r.   r/   
ValueErrorwarningswarnDeprecationWarningr   r
   _fields_list_to_dict_Cursor__collection_Cursor__spec_Cursor__projection_Cursor__skip_Cursor__limit_Cursor__batch_sizecopy_Cursor__modifiers_index_document_Cursor__ordering_Cursor__max_scan_Cursor__explain_Cursor__comment_Cursor__max_time_ms_Cursor__max_await_time_ms_Cursor__max_Cursor__min_Cursor__manipulater   _Cursor__collation_Cursor__return_key_Cursor__show_record_id_Cursor__allow_disk_use_Cursor__snapshot_Cursor__set_hintdatabaseclient	is_mongosr   _Cursor__emptyr   _Cursor__data_Cursor__address_Cursor__retrievedcodec_options_Cursor__codec_options_Cursor__read_preferenceread_concern_Cursor__read_concern_Cursor__query_flagsr,   name_Cursor__dbname_Cursor__collname)r:   
collectionrI   rT   skiplimitrJ   cursor_typesortrK   r!   rN   
batch_size
manipulate	collationhintmax_scanmax_time_msmaxmin
return_keyshow_record_idsnapshotcommentsessionrQ   specs                              r2   r;   zCursor.__init__n   sL   $ 	!$DN&*D#!DN&+D#<DHd+$$=>>%%>??,.?@z66
8K8K)88*:L:LN N@AA02GH6 MMC,<Y7*m4;<<>677%-.>ON!#QZ
 55j,OJ&&&$9)9?R@7#:#:4#@HD" (#' 

&5i@& . ." *,,,  ))00::& (A B B&'NOO!DN g)77!%(55(.">> .";;."@@ #++00$//r1   c                     | j                   S )zdThe :class:`~pymongo.collection.Collection` that this
        :class:`Cursor` is iterating.
        )re   r@   s    r2   r   zCursor.collection   s    
    r1   c                     | j                   S )z2The number of documents retrieved so far.
        )r   r@   s    r2   	retrievedzCursor.retrieved   s     r1   c                 $    | j                          y r=   _Cursor__dier@   s    r2   rA   zCursor.__del__   rB   r1   c                 \    t               | _        d| _        d| _        d| _        d| _        | S )a  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.
        Nr   F)r   r   rW   r   r   rZ   r@   s    r2   rewindzCursor.rewind   s/     g	r1   c                 $    | j                  d      S )a  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.
        T_cloner@   s    r2   clonezCursor.clone
  s     {{4  r1   c                 ,   |s9| j                   r| j                  | j                        }n| j                  d      }dt        fdt	        | j
                        D              }|r| j                  |      }|j
                  j                  |       |S )zInternal clone helper.N)r   rT   r   r   r   max_await_time_msr   r   r   orderingexplainr   r   r   r   query_flagsrN   r   emptyr   r   rQ   r   r$   c              3   \   K   | ]#  \  }}|j                  d       r|dd v r||f % yw)	_Cursor__	   N)
startswith).0kvvalues_to_clones      r2   	<genexpr>z Cursor._clone.<locals>.<genexpr>#  s;      Otq!||K0QqrUo5M F Os   ),)r\   _clone_baser[   dictr   __dict__	_deepcopyupdate)r:   deepcopybasedatar   s       @r2   r   zCursor._clone  s    &&''7''-2  Oy'? O O>>$'DT"r1   c                 <    | j                  | j                  |      S )zJCreates an empty Cursor object for information to be copied into.
        r   )	__class__re   )r:   r   s     r2   r   zCursor._clone_base*  s     ~~d//~AAr1   c                 6   	 | j                   }d| _         | j                  r|s| j                  r@| j                  r4| j                  j
                  j                  t        j                         nt        | j                  | j                  j                        }|rG| j                  j                  j                  j                  | j                  || j                          n:| j                  j                  j                  j#                  | j                  |       | j                  r&| j                  r| j                  j%                          | j                   r1| j&                  s$| j                   j)                  |       d| _        yyy# t        $ r Y yw xY w)zCloses this cursor.
        NTr   )lock)rZ   AttributeErrorrW   rX   rY   r7   close_socketr   ERRORr   r   re   	full_namer}   r~   _close_cursor_nowr[   _close_cursorr?   r\   _end_session)r:   synchronousalready_killedaddresss       r2   __diezCursor.__die/  sC   	!]]N
 99^~~$"4"4 ""''44*002 )NND$5$5$?$?A%%..55GG		7DNN H D %%..55CC		7,>>d00$$&>>$"9"9NN''['9!DN #:>1  		s   F 	FFc                 &    | j                  d       y)z-Explicitly close / kill this cursor.
        TNr   r@   s    r2   r?   zCursor.closeP  s     	

4r1   c                     | j                   j                         }| j                  r| j                  |d<   | j                  rd|d<   | j                  r| j                  |d<   | j
                  r| j
                  |d<   | j                  r| j                  |d<   | j                  | j                  |d<   | j                  r| j                  |d<   | j                  r| j                  |d	<   | j                  r| j                  |d
<   | j                  r| j                  |d<   | j                  r| j                  |d<   |rZ| j                  j                         }d|vrt        d|fg      }t        |t              st        |      }|j!                  |       |S d| j                  v rPt#        | j                        dk(  s!t%        t'        | j                              dk(  rt        d| j                  i      S | j                  S )z)Get the spec to use for a query.
        z$orderbyTz$explainz$hintz$commentz$maxScanz
$maxTimeMSz$maxz$minz
$returnKeyz$showDiskLocz	$snapshotz$queryqueryrS   )rl   rk   rn   rp   _Cursor__hintrq   ro   rr   rt   ru   rx   ry   r{   rf   r	   r]   r   lennextiter)r:   	operatorsr   s      r2   __query_speczCursor.__query_specU  s    $$))+	??$(OOIj!>>$(Ij!;;!%Ig>>$(NNIj!??$(OOIj!)&*&8&8Il#:: $

If:: $

If&*&7&7Il#  (,(=(=In%??%)__Ik";;##%D t#Xt,-.dC( 4yKK	"K $4;;1$D%&'1$++.//{{r1   c                 J    | j                   s| j                  t        d      y)zDCheck if it is okay to chain more options onto this cursor.
        Nz(cannot set options after executing query)r   rW   r   r@   s    r2   __check_okay_to_chainzCursor.__check_okay_to_chain  s'     tyy4"#MNN  5r1   c                 D   t        |t              st        d      | j                          |t        d   z  rS| j
                  rt        d      | j                  j                  j                  j                  rt        d      d| _        | xj                  |z  c_        | S )zsSet arbitrary query flags using a bitmask.

        To set the tailable flag:
        cursor.add_option(2)
        mask must be an intr$   rV   rU   T)r]   r^   r_   _Cursor__check_okay_to_chainr,   ri   r   re   r}   r~   r   rX   r   r:   masks     r2   
add_optionzCursor.add_option  s     $$122""$.++||&'NOO  ))00::& (A B B!DNd"r1   c                     t        |t              st        d      | j                          |t        d   z  rd| _        | xj                  | z  c_        | S )zzUnset arbitrary query flags using a bitmask.

        To unset the tailable flag:
        cursor.remove_option(2)
        r   r$   F)r]   r^   r_   r   r,   rX   r   r   s     r2   remove_optionzCursor.remove_option  sR     $$122""$.++"DNte#r1   c                 j    t        |t              st        d      | j                          || _        | S )a  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
        zallow_disk_use must be a bool)r]   boolr_   r   rz   )r:   rQ   s     r2   rQ   zCursor.allow_disk_use  s3     .$/;<<""$ .r1   c                     t        |t              st        d      | j                  rt	        d      | j                          d| _        || _        | S )a  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
        zlimit must be an integerrV   F)r]   r   r_   rX   r   r   r   ri   )r:   r   s     r2   r   zCursor.limit  sL     %/677>>"#JKK""$r1   c                     t        |t              st        d      |dk  rt        d      | j	                          || _        | S )az  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.
        rO   r   rP   )r]   r   r_   r`   r   rj   )r:   r   s     r2   r   zCursor.batch_size  sF    & *m4;<<>677""$&r1   c                     t        |t              st        d      |dk  rt        d      | j	                          || _        | S )a  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
        zskip must be an integerr   zskip must be >= 0)r]   r   r_   r`   r   rh   )r:   r   s     r2   r   zCursor.skip  sE     $.566!8011""$r1   c                 n    t        |t              s|t        d      | j                          || _        | S )a  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
        z&max_time_ms must be an integer or None)r]   r   r_   r   rr   )r:   r   s     r2   r   zCursor.max_time_ms  s9     ;6+DEE""$(r1   c                     t        |t              s|t        d      | j                          | j                  t
        j                  z  r|| _        | S )ag  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
        z,max_await_time_ms must be an integer or None)r]   r   r_   r   r   r'   r.   rs   )r:   r   s     r2   r   zCursor.max_await_time_ms+  sP    " ,m<%1JKK""$ 
 9 99'8D$r1   c                    | j                          d| _        t        |t              r|j                  t        d      d}|j                  &|j                  dk  rt        d      |j                  }|j                  /|j                  |z
  }|dk  rt        d|z        |dk(  r
d| _        nd}|| _        || _	        | S t        |t              r|dk  rt        d      | j                         }|j                  || j                  z          |j                  d       |xj                  t        j                    z  c_        |D ]  }|c S  t        d      t#        d	|z        )
aG  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
        Fz+Cursor instances do not support slice stepsr   z0Cursor instances do not support negative indicesz8stop index must be greater than start index for slice %rTz no such item for Cursor instancez.index %r cannot be applied to Cursor instances)r   r   r]   slicestep
IndexErrorstartstoprh   ri   r   r   r   r   r   r'   r.   r_   )r:   indexr   r   r   docs         r2   __getitem__zCursor.__getitem__G  sp   : 	""$eU#zz% !NOOD{{&;;?$ &8 9 9{{zz%

T)19$ &:<A&B C CA:#'DLDK DLKe]+qy  "+ , ,JJLEJJut{{*+KKOJ$=$=#== 
?@@ $&+, - 	-r1   c                 4    | j                          || _        | S )aE  **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.
        )r   ro   )r:   r   s     r2   r   zCursor.max_scan  s      	""$"r1   c                     t        |t        t        f      st        d      | j	                          t        |      | _        | S )a5  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
        )spec must be an instance of list or tuple)r]   listtupler_   r   r	   rt   r:   r   s     r2   r   z
Cursor.max  :      $u.GHH""$Y
r1   c                     t        |t        t        f      st        d      | j	                          t        |      | _        | S )a5  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
        r   )r]   r   r   r_   r   r	   ru   r   s     r2   r   z
Cursor.min  r   r1   c                     | j                          t        j                  ||      }t        j                  |      | _        | S )a  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
        )r   r
   _index_listrm   rn   )r:   key_or_list	directionkeyss       r2   r   zCursor.sort  s:    T 	""$"";	:!11$7r1   c                 &   t        j                  dt        d       t        d|       t	        d| j
                  j                  fd| j                  fg      }| j                  | j                  |d<   | j                  r| j                  |d<   | j                  | j                  |d	<   |r6| j                  r| j                  |d
<   | j                  r| j                  |d<   | j
                  j                  || j                  | j                        S )a  **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`.
        z<count is deprecated. Use Collection.count_documents instead.r   rL   with_limit_and_skipcountr   	maxTimeMSr   r   r   r   r   )ra   rb   rc   r   r	   re   r   rf   rr   rq   r   ri   rh   _countrw   r[   )r:   r  cmds      r2   r  zCursor.count  s    J 	 !"4	D.0CDGT..334T[[)+ ,)#11C>>!^^C	N;;"++CK||#||G{{"kkF  ''!!4>> ( ; 	;r1   c                 0   i }| j                   r| j                   |d<   | j                  | j                  |d<   | j                  r| j                  |d<   | j                  | j                  |d<    | j                  j
                  |fd| j                  i|S )a  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`
        r   r  r   r   r   )rf   rr   rq   rw   re   distinctr[   )r:   keyoptionss      r2   r  zCursor.distinct9  s    " ;;#{{GG)#'#5#5GK >>!%GI'#'#3#3GK )t  ))44+24 	4r1   c                     | j                         }d|_        |j                  rt        |j                         |_        t	        |      S )a  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
        T)r   rp   ri   absr   )r:   cs     r2   r   zCursor.explainW  s9     JJL 99QYYAIAwr1   c                 |    |d | _         y t        |t              r|| _         y t        j                  |      | _         y r=   )r   r]   r   r
   rm   r:   r   s     r2   
__set_hintzCursor.__set_hintk  s4    =DKe[)DK!11%8DKr1   c                 H    | j                          | j                  |       | S )a"  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.
        )r   r|   r  s     r2   r   zCursor.hintu  s!    0 	""$r1   c                 4    | j                          || _        | S )a6  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
        )r   rq   )r:   r   s     r2   r   zCursor.comment  s     	""$ r1   c                 z    | j                          t        |t              st        |      }|| j                  d<   | S )ai  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/
        z$where)r   r]   r   rf   )r:   codes     r2   wherezCursor.where  s6    < 	""$$%:D $Hr1   c                 F    | j                          t        |      | _        | S )a"  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`.
        )r   r   rw   )r:   r   s     r2   r   zCursor.collation  s"     	""$5i@r1   c                    | j                   j                  j                  }|j                  r| j                  rt        d      	 |j                  || j                  | j                  | j                        }|j"                  | _        | j                  r1| j$                  s%t'        |j(                  |j*                        | _        |j,                  }|j.                  }|j0                  r|dk7  r|d   d   }|d	   | _        |d
k(  r8|d   }|j5                  d      }|r%|j7                  dd      \  | _        | _        n|d   }t=        |      | _        | xj@                  tC        |      z  c_         nd| _        t=        |      | _        | xj@                  tC        |      z  c_         nT|jD                  jF                  | _        t=        |      | _        | xj@                  |jD                  jH                  z  c_         | j2                  dk(  rd| _
        | j                          | jJ                  r8| j2                  r+| jJ                  | j@                  k  r| j                          yyyy# t        $ r1 d| _
        | j                          | j                  t        d   z  rY y t        $ r d| _
        | j                           t        $ r d| _
        | j                           t         $ r | j                           w xY w)a#  Send a query or getmore operation and handles the response.

        If operation is ``None`` this is an exhaust cursor, which reads
        the next result batch off the exhaust socket instead of
        sending getMore messages to the server.

        Can raise ConnectionFailure.
        z.exhaust cursors do not support auto encryption)r$   r   Tr   Nr   r   cursoridfind
firstBatchns.rS   	nextBatch)&re   r}   r~   
_encrypterrX   r   _run_operation_with_response_unpack_responser   r   rZ   r   r   r,   r   r   	Exceptionr   rY   r4   socket_infor8   r   docsfrom_commandrW   getsplitr   r   r   r   r   r   r   	cursor_idnumber_returnedri   )	r:   	operationr~   responsecmd_namer'  r  	documentsr  s	            r2   __send_messagezCursor.__send_message  s    ""++22"@B B%	::400$.. ; (HL "))>>$"4"4!/0D0D08"?D >>}}  9$a*"4L	v% &| 4ID)B9;#q9I6t &{ 3I#I.  C	N2 	#Dk  CI-  //DI+DK = ==99> DM JJL<<DII$,,$:J:J*JJJL +KI<Q   	 DM JJL !!N3D$EE 	 !DM JJL  	
 !DMJJL 	JJL	s   3I' '6K:AK:c                 *    |j                  ||||      S r=   )unpack_responser:   r.  r+  r   user_fieldslegacy_responses         r2   r$  zCursor._unpack_response5  s    ''	=+(79 	9r1   c                     | j                   *| j                  j                  | j                        | _         | j                   S r=   )r   re   _read_preference_forr   r@   s    r2   _read_preferencezCursor._read_preference:  s:    !!)%)%6%6%K%K&D"%%%r1   c                    t        | j                        s| j                  rt        | j                        S | j                  s3| j                  j
                  j                  j                         | _        | j                  A| j                  s| j                  r(| j                  st        j                  dt        d       | j                  | j                   | j                  j
                  j"                  | j                  j"                  | j$                  | j'                         | j(                  | j*                  | j-                         | j.                  | j0                  | j2                  | j4                  | j                  | j                  j
                  j                  | j6                        }| j9                  |       n| j                  r| j.                  r<| j.                  | j:                  z
  }| j0                  r#t=        || j0                        }n| j0                  }| j?                  | j@                  | jB                  || j                  | j*                  | j-                         | j                  | j                  j
                  j                  | jD                  | jF                  
      }| j9                  |       t        | j                        S )a  Refreshes the cursor with more data from Mongo.

        Returns the length of self.__data after refresh. Will exit early if
        self.__data is already non-empty. Raises OperationFailure when the
        cursor cannot be refreshed due to an error on the query.
        zusing a min/max query operator without specifying a Cursor.hint is deprecated. A hint will be required when using min/max in PyMongo 4.0   rL   )$r   r   rZ   r[   re   r}   r~   _ensure_sessionrW   ru   rt   r   ra   rb   rc   _query_classr   r   rh   _Cursor__query_specrg   r   r9  ri   rj   r   rw   rz   _Cursor__send_messager   r   _getmore_classr   r   rs   rY   )r:   qr   gs       r2   _refreshzCursor._refreshA  s    t{{t}}t{{##~~!..77>>NNPDN99

djj$++ , 1Q	@
 !!$"4"4"&"3"3"<"<"A"A"&"3"3"8"8"&++"&"3"3"5"&"3"3"&"6"6"&"7"7"9"&,,"&"3"3"&"5"5"&"2"2"&.."&"3"3"<"<"C"C"&"7"79A "YY||t'7'77$$t'8'89E)) ##DMM$(OO$)$(II$($8$8$($9$9$;$(NN$($5$5$>$>$E$E$($<$<$($6$6	8A "4;;r1   c                 \    t        t        | j                        xs | j                         S )a	  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.
        )r   r   r   rZ   r@   s    r2   alivezCursor.alive|  s$    ( C$;T]]):<<r1   c                     | j                   S )zReturns 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
        )rW   r@   s    r2   r+  zCursor.cursor_id  s     yyr1   c                     | j                   S )zzThe (host, port) of the server used, or None.

        .. versionchanged:: 3.0
           Renamed from "conn_id".
        )r   r@   s    r2   r   zCursor.address  s     ~~r1   c                 4    | j                   r| j                  S y)zmThe cursor's :class:`~pymongo.client_session.ClientSession`, or None.

        .. versionadded:: 3.6
        N)r\   r[   r@   s    r2   r   zCursor.session  s     "">>! #r1   c                     | S r=   r0   r@   s    r2   __iter__zCursor.__iter__      r1   c                 \   | j                   rt        t        | j                        s| j	                         rp| j
                  rJ| j                  j                  }|j                  | j                  j                         | j                        S | j                  j                         S t        )zAdvance the cursor.)
r   StopIterationr   r   rC  rv   re   r}   _fix_outgoingpopleft)r:   _dbs     r2   r   zCursor.next  s    <<t{{t}}  ''00(()<)<)>)-):):< < {{**,,r1   c                     | S r=   r0   r@   s    r2   	__enter__zCursor.__enter__  rK  r1   c                 $    | j                          y r=   r>   )r:   exc_typeexc_valexc_tbs       r2   __exit__zCursor.__exit__  rB   r1   c                 &    | j                  d      S )zKSupport function for `copy.copy()`.

        .. versionadded:: 2.4
        Fr   r   r@   s    r2   __copy__zCursor.__copy__  s    
 {{E{**r1   c                 &    | j                  d      S )zOSupport function for `copy.deepcopy()`.

        .. versionadded:: 2.4
        TrY  r   )r:   memos     r2   __deepcopy__zCursor.__deepcopy__  s    
 {{D{))r1   c                    t        |d      sg dt        |      }}}ni dt        |      }}}|i }t        |      }||v r|j	                  |      S |||<   |D ]  \  }}t        |t        t        f      r#t        |t              s| j                  ||      }n&t        |t              st        j                  ||      }|r|j                  |       yt        |t              st        j                  ||      }|||<    |S )zDeepcopy helper for the data dictionary or list.

        Regular expressions cannot be deep copied but as they are immutable we
        don't have to copy them when cloning.
        itemsTF)hasattr	enumerater   r  r)  r]   r   r   r	   r   r   rk   r   append)	r:   xr\  yis_listiteratorval_idr  values	            r2   r   zCursor._deepcopy  s     q'"#%tYq\wA#%uilwA<DAT>88F##V" 	JC%$.z%7Mud3w/eT2!#w/--T2C#	 r1   )TN)Fr=   r6   )<r(   r)   r*   rE   r   r=  r   r@  r'   r+   r;   propertyr   r   rA   r   r   r   r   r   r?   r>  r   r   r   rQ   r   r   r   r   r   r   r   r   r   r   r  r  r   r|   r   r   r  r   r?  r$  r9  rC  rE  r+  r   r   rJ  r   __next__rR  rW  rZ  r]  r   r0   r1   r2   rG   rG   h   s   LN*.4aE'44%eA$dTttet $y*v ! !    
"!,B
"B
6pO* ,.8**8D-L(..-^9;v4<(98#J$\~ <A9
&9 v = =* 	 	   " "  H+*r1   rG   c                   @     e Zd ZdZeZeZ fdZ	 ddZ	d Z
d Z xZS )RawBatchCursorzFA cursor / iterator over raw batches of BSON data from a query result.c                 r    |j                  d      }d|d<   t        t        |   |i | |rt	        d      y)zCreate a new cursor / iterator over raw batches of BSON data.

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

        .. mongodoc:: cursors
        r   Fz.Cannot use RawBatchCursor with manipulate=TrueN)r)  superrl  r;   r   )r:   argskwargsr   r   s       r2   r;   zRawBatchCursor.__init__  sM     ZZ-
$|nd,d=f= "@B B r1   c                 $    |j                  |      S r=   )raw_responser4  s         r2   r$  zRawBatchCursor._unpack_response  s    $$Y//r1   c                 n    | j                  dt        | j                              }|j                         S )zWReturns an explain plan record for this cursor.

        .. mongodoc:: explain
        T)r   r   )r   rG   r   r   )r:   r   s     r2   r   zRawBatchCursor.explain  s+    
 Tt0GH}}r1   c                     t        d      )Nz)Cannot call __getitem__ on RawBatchCursor)r   r  s     r2   r   zRawBatchCursor.__getitem__  s    JKKr1   r6   )r(   r)   r*   rE   r   r=  r   r@  r;   r$  r   r   __classcell__)r   s   @r2   rl  rl    s,    P!L%NB& <A0Lr1   rl  ))rE   rk   ra   collectionsr   bsonr   	bson.coder   bson.py3compatr   r   r   bson.sonr	   pymongor
   pymongo.commonr   r   pymongo.collationr   pymongo.errorsr   r   r   r   pymongo.messager   r   r   r   r   pymongo.monitoringr   r,   objectr'   r4   rG   rl  r0   r1   r2   <module>r     s    8     ) )   @ 8. .- -
 6  >. .(MV M`$%LV %Lr1   