o Sb @sdZddlZddlZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZmZmZmZmZmZddlmZmZddlmZddlmZddlmZdd lmZdd l m!Z!m"Z"m#Z#dd l$m%Z%m&Z&m'Z'dd l(m)Z)m*Z*m+Z+m,Z,m-Z-dd l.m/Z/ddl0m1Z1m2Z2e3gdZ4ddddddddZ5Gddde6Z7Gddde6Z8eee9ee:e9e e9efffZ;ee9e;fZZ>ddl?m@Z@Gddde e2ZAGd d!d!eAe e2ZBdS)"z1Cursor class to iterate over Mongo query results.N)deque) TYPE_CHECKINGAnyDictGenericIterableListMappingNoReturnOptionalSequenceTupleUnioncastoverload)RE_TYPE&_convert_raw_document_lists_to_streams)Code)SON)helpers)validate_collation_or_none)validate_booleanvalidate_is_document_typevalidate_is_mapping)ConnectionFailureInvalidOperationOperationFailure)_CursorAddress_GetMore_Query_RawBatchGetMore_RawBatchQuery)PinnedResponse) _CollationIn _DocumentType)+2ioiC` @)tailable_cursorZsecondary_okay oplog_replay no_timeout await_dataexhaustpartialc@s2eZdZdZ edZ eedBZ edZdS) CursorTyperr2r5r6N)__name__ __module__ __qualname__ NON_TAILABLE_QUERY_OPTIONSTAILABLETAILABLE_AWAITEXHAUSTrArA5/tmp/pip-target-onvjaxws/lib/python/pymongo/cursor.pyr8ds r8c@s(eZdZdZddZddZddZdS) _SocketManagerz;Used with exhaust cursors to ensure the socket is returned.cCs ||_||_d|_t|_dSNF)sock more_to_comeclosed threadingLocklock)selfrErFrArArB__init__sz_SocketManager.__init__cCs ||_dSN)rF)rKrFrArArBupdate_exhausts z_SocketManager.update_exhaustcCs$|jsd|_|jd|_dSdS)z5Return this instance's socket to the connection pool.TN)rGrEZunpinrKrArArBcloses   z_SocketManager.closeN)r9r:r;__doc__rLrNrPrArArArBrCs  rC) ClientSession) Collectionc3@seZdZdZeZeZdddddej dddddddddddddddddfddde e e e fde ee e e fee fd ed ed ed ed e edededede ede ede ede ede ede ede ede ede ede e de dde ede eddf2d d!Zedd"d#Zedefd$d%Zdd&d'Zdd)d*Zdd+d,Zdd.d/Zd0d1Zdd2d3Zdd4d5Zd6d7Z d8d9Z!d:edd(fd;d<Z"d:edd(fd=d>Z#dedd(fd?d@Z$d edd(fdAdBZ%dedd(fdCdDZ&d edd(fdEdFZ'de edd(fdGdHZ(dIe edd(fdJdKZ)e*dLede+fdMdNZ,e*dLe-dd(fdOdNZ,dPdNZ,de edd(fdQdRZ.dSedd(fdTdUZ/dSedd(fdVdWZ0 ddXedYe eee fdd(fdZd[Z1d\e de2fd]d^Z3de+fd_d`Z4dadbZ5dLe edd(fdcddZ6de dd(fdedfZ7dgee e8fdd(fdhdiZ9de edd(fdjdkZ:dldmZ; ddndoZedefdtduZ?ede efdvdwZ@ede eAe e ffdxdyZBede dfdzd{ZCdd|d}ZDde+fd~dZEeEZFdddZGde de de ddfddZHdddZIde de fddZJdddZKdS)Cursorz-A cursor / iterator over Mongo query results.NrF collectionCollection[_DocumentType]filter projectionskiplimitno_cursor_timeout cursor_typesortallow_partial_resultsr3 batch_size collationhintmax_scan max_time_msmaxmin return_keyshow_record_idsnapshotcommentsessionrRallow_disk_useletreturncCs||_d|_d|_d|_d|_||r||_d|_nd|_d|_|p#i}td|t|t s2t dt|t s;t dt d||rM|jsMt j dtd d |tjtjtjtjfvr]td t d | t d | t| t spt d| dkrxtd|durt d|}|durt|d}|durtd|||_||_|du|_||_||_||_| |_|rt|pd|_ ||_!d|_"||_#||_$d|_%||_&||_'t(| |_)||_*||_+||_,||_-|.| |tjkr|jj/j0j1rt2d|rt2dd|_d|_3t4|_5d|_6d|_7|j8|_9d|_:|j;|_<||_=|r|j=t>dO_=| r+|j=t>dO_=| r7|j=t>d O_=|j/j?|_@|j?|_AdS)a Create a new cursor. Should not be called directly by application developers - see :meth:`~pymongo.collection.Collection.find` instead. .. seealso:: The MongoDB documentation on `cursors `_. NFTrWzskip must be an instance of intz limit must be an instance of intr[zuse an explicit session with no_cursor_timeout=True otherwise the cursor may still timeout after 30 minutes, for more info see https://mongodb.com/docs/v4.4/reference/method/cursor.noCursorTimeout/#session-idle-timeout-overrides-nocursortimeoutr+) stacklevelz!not a valid value for cursor_typer^r3batch_size must be an integerrbatch_size must be >= 0rkrXrl+Exhaust cursors are not supported by mongos%Can't use limit and exhaust together.r4r7)B_Cursor__collection _Cursor__id_Cursor__exhaust_Cursor__sock_mgr_Cursor__killed_Cursor__session_Cursor__explicit_sessionr isinstanceint TypeErrorrwarningswarn UserWarningr8r<r>r?r@ ValueErrorrZ_fields_list_to_dictr _Cursor__let _Cursor__spec_Cursor__has_filter_Cursor__projection _Cursor__skip_Cursor__limit_Cursor__batch_size_index_document_Cursor__ordering_Cursor__max_scan_Cursor__explain_Cursor__comment_Cursor__max_time_ms_Cursor__max_await_time_ms _Cursor__max _Cursor__minr_Cursor__collation_Cursor__return_key_Cursor__show_record_id_Cursor__allow_disk_use_Cursor__snapshot_Cursor__set_hintdatabaseclient is_mongosr_Cursor__emptyr _Cursor__data_Cursor__address_Cursor__retrieved codec_options_Cursor__codec_options_Cursor__read_preferenceZ read_concern_Cursor__read_concern_Cursor__query_flagsr=name_Cursor__dbname_Cursor__collname)rKrUrWrXrYrZr[r\r]r^r3r_r`rarbrcrdrerfrgrhrirjrkrlspecrArArBrLs$                   zCursor.__init__cC|jS)zdThe :class:`~pymongo.collection.Collection` that this :class:`Cursor` is iterating. )rsrOrArArBrU:szCursor.collectioncCr)z)The number of documents retrieved so far.)rrOrArArB retrievedAszCursor.retrievedcC |dSrM _Cursor__dierOrArArB__del__F zCursor.__del__Cursor[_DocumentType]cCs,|t|_d|_d|_d|_d|_|S)aRewind 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. NrF)rPrrrtrrrwrOrArArBrewindIs z Cursor.rewindcCs |dS)aGet 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_clonerOrArArBclone[s z Cursor.cloneTcs`|s|jr ||j}n|d}dtfdd|jD}|r(||}|j||S)zInternal clone helper.N)rrXrYrZrcmax_await_time_msrirdreZorderingexplainrar_rbZ query_flagsr`emptyrgrfrkrhr6Z has_filterc3s6|]\}}|dr|ddvr||fVqdS)Z _Cursor__ N) startswith).0kvZvalues_to_clonerArB s z Cursor._clone..)ry _clone_baserxdict__dict__items _deepcopyupdate)rKdeepcopybasedatarArrBres    z Cursor._clonecCs|j|j|dS)zACreates an empty Cursor object for information to be copied into.)rj) __class__rs)rKrjrArArBrszCursor._clone_basecCsz|j}Wn tyYdSwd|_|jr(|s(|j}t|jd|j|jf}nd}d}|jjj ||||j |j |j |j sBd|_ d|_ dS)zCloses this cursor.NTz%s.%sr)rwAttributeErrorrtrrrrrsrrZ_cleanup_cursorrvrxry)rKZ synchronousZalready_killed cursor_idaddressrArArBZ__dies,     z Cursor.__diecCs|ddS)z$Explicitly close / kill this cursor.TNrrOrArArBrPsz Cursor.closecCsVi}|jr |j|d<|jrd|d<|jr|j|d<|jr!|j|d<|jr)|j|d<|jr1|j|d<|jdur;|j|d <|jrC|j|d <|jrK|j|d <|j durU|j |d <|j dur_|j |d <|j duri|j |d<|rt |j }d|vr|td|fg}t|tst|}|||Sd|j vrt|j dkstt|j dkrtd|j iS|j S)z Get the spec to use for a query.z$orderbyTz$explainz$hintrlz$commentz$maxScanNz $maxTimeMSz$maxz$minz $returnKeyz $showDiskLocz $snapshotz$queryquery)rr _Cursor__hintrrrrrrrrrcopyrrrzrlennextiter)rK operatorsrrArArBZ __query_specsP                    zCursor.__query_speccCs|js|jdur tddS)z;Check if it is okay to chain more options onto this cursor.Nz(cannot set options after executing query)rrtrrOrArArBZ__check_okay_to_chainszCursor.__check_okay_to_chainmaskcCs`t|ts td||td@r'|jrtd|jjj j r$tdd|_ |j |O_ |S)zsSet arbitrary query flags using a bitmask. To set the tailable flag: cursor.add_option(2) mask must be an intr6rrrqT) rzr{r|_Cursor__check_okay_to_chainr=rrrsrrrrurrKrrArArB add_options   zCursor.add_optioncCs@t|ts td||td@rd|_|j|M_|S)zzUnset arbitrary query flags using a bitmask. To unset the tailable flag: cursor.remove_option(2) rr6F)rzr{r|rr=rurrrArArB remove_options  zCursor.remove_optioncCs$t|ts td|||_|S)aSpecifies 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 zallow_disk_use must be a bool)rzboolr|rr)rKrkrArArBrks zCursor.allow_disk_usecCs8t|ts td|jrtd|d|_||_|S)aLimits 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 .. seealso:: The MongoDB documentation on `limit `_. zlimit must be an integerrrF)rzr{r|rurrrr)rKrZrArArBrZ,s z Cursor.limitcC4t|ts td|dkrtd|||_|S)azLimits 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. rorrp)rzr{r|rrr)rKr_rArArBr_Cs zCursor.batch_sizecCr)aSkips 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 zskip must be an integerrzskip must be >= 0)rzr{r|rrr)rKrYrArArBrY_s z Cursor.skipcCs,t|ts |dur td|||_|S)aSpecifies 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 Nz&max_time_ms must be an integer or None)rzr{r|rr)rKrcrArArBrcts  zCursor.max_time_msrcCs8t|ts |dur td||jtj@r||_|S)agSpecifies 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 Nz,max_await_time_ms must be an integer or None)rzr{r|rrr8r?r)rKrrArArBrs  zCursor.max_await_time_msindexcCdSrMrArKrrArArB __getitem__zCursor.__getitem__cCrrMrArrArArBrrcCs|d|_t|trN|jdurtdd}|jdur(|jdkr%td|j}|jdurD|j|}|dkr>> 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 FNz+Cursor instances do not support slice stepsrz0Cursor 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)rrrzslicestep IndexErrorstartstoprrr{rrYrZrr8r?r|)rKrrYrZrdocrArArBrsD)         cC|||_|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. )rr)rKrbrArArBrbszCursor.max_scanrcC,t|ttfs td|t||_|S)a5Adds ``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)rzlisttupler|rrrrKrrArArBrd  z Cursor.maxcCr)a5Adds ``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)rzrrr|rrrrrArArBre&rz Cursor.min key_or_list directioncCs$|t||}t||_|S)aSorts 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) 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 `_. 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 )rrZ _index_listrr)rKrrkeysrArArBr]=s+  z Cursor.sortkeycCsfi}|jr |j|d<|jdur|j|d<|jr|j|d<|jdur&|j|d<|jj|fd|ji|S)aGet 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` rNZ maxTimeMSrir`rj)rrrrrsdistinctrx)rKroptionsrArArBrms      zCursor.distinctcCs*|}d|_|jrt|j |_t|S)aReturns an explain plan record for this cursor. .. note:: This method uses the default verbosity mode of the `explain command `_, ``allPlansExecution``. To use a different verbosity use :meth:`~pymongo.database.Database.command` to run the explain command directly. .. seealso:: The MongoDB documentation on `explain `_. T)rrrabsr)rKcrArArBrs  zCursor.explaincCs6|dur d|_dSt|tr||_dSt||_dSrM)rrzstrrrrrArArBZ __set_hints   zCursor.__set_hintcCs||||S)aAdds 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) )rrrrArArBras z Cursor.hintcCr)a6Adds a 'comment' to the cursor. http://mongodb.com/docs/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 )rr)rKrirArArBris zCursor.commentcodecCsJ|t|ts t|}|jrt|j}ntt|j}||d<||_|S)aiAdds 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://mongodb.com/docs/manual/reference/operator/query/expr/ .. _$where: https://mongodb.com/docs/manual/reference/operator/query/where/ z$where)rrzrrrrrr)rKrrrArArBwheres   z Cursor.wherecCs|t||_|S)aAdds a :class:`~pymongo.collation.Collation` to this query. 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`. )rrr)rKr`rArArBr`s zCursor.collationc Cs |jjj}|jr|jrtdz |j||j|jd}WnHt yJ}z#|j t vs+|jr.d|_ | |j t vrE|jtd@rEWYd}~dSd}~wtyXd|_ | tyc| w|j|_t|trx|jsxt|j|j|_|j}|j}|jr|dkr|dd}|d |_|d kr|d }|d } | r| d d\|_|_ n|d}t!||_"|j#t$|7_#n%d|_t!||_"|j#t$|7_#n|j%j&|_t!||_"|j#|j%j'7_#|jdkr| |j(r|jr|j(|j#kr| dSdSdSdS)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)rTr2NrrcursoridfindZ firstBatchns.rZ nextBatch))rsrrZ _encrypterrurZ_run_operation_unpack_responserrr_CURSOR_CLOSED_ERRORSrwrPrr=r Exceptionrrzr"rvrCZ socket_inforFrdocsZ from_commandrtgetsplitrrrrrrrrZnumber_returnedr) rKZ operationrresponseexccmd_namerrZ documentsrrArArBZ__send_message sp                 zCursor.__send_messagecCs|||||SrM)Zunpack_response)rKrrr user_fieldslegacy_responserArArBr]szCursor._unpack_responsecCs |jdur |j|j|_|jSrM)rrsZ_read_preference_forrjrOrArArB_read_preferencebs zCursor._read_preferencecCs8t|js|jr t|jS|js|jjj|_|jdur[|j s#|j r*|j s*t d| |j|jjj|jj|j||j|j||j|j|j|j|j|jjj|j|j}||n<|jr|jrq|j|j}|jrpt||j}n|j}||j|j ||j|j||j|jjj|j!|j"|j|j# }||t|jS)aRefreshes 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. NzoPassing a 'hint' is required when using the min/max query option to ensure the query utilizes the correct index)$rrrwrxrsrrZ_ensure_sessionrtrrrr _query_classrrr_Cursor__query_specrrrrrrrrru_Cursor__send_messagerre_getmore_classrrrrvr)rKqrZgrArArB_refreshhsf       zCursor._refreshcCstt|jp |j S)aDoes 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 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. )rrrrwrOrArArBalivesz Cursor.alivecCr)zDReturns the id of the cursor .. versionadded:: 2.2 )rtrOrArArBrszCursor.cursor_idcCr)zzThe (host, port) of the server used, or None. .. versionchanged:: 3.0 Renamed from "conn_id". )rrOrArArBrszCursor.addresscCs|jr|jSdS)zmThe cursor's :class:`~pymongo.client_session.ClientSession`, or None. .. versionadded:: 3.6 N)ryrxrOrArArBrjszCursor.sessioncC|SrMrArOrArArB__iter__zCursor.__iter__cCs*|jrtt|js|r|jSt)zAdvance the cursor.)r StopIterationrrrpopleftrOrArArBrs  z Cursor.nextcCrrMrArOrArArB __enter__rzCursor.__enter__exc_typeexc_valexc_tbcCrrM)rP)rKrrrrArArB__exit__rzCursor.__exit__cC |jddS)zKSupport function for `copy.copy()`. .. versionadded:: 2.4 FrrrOrArArB__copy__ zCursor.__copy__memocCr)zOSupport function for `copy.deepcopy()`. .. versionadded:: 2.4 Trr)rKrrArArB __deepcopy__rzCursor.__deepcopy__c Cst|dsgdt|}}}n id|}}}|dur i}t|}||vr-||S|||<|D]9\}}t|ttfrJt|tsJ| ||}n t|t sUt ||}|r]| |q3t|t sht ||}|||<q3|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. rTFN)hasattr enumeraterrrrzrrrrrrrappend) rKxryZis_listiteratorZval_idrvaluerArArBrs(         zCursor._deepcopy)rmrV)rmN)rmr)TN)FrMrD)Lr9r:r;rQrr rr r8r<r r rrrrr{r_Sortr#_HintrLpropertyrUrrrrrrrrPr rrrrkrZr_rYrcrrr$rrrbrdrer]rrrrrarirrr`r rrrrrr rrjrr__next__rrrr rrArArArBrTs            +  9P 0 -Q @   rTcsfeZdZdZeZeZdddededdffdd Z dd d Z de fd dZ dede fddZZS)RawBatchCursorzFA cursor / iterator over raw batches of BSON data from a query result.rUrVargskwargsrmNcs"tt|j|g|Ri|dS)aGCreate 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. .. seealso:: The MongoDB documentation on `cursors `_. N)superr,rL)rKrUr-r.rrArBrL#s" zRawBatchCursor.__init__FcCs"|j||d}|st|d|S)N)rr) raw_responser)rKrrrrrr1rArArBr.s zRawBatchCursor._unpack_responsecCs|jdt|jd}|S)zReturns an explain plan record for this cursor. .. seealso:: The MongoDB documentation on `explain `_. T)rr)rrTrUr)rKrrArArBr8szRawBatchCursor.explainrcCstd)Nz)Cannot call __getitem__ on RawBatchCursor)rrrArArBr@szRawBatchCursor.__getitem__rD)r9r:r;rQr!r r r rrLrr$rr r __classcell__rArAr0rBr,s  r,)CrQrrHr} collectionsrtypingrrrrrrr r r r r rrrZbsonrrZ bson.coderZbson.sonrZpymongorZpymongo.collationrZpymongo.commonrrrZpymongo.errorsrrrZpymongo.messagerrrr r!Zpymongo.responser"Zpymongo.typingsr#r$ frozensetrr=objectr8rCrr{r(r)Zpymongo.client_sessionrRZpymongo.collectionrSrTr,rArArArBsZ @      "