o
    'hmE                    @  s  d Z ddlmZ ddlZddlmZ ddlmZmZm	Z	m
Z
mZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZ ddlm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'm(Z(m)Z) ddl*m+Z+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:m;Z; ddl<m=Z=m>Z>m?Z?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZP ddlQmRZR ddlSmTZTmUZU ddlVmWZWmXZXmYZYmZZZm[Z[ ddl\m]Z]m^Z^m_Z_m`Z` ddlambZbmcZcmdZd dZeedZfddiZgeeIe^ eGeFeJe^ eMeLf ZhG d d! d!ZierNddljZjdd"l*mkZk dd#llmmZm dd$lnmoZo dd%lpmqZq dd&lrmsZs dd'l7mtZt dd(lQmuZu G d)d* d*e'jvee^ ZwdS )+z%Collection level utilities for Mongo.    )annotationsN)abc)TYPE_CHECKINGAnyAsyncContextManagerCallable	CoroutineGenericIterableIteratorMappingMutableMappingNoReturnOptionalSequenceTypeTypeVarUnioncastoverload)DEFAULT_CODEC_OPTIONSCodecOptions)ObjectId)RawBSONDocument)SON)	Timestamp)	ASCENDING_csotcommonhelpers_sharedmessage)_CollectionAggregationCommand _CollectionRawAggregationCommand)
_AsyncBulk)AsyncCollectionChangeStream)AsyncCommandCursorAsyncRawBatchCommandCursor)AsyncCursorAsyncRawBatchCursor)validate_collation_or_none)_ecoc_coll_name_esc_coll_name)ConfigurationErrorInvalidNameInvalidOperationOperationFailure)_check_write_command_response)_UNICODE_REPLACE_CODEC_OPTIONS)
DeleteMany	DeleteOne
IndexModel	InsertOne
ReplaceOneSearchIndexModel
UpdateMany	UpdateOne_IndexKeyHint
_IndexList_Op)DEFAULT_READ_CONCERN)ReadPreference_ServerMode)BulkWriteResultDeleteResultInsertManyResultInsertOneResultUpdateResult)_CollationIn_DocumentType_DocumentTypeArg	_Pipeline)DEFAULT_WRITE_CONCERNWriteConcernvalidate_booleanFTvalue   c                   @  s   e Zd ZdZdZ	 dZdS )ReturnDocumentzAn enum used with
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_replace` and
    :meth:`~pymongo.asynchronous.collection.AsyncCollection.find_one_and_update`.
    FTN)__name__
__module____qualname____doc__BEFOREAFTER rV   rV   [/var/www/html/olx_land/venv/lib/python3.10/site-packages/pymongo/asynchronous/collection.pyrO   q   s    rO   )_AggregationCommand)AsyncClientSessionAsyncDatabase)AsyncConnection)Server)	Collation)ReadConcernc                	      s  e Zd ZdZ						dd fddZdddZdddZddd Zdd#d$Zdd%d&Z	dd(d)Z
dd+d,Zedd-d.Zedd/d0Zedd1d2Ze		3	3	3ddd4d5Ze	3	3	3ddd8d5Z				dd d;d5Zd!d?d@ZdZddAdBZeZd"dDdEZ												d#d$dYdZZd%d]d^Z			_							d&d'djdkZ		d(d)dodpZd*dqdrZej	_				d+d,dzd{Z	d-d.ddZ			d/d0ddZ ej	_			d1d2ddZ!					_									d3d4ddZ"					_								d5d6ddZ#								d7d8ddZ$									d9d:ddZ%								d7d;ddZ&			d/d<ddZ'			_						d=d>ddZ(			_					d?d@ddZ)					dAdBddZ*					dAdBddZ+	d-dCddZ,dDddZ-dEddZ.dFddZ/dGddZ0d-dHddZ1		dIdJddZ2dKddĄZ3		dIdLddɄZ4ejdMdd˄Z5		dIdNddτZ6		dIdOddфZ7ej		dIdPddԄZ8ej		dIdPddքZ9		dIdQddلZ:		dIdQddۄZ;		dIdRdd݄Z<			d/dSddZ=		dIdTddZ>		dIdUddZ?		dIdUddZ@		dIdVddZA		dIdWddZB		dIdRddZCej		dIdXddZD			d/dYddZE		dIdZddZFej		dId[d dZG				dd\ddZHdeIjJddddfd]d
dZK						d^d_ddZLdddeIjJddddfd`ddZMdddeIjJdddddf	daddZN  ZOS (b  AsyncCollectionz!An asynchronous Mongo collection.FNdatabaseAsyncDatabase[_DocumentType]namestrcreateOptional[bool]codec_options(Optional[CodecOptions[_DocumentTypeArg]]read_preferenceOptional[_ServerMode]write_concernOptional[WriteConcern]read_concernOptional[ReadConcern]sessionOptional[AsyncClientSession]kwargsr   returnNonec	                   sf  t  |p|j|p|j|p|j|p|j t|ts#tdt	| ddl
m}
 t||
sDtdd t	|jD sDtdt	|j |rJd|v rNtdd	|v r]|d
s]td| |d dksi|d dkrotd| d|v rwtd|| _|| _| jj d| j | _| jjdtd| _|jjj| _|s|	rtrtjdtdd |  |	| dS t!ddS )a&  Get / create an asynchronous Mongo collection.

        Raises :class:`TypeError` if `name` is not an instance of
        :class:`str`. Raises :class:`~pymongo.errors.InvalidName` if `name` is
        not a valid collection name. Any additional keyword arguments will be used
        as options passed to the create command. See
        :meth:`~pymongo.asynchronous.database.AsyncDatabase.create_collection` for valid
        options.

        If `create` is ``True``, `collation` is specified, or any additional
        keyword arguments are present, a ``create`` command will be
        sent, using ``session`` if specified. Otherwise, a ``create`` command
        will not be sent and the collection will be created implicitly on first
        use. The optional ``session`` argument is *only* used for the ``create``
        command, it is not associated with the collection afterward.

        :param database: the database to get a collection from
        :param name: the name of the collection to get
        :param create: **Not supported by AsyncCollection**.
        :param codec_options: An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) database.codec_options is used.
        :param read_preference: The read preference to use. If
            ``None`` (the default) database.read_preference is used.
        :param write_concern: An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) database.write_concern is used.
        :param read_concern: An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) database.read_concern is used.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`. If a collation is provided,
            it will be passed to the create collection command.
        :param session: **Not supported by AsyncCollection**.
        :param kwargs: **Not supported by AsyncCollection**.

        .. versionchanged:: 4.2
           Added the ``clusteredIndex`` and ``encryptedFields`` parameters.

        .. versionchanged:: 4.0
           Removed the reindex, map_reduce, inline_map_reduce,
           parallel_scan, initialize_unordered_bulk_op,
           initialize_ordered_bulk_op, group, count, insert, save,
           update, remove, find_and_modify, and ensure_index methods. See the
           :ref:`pymongo4-migration-guide`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.4
           Support the `collation` option.

        .. versionchanged:: 3.2
           Added the read_concern option.

        .. versionchanged:: 3.0
           Added the codec_options, read_preference, and write_concern options.
           Removed the uuid_subtype attribute.
           :class:`~pymongo.asynchronous.collection.AsyncCollection` no longer returns an
           instance of :class:`~pymongo.asynchronous.collection.AsyncCollection` for attribute
           names with leading underscores. You must use dict-style lookups
           instead::

               collection['__my_collection__']

           Not:

               collection.__my_collection__

        .. seealso:: The MongoDB documentation on `collections <https://dochub.mongodb.org/core/collections>`_.
        z%name must be an instance of str, not r   rZ   c                 s  s    | ]}|j d kV  qdS )r[   N)rP   ).0clsrV   rV   rW   	<genexpr>   s    z+AsyncCollection.__init__.<locals>.<genexpr>z!AsyncDatabase required but given .. collection names cannot be empty$)oplog.$mainz$cmdz)collection names must not contain '$': %r.z3collection names must not start or end with '.': %r z4collection names must not contain the null characterreplace)unicode_decode_error_handlerdocument_classzhThe `create` and `kwargs` arguments to AsyncCollection are deprecated and will be removed in PyMongo 5.0   )
stacklevelzDAsyncCollection does not support the `create` or `kwargs` arguments.N)"super__init__rg   ri   rk   rm   
isinstancerd   	TypeErrortypepymongo.asynchronous.databaser[   any__mro__rP   r-   
startswith	_database_namerc   
_full_name_replacedict_write_response_codec_optionsclientoptionstimeout_timeout_IS_SYNCwarningswarnDeprecationWarning_create
ValueError)selfra   rc   re   rg   ri   rk   rm   ro   rq   r[   	__class__rV   rW   r      sN   S

zAsyncCollection.__init__AsyncCollection[_DocumentType]c              	   C  sJ   | dr | j d| }tt| j d|d| d| d| |S )zGet a sub-collection of this collection by name.

        Raises InvalidName if an invalid collection name is used.

        :param name: the name of the collection to get
        _r{   z has no attribute z. To access the z collection, use database['z'].)r   r   AttributeErrorr   rP   __getitem__)r   rc   	full_namerV   rV   rW   __getattr__  s   

zAsyncCollection.__getattr__c                 C  s*   t | j| j d| d| j| j| j| jS )Nr{   Fr`   r   r   rg   ri   rk   rm   )r   rc   rV   rV   rW   r     s   zAsyncCollection.__getitem__c                 C  s    t | j d| jd| jdS )N(z, ))r   rP   r   r   r   rV   rV   rW   __repr__'  s    zAsyncCollection.__repr__otherboolc                 C  s&   t |tr| j|jko| j|jkS tS N)r   r`   r   ra   r   rc   NotImplementedr   r   rV   rV   rW   __eq__*  s   
zAsyncCollection.__eq__c                 C  s
   | |k S r   rV   r   rV   rV   rW   __ne__/  s   
zAsyncCollection.__ne__intc                 C  s   t | j| jfS r   )hashr   r   r   rV   rV   rW   __hash__2  s   zAsyncCollection.__hash__r   c                 C  s   t t| j d)Nzq objects do not implement truth value testing or bool(). Please compare with None instead: collection is not None)NotImplementedErrorr   rP   r   rV   rV   rW   __bool__5  s   zAsyncCollection.__bool__c                 C     | j S )zThe full name of this :class:`AsyncCollection`.

        The full name is of the form `database_name.collection_name`.
        )r   r   rV   rV   rW   r   <  s   zAsyncCollection.full_namec                 C  r   )z*The name of this :class:`AsyncCollection`.)r   r   rV   rV   rW   rc   D  s   zAsyncCollection.namec                 C  r   )z{The :class:`~pymongo.asynchronous.database.AsyncDatabase` that this
        :class:`AsyncCollection` is a part of.
        )r   r   rV   rV   rW   ra   I  s   zAsyncCollection.database.c                 C     d S r   rV   r   rg   ri   rk   rm   rV   rV   rW   with_optionsP     zAsyncCollection.with_options#bson.CodecOptions[_DocumentTypeArg]!AsyncCollection[_DocumentTypeArg]c                 C  r   r   rV   r   rV   rV   rW   r   Z  r   -Optional[bson.CodecOptions[_DocumentTypeArg]]BAsyncCollection[_DocumentType] | AsyncCollection[_DocumentTypeArg]c                 C  s0   t | j| jd|p
| j|p| j|p| j|p| jS )a  Get a clone of this collection changing the specified settings.

          >>> coll1.read_preference
          Primary()
          >>> from pymongo import ReadPreference
          >>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY)
          >>> coll1.read_preference
          Primary()
          >>> coll2.read_preference
          Secondary(tag_sets=None)

        :param codec_options: An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) the :attr:`codec_options` of this :class:`AsyncCollection`
            is used.
        :param read_preference: The read preference to use. If
            ``None`` (the default) the :attr:`read_preference` of this
            :class:`AsyncCollection` is used. See :mod:`~pymongo.read_preferences`
            for options.
        :param write_concern: An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) the :attr:`write_concern` of this :class:`AsyncCollection`
            is used.
        :param read_concern: An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) the :attr:`read_concern` of this :class:`AsyncCollection`
            is used.
        Fr   r   rV   rV   rW   r   d  s   #cmdMapping[str, Any]rJ   c                 C  s*   | d}|d urtdi |S | |S )NwriteConcernrV   )getrJ   _write_concern_for)r   r   ro   raw_wcrV   rV   rW   _write_concern_for_cmd  s   

z&AsyncCollection._write_concern_for_cmdc                 C  s   t d)Nz('AsyncCollection' object is not iterable)r   r   rV   rV   rW   __next__  s   zAsyncCollection.__next__argsc                 O  sX   d| j vrtdt| j d| j  tdt| j dt| j d| j dd  )zAThis is only here so that some API misusages are easier to debug.r{   'z' object is not callable. If you meant to call the '%s' method on an 'AsyncDatabase' object it is failing because no such method exists.zE' object is not callable. If you meant to call the '%s' method on a 'z5' object it is failing because no such method exists.r|   )r   r   r   rP   splitr   r   rq   rV   rV   rW   __call__  s   
zAsyncCollection.__call__pipelineOptional[_Pipeline]full_documentOptional[str]resume_afterOptional[Mapping[str, Any]]max_await_time_msOptional[int]
batch_size	collationOptional[_CollationIn]start_at_operation_timeOptional[Timestamp]start_aftercommentOptional[Any]full_document_before_changeshow_expanded_events*AsyncCollectionChangeStream[_DocumentType]c                   s4   t | |||||||||	|
||}| I dH  |S )aX  Watch changes on this collection.

        Performs an aggregation with an implicit initial ``$changeStream``
        stage and returns a
        :class:`~pymongo.asynchronous.change_stream.AsyncCollectionChangeStream` cursor which
        iterates over changes on this collection.

        .. code-block:: python

           async with await db.collection.watch() as stream:
               async for change in stream:
                   print(change)

        The :class:`~pymongo.asynchronous.change_stream.AsyncCollectionChangeStream` iterable
        blocks until the next change document is returned or an error is
        raised. If the
        :meth:`~pymongo.asynchronous.change_stream.AsyncCollectionChangeStream.next` method
        encounters a network error when retrieving a batch from the server,
        it will automatically attempt to recreate the cursor such that no
        change events are missed. Any error encountered during the resume
        attempt indicates there may be an outage and will be raised.

        .. code-block:: python

            try:
                async with await db.coll.watch([{"$match": {"operationType": "insert"}}]) as stream:
                    async for insert_change in stream:
                        print(insert_change)
            except pymongo.errors.PyMongoError:
                # The AsyncChangeStream encountered an unrecoverable error or the
                # resume attempt failed to recreate the cursor.
                logging.error("...")

        For a precise description of the resume process see the
        `change streams specification`_.

        .. note:: Using this helper method is preferred to directly calling
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.aggregate` with a
            ``$changeStream`` stage, for the purpose of supporting
            resumability.

        .. warning:: This AsyncCollection's :attr:`read_concern` must be
            ``ReadConcern("majority")`` in order to use the ``$changeStream``
            stage.

        :param pipeline: A list of aggregation pipeline stages to
            append to an initial ``$changeStream`` stage. Not all
            pipeline stages are valid after a ``$changeStream`` stage, see the
            MongoDB documentation on change streams for the supported stages.
        :param full_document: The fullDocument to pass as an option
            to the ``$changeStream`` stage. Allowed values: 'updateLookup',
            'whenAvailable', 'required'. When set to 'updateLookup', the
            change notification for partial updates will include both a delta
            describing the changes to the document, as well as a copy of the
            entire document that was changed from some time after the change
            occurred.
        :param full_document_before_change: Allowed values: 'whenAvailable'
            and 'required'. Change events may now result in a
            'fullDocumentBeforeChange' response field.
        :param resume_after: A resume token. If provided, the
            change stream will start returning changes that occur directly
            after the operation specified in the resume token. A resume token
            is the _id value of a change document.
        :param max_await_time_ms: The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
        :param batch_size: The maximum number of documents to return
            per batch.
        :param collation: The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
        :param start_at_operation_time: If provided, the resulting
            change stream will only return changes that occurred at or after
            the specified :class:`~bson.timestamp.Timestamp`. Requires
            MongoDB >= 4.0.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param start_after: The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.
        :param comment: A user-provided comment to attach to this
            command.
        :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`.

        :return: A :class:`~pymongo.asynchronous.change_stream.AsyncCollectionChangeStream` cursor.

        .. versionchanged:: 4.3
           Added `show_expanded_events` parameter.

        .. versionchanged:: 4.2
           Added ``full_document_before_change`` parameter.

        .. versionchanged:: 4.1
           Added ``comment`` parameter.

        .. versionchanged:: 3.9
           Added the ``start_after`` parameter.

        .. versionchanged:: 3.7
           Added the ``start_at_operation_time`` parameter.

        .. versionadded:: 3.6

        .. seealso:: The MongoDB documentation on `changeStreams <https://mongodb.com/docs/manual/changeStreams/>`_.

        .. _change streams specification:
            https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md
        N)r$   _initialize_cursor)r   r   r   r   r   r   r   r   ro   r   r   r   r   change_streamrV   rV   rW   watch  s$   zzAsyncCollection.watch	operation$AsyncContextManager[AsyncConnection]c                   s   | j j||I d H S r   )r   r   _conn_for_writes)r   ro   r   rV   rV   rW   r   >  s   z AsyncCollection._conn_for_writesTconnr\   commandMutableMapping[str, Any]Optional[CodecOptions]checkallowable_errors#Optional[Sequence[Union[str, int]]]retryable_writeuser_fieldsc                   s   | j j|
4 I dH -}|j| j j||p| |
|p| j||||d|	|| j j||dI dH W  d  I dH  S 1 I dH s?w   Y  dS )a  Internal command helper.

        :param conn` - A AsyncConnection instance.
        :param command` - The command itself, as a :class:`~bson.son.SON` instance.
        :param read_preference` (optional) - The read preference to use.
        :param codec_options` (optional) - An instance of
            :class:`~bson.codec_options.CodecOptions`.
        :param check: raise OperationFailure if there are errors
        :param allowable_errors: errors to ignore if `check` is True
        :param read_concern` (optional) - An instance of
            :class:`~pymongo.read_concern.ReadConcern`.
        :param write_concern: An instance of
            :class:`~pymongo.write_concern.WriteConcern`.
        :param collation` (optional) - An instance of
            :class:`~pymongo.collation.Collation`.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param retryable_write: True if this command is a retryable
            write.
        :param user_fields: Response fields that should be decoded
            using the TypeDecoders from codec_options, passed to
            bson._decode_all_selective.

        :return: The result document.
        NT)rm   rk   parse_write_concern_errorr   ro   r   r   r   )r   r   _tmp_sessionr   rc   _read_preference_forrg   )r   r   r   ri   rg   r   r   rm   rk   r   ro   r   r   srV   rV   rW   _commandC  s&   (
0zAsyncCollection._commandr   encrypted_fieldsqev2_requiredc           	   	     s   d|i}|r||d< |rd|v rt |d |d< || | j|tjdI dH 4 I dH .}|r>|jdk r>td|j d| j||tj	| 
|||d	I dH  W d  I dH  dS 1 I dH saw   Y  dS )
z.Sends a create command with the given options.re   encryptedFieldssizer   N   zDriver support of Queryable Encryption is incompatible with server. Upgrade server to use Queryable Encryption. Got maxWireVersion z. but need maxWireVersion >= 21 (MongoDB >=7.0))ri   rk   r   ro   )floatupdater   r<   CREATEmax_wire_versionr,   r   r>   PRIMARYr   )	r   rc   r   r   ro   r   r   r   r   rV   rV   rW   _create_helper}  s0   

 .zAsyncCollection._create_helperc                   s   t |dd }|dd }|r\td| dddiddi}| jt|| j|d |dd	I d H  | t|| j|d |I d H  | j| j||||d
I d H  | dt	fg|I d H  d S | | j|||I d H  d S )Nr   r   r   clusteredIndex_idrN   T)keyunique)r   )r   __safeContent__)
r)   popr   validate_is_mappingr   r+   r   r*   create_indexr   )r   r   ro   r   r   optsrV   rV   rW   r     s*   

zAsyncCollection._createrequests!Sequence[_WriteOp[_DocumentType]]orderedbypass_document_validationletOptional[Mapping]r@   c              	     s   t d| t| ||||d}|D ]}z|| W q ty*   t|ddw | |}	||	|tj	I dH }
|
durDt
|
dS t
i dS )a  Send a batch of write operations to the server.

        Requests are passed as a list of write operation instances (
        :class:`~pymongo.operations.InsertOne`,
        :class:`~pymongo.operations.UpdateOne`,
        :class:`~pymongo.operations.UpdateMany`,
        :class:`~pymongo.operations.ReplaceOne`,
        :class:`~pymongo.operations.DeleteOne`, or
        :class:`~pymongo.operations.DeleteMany`).

          >>> async for doc in db.test.find({}):
          ...     print(doc)
          ...
          {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')}
          {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
          >>> # DeleteMany, UpdateOne, and UpdateMany are also available.
          ...
          >>> from pymongo import InsertOne, DeleteOne, ReplaceOne
          >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}),
          ...             ReplaceOne({'w': 1}, {'z': 1}, upsert=True)]
          >>> result = await db.test.bulk_write(requests)
          >>> result.inserted_count
          1
          >>> result.deleted_count
          1
          >>> result.modified_count
          0
          >>> result.upserted_ids
          {2: ObjectId('54f62ee28891e756a6e1abd5')}
          >>> async for doc in db.test.find({}):
          ...     print(doc)
          ...
          {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')}
          {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')}
          {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')}

        :param requests: A list of write operations (see examples above).
        :param ordered: If ``True`` (the default) requests will be
            performed on the server serially, in the order provided. If an error
            occurs all remaining operations are aborted. If ``False`` requests
            will be performed on the server in arbitrary order, possibly in
            parallel, and all operations will be attempted.
        :param bypass_document_validation: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").

        :return: An instance of :class:`~pymongo.results.BulkWriteResult`.

        .. seealso:: :ref:`writes-and-ids`

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

        .. versionchanged:: 4.1
           Added ``comment`` parameter.
           Added ``let`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.2
          Added bypass_document_validation support

        .. versionadded:: 3.0
        r  )r   r  z is not a valid requestNTF)r   validate_listr#   _add_to_bulkr   r   r   executer<   INSERTr@   )r   r  r
  r  ro   r   r  blkrequestrk   bulk_api_resultrV   rV   rW   
bulk_write  s   S


zAsyncCollection.bulk_writedocop_idbypass_doc_valc           
        s|   pj j}j||gd|dur|d< d fdd}	jjj||	|tjdI dH  t|t	s<|
dS dS )z0Internal helper for inserting a single document.)insertr
  	documentsNr   ro   rp   r   r\   r   r   rr   rs   c              	     sF    d ur	 d< |j jjj| jj|dI d H }t| d S )NbypassDocumentValidationrk   rg   ro   r   r   )r   r   rc   r   r   r0   )ro   r   r   resultr  r   r   rk   rV   rW   _insert_command.  s   
z4AsyncCollection._insert_one.<locals>._insert_commandr   r   )ro   rp   r   r\   r   r   rr   rs   )rk   acknowledgedrc   r   r   _retryable_writer<   r  r   r   r   )
r   r  r
  rk   r  r  ro   r   r   r  rV   r  rW   _insert_one  s   



zAsyncCollection._insert_onedocument%Union[_DocumentType, RawBSONDocument]rC   c              
     sZ   t d| t|tsd|v st |d< | |}t| j|d|d|||dI dH |jS )aZ  Insert a single document.

          >>> await db.test.count_documents({'x': 1})
          0
          >>> result = await db.test.insert_one({'x': 1})
          >>> result.inserted_id
          ObjectId('54f112defba522406c9cc208')
          >>> await db.test.find_one({'x': 1})
          {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')}

        :param document: The document to insert. Must be a mutable mapping
            type. If the document does not have an _id field one will be
            added automatically.
        :param bypass_document_validation: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.

        :return: - An instance of :class:`~pymongo.results.InsertOneResult`.

        .. seealso:: :ref:`writes-and-ids`

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

        .. versionchanged:: 4.1
           Added ``comment`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.2
          Added bypass_document_validation support

        .. versionadded:: 3.0
        r#  r   TN)r
  rk   r  r  ro   r   )	r   validate_is_document_typer   r   r   r   rC   r"  r   )r   r#  r  ro   r   rk   rV   rV   rW   
insert_oneH  s"   .


	zAsyncCollection.insert_oner  /Iterable[Union[_DocumentType, RawBSONDocument]]rB   c           	        s   t  tjrt  tjs stdg d fdd}| |}t| |||d}t| |_|	||t
jI dH  t|jS )	ab  Insert an iterable of documents.

          >>> await db.test.count_documents({})
          0
          >>> result = await db.test.insert_many([{'x': i} for i in range(2)])
          >>> await result.inserted_ids
          [ObjectId('54f113fffba522406c9cc20e'), ObjectId('54f113fffba522406c9cc20f')]
          >>> await db.test.count_documents({})
          2

        :param documents: A iterable of documents to insert.
        :param ordered: If ``True`` (the default) documents will be
            inserted on the server serially, in the order provided. If an error
            occurs all remaining inserts are aborted. If ``False``, documents
            will be inserted on the server in arbitrary order, possibly in
            parallel, and all document inserts will be attempted.
        :param bypass_document_validation: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.

        :return: An instance of :class:`~pymongo.results.InsertManyResult`.

        .. seealso:: :ref:`writes-and-ids`

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

        .. versionchanged:: 4.1
           Added ``comment`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.2
          Added bypass_document_validation support

        .. versionadded:: 3.0
        z"documents must be a non-empty listrr   'Iterator[tuple[int, Mapping[str, Any]]]c                  3  sR     D ]#} t d|  t| ts d| vrt | d< | d  tj| fV  qdS )z6A generator that validates documents and handles _ids.r#  r   N)r   r%  r   r   r   appendr    _INSERT)r#  r  inserted_idsrV   rW   gen  s   

z(AsyncCollection.insert_many.<locals>.gen)r   N)rr   r(  )r   r   r
   r   r   r   r#   listopsr  r<   r  rB   r   )	r   r  r
  r  ro   r   r-  rk   r  rV   r+  rW   insert_many  s   
4


zAsyncCollection.insert_manycriteria#Union[Mapping[str, Any], _Pipeline]upsertmultiarray_filters%Optional[Sequence[Mapping[str, Any]]]hintOptional[_IndexKeyHint]sortc              	     s  t d| t|
}
|p| j}|j}||||d}|
dur'|s#td|
|d< |dur5|s1td||d< |durR|sD|jdk rDtd	t|tsNt	|}||d
< |durk|sa|jdk ratdt
d| ||d< | j||gd}|durt
d| ||d< |dur||d< |	dur|	|d< |j| jj||| j|| jj|dI dH  }t| |drd|vrd|d< nd|d< d|v r|d d d |d< |sdS |S )!Internal update / replace helper.r3  )qur4  r3  N3Collation is unsupported for unacknowledged writes.r   6arrayFilters is unsupported for unacknowledged writes.arrayFilters   zPMust be connected to MongoDB 4.2+ to use hint on unacknowledged update commands.r7     zPMust be connected to MongoDB 8.0+ to use sort on unacknowledged update commands.r9  )r   r
  updatesr  r   r  r  nupsertedTupdatedExistingFr   r   )rK   r)   rk   r   r,   r   r   rd   r   _index_documentr   r  rc   r   r   r   r   copyr0   r   )r   r   r1  r#  r3  r4  rk   r  r
  r  r   r5  r7  ro   r   r  r9  r   r   
update_docr   r  rV   rV   rW   _update  sz   




	
zAsyncCollection._updatec                   sT   d 	
fd	d
}j jpjjo" |||I dH S )r:  ro   rp   r   r\   r   r   rr   r   c                   s8   j |f	
 | |dI d H S )N)r3  r4  rk   r  r
  r  r   r5  r7  ro   r   r  r9  r   )rI  ro   r   r   r5  r  r   r   r1  r#  r7  r  r4  r  r
  r   r9  r3  rk   rV   rW   rI  H  s*   z2AsyncCollection._update_retryable.<locals>._updateN)ro   rp   r   r\   r   r   rr   r   )r   r   r!  rk   r   )r   r1  r#  r   r3  r4  rk   r  r
  r  r   r5  r7  ro   r  r9  r   rI  rV   rK  rW   _update_retryable3  s   *
z!AsyncCollection._update_retryablefilterreplacementrD   c                   sh   t d| t | |durt d| | |}t| j||tj||||||||	|
dI dH |jS )aE  Replace a single document matching the filter.

          >>> async for doc in db.test.find({}):
          ...     print(doc)
          ...
          {'x': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')}
          >>> result = await db.test.replace_one({'x': 1}, {'y': 1})
          >>> result.matched_count
          1
          >>> result.modified_count
          1
          >>> async for doc in db.test.find({}):
          ...     print(doc)
          ...
          {'y': 1, '_id': ObjectId('54f4c5befba5220aa4d6dee7')}

        The *upsert* option can be used to insert a new document if a matching
        document does not exist.

          >>> result = await db.test.replace_one({'x': 1}, {'x': 1}, True)
          >>> result.matched_count
          0
          >>> result.modified_count
          0
          >>> result.upserted_id
          ObjectId('54f11e5c8891e756a6e1abd4')
          >>> await db.test.find_one({'x': 1})
          {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')}

        :param filter: A query that matches the document to replace.
        :param replacement: The new document.
        :param upsert: If ``True``, perform an insert if no documents
            match the filter.
        :param bypass_document_validation: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.2 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.
        :param sort: Specify which document the operation updates if the query matches
            multiple documents. The first document matched by the sort order will be updated.
            This option is only supported on MongoDB 8.0 and above.
        :return: - An instance of :class:`~pymongo.results.UpdateResult`.

        .. versionchanged:: 4.11
           Added ``sort`` parameter.
        .. versionchanged:: 4.1
           Added ``let`` parameter.
           Added ``comment`` parameter.
        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
          Added the `collation` option.
        .. versionchanged:: 3.2
          Added bypass_document_validation support.

        .. versionadded:: 3.0
        rM  Nr  )rk   r  r   r7  ro   r  r9  r   )	r   r  validate_ok_for_replacer   rD   rL  r<   UPDATEr   )r   rM  rN  r3  r  r   r7  ro   r  r9  r   rk   rV   rV   rW   replace_onef  s.   V


zAsyncCollection.replace_oner   c                   sb   t d| t | t d| | |}t| j||tj||||||||	|
|dI dH |j	S )a  Update a single document matching the filter.

          >>> async for doc in db.test.find():
          ...     print(doc)
          ...
          {'x': 1, '_id': 0}
          {'x': 1, '_id': 1}
          {'x': 1, '_id': 2}
          >>> result = await db.test.update_one({'x': 1}, {'$inc': {'x': 3}})
          >>> result.matched_count
          1
          >>> result.modified_count
          1
          >>> async for doc in db.test.find():
          ...     print(doc)
          ...
          {'x': 4, '_id': 0}
          {'x': 1, '_id': 1}
          {'x': 1, '_id': 2}

        If ``upsert=True`` and no documents match the filter, create a
        new document based on the filter criteria and update modifications.

          >>> result = await db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True)
          >>> result.matched_count
          0
          >>> result.modified_count
          0
          >>> result.upserted_id
          ObjectId('626a678eeaa80587d4bb3fb7')
          >>> await db.test.find_one(result.upserted_id)
          {'_id': ObjectId('626a678eeaa80587d4bb3fb7'), 'x': -7}

        :param filter: A query that matches the document to update.
        :param update: The modifications to apply.
        :param upsert: If ``True``, perform an insert if no documents
            match the filter.
        :param bypass_document_validation: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`.
        :param array_filters: A list of filters specifying which
            array elements an update should apply.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.2 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param sort: Specify which document the operation updates if the query matches
            multiple documents. The first document matched by the sort order will be updated.
            This option is only supported on MongoDB 8.0 and above.
        :param comment: A user-provided comment to attach to this
            command.

        :return: - An instance of :class:`~pymongo.results.UpdateResult`.

        .. versionchanged:: 4.11
           Added ``sort`` parameter.
        .. versionchanged:: 4.1
           Added ``let`` parameter.
           Added ``comment`` parameter.
        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.9
           Added the ability to accept a pipeline as the ``update``.
        .. versionchanged:: 3.6
           Added the ``array_filters`` and ``session`` parameters.
        .. versionchanged:: 3.4
          Added the ``collation`` option.
        .. versionchanged:: 3.2
          Added ``bypass_document_validation`` support.

        .. versionadded:: 3.0
        rM  r5  )	rk   r  r   r5  r7  ro   r  r9  r   N
r   r  validate_ok_for_updatevalidate_list_or_noner   rD   rL  r<   rP  r   )r   rM  r   r3  r  r   r5  r7  ro   r  r9  r   rk   rV   rV   rW   
update_one  s.   `


zAsyncCollection.update_onec                   sb   t d| t | t d| | |}t| j||tj|d|||||||	|
dI dH |j	S )aM
  Update one or more documents that match the filter.

          >>> async for doc in db.test.find():
          ...     print(doc)
          ...
          {'x': 1, '_id': 0}
          {'x': 1, '_id': 1}
          {'x': 1, '_id': 2}
          >>> result = await db.test.update_many({'x': 1}, {'$inc': {'x': 3}})
          >>> result.matched_count
          3
          >>> result.modified_count
          3
          >>> async for doc in db.test.find():
          ...     print(doc)
          ...
          {'x': 4, '_id': 0}
          {'x': 4, '_id': 1}
          {'x': 4, '_id': 2}

        :param filter: A query that matches the documents to update.
        :param update: The modifications to apply.
        :param upsert: If ``True``, perform an insert if no documents
            match the filter.
        :param bypass_document_validation: If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`.
        :param array_filters: A list of filters specifying which
            array elements an update should apply.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.2 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.

        :return: - An instance of :class:`~pymongo.results.UpdateResult`.

        .. versionchanged:: 4.1
           Added ``let`` parameter.
           Added ``comment`` parameter.
        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.9
           Added the ability to accept a pipeline as the `update`.
        .. versionchanged:: 3.6
           Added ``array_filters`` and ``session`` parameters.
        .. versionchanged:: 3.4
          Added the `collation` option.
        .. versionchanged:: 3.2
          Added bypass_document_validation support.

        .. versionadded:: 3.0
        rM  r5  T)	r4  rk   r  r   r5  r7  ro   r  r   NrR  )r   rM  r   r3  r5  r  r   r7  ro   r  r   rk   rV   rV   rW   update_manyK  s.   M


zAsyncCollection.update_manyc                   sB   | j j| j j| j| j| j| j}|j| j	|||dI dH  dS )az  Alias for :meth:`~pymongo.asynchronous.database.AsyncDatabase.drop_collection`.

        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param encrypted_fields: **(BETA)** Document that describes the encrypted fields for
            Queryable Encryption.

        The following two calls are equivalent:

          >>> await db.foo.drop()
          >>> await db.drop_collection("foo")

        .. versionchanged:: 4.2
           Added ``encrypted_fields`` parameter.

        .. versionchanged:: 4.1
           Added ``comment`` parameter.

        .. versionchanged:: 3.7
           :meth:`drop` now respects this :class:`AsyncCollection`'s :attr:`write_concern`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        )ro   r   r   N)
r   r   get_databaserc   rg   ri   rk   rm   drop_collectionr   )r   ro   r   r   dborV   rV   rW   drop  s    
zAsyncCollection.dropc              	     s   t d| |p| j}|j}|t| d}t|}|dur)|s%td||d< |durF|s8|jdk r8tdt|t	sBt
|}||d< | j||gd	}|dur\t d
| ||d
< |durd||d< |j| jj||| j|	| jj|
dI dH }t| |S )Internal delete helper.rM  )r;  limitNr=  r   	   zPMust be connected to MongoDB 4.4+ to use hint on unacknowledged delete commands.r7  )deleter
  deletesr  r   r  )r   r  rk   r   r   r)   r,   r   r   rd   r   rF  rc   r%  r   r   r   r   r0   )r   r   r1  r4  rk   r  r
  r   r7  ro   r   r  r   r   
delete_docr   r  rV   rV   rW   _delete  sF   


	zAsyncCollection._deletec                   sN   d 	f
d	d
}j jj	pjjo ||tjdI dH S )r[  ro   rp   r   r\   r   r   rr   r   c                   s*   j |	 | |dI d H S )N)	rk   r  r
  r   r7  ro   r   r  r   )ra  rJ  
r   r   r1  r7  r  r4  r  r
  r   rk   rV   rW   ra  "  s   z2AsyncCollection._delete_retryable.<locals>._deleter   N)ro   rp   r   r\   r   r   rr   r   )r   r   r!  rk   r   r<   DELETE)r   r1  r4  rk   r  r
  r   r7  ro   r  r   ra  rV   rb  rW   _delete_retryable  s    z!AsyncCollection._delete_retryablerA   c                   4   |  |}t| j|d||||||dI dH |jS )a  Delete a single document matching the filter.

          >>> await db.test.count_documents({'x': 1})
          3
          >>> result = await db.test.delete_one({'x': 1})
          >>> result.deleted_count
          1
          >>> await db.test.count_documents({'x': 1})
          2

        :param filter: A query that matches the document to delete.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.

        :return: - An instance of :class:`~pymongo.results.DeleteResult`.

        .. versionchanged:: 4.1
           Added ``let`` parameter.
           Added ``comment`` parameter.
        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
          Added the `collation` option.
        .. versionadded:: 3.0
        Frk   r   r7  ro   r  r   Nr   rA   rd  r   r   rM  r   r7  ro   r  r   rk   rV   rV   rW   
delete_one;     
2

zAsyncCollection.delete_onec                   re  )a  Delete one or more documents matching the filter.

          >>> await db.test.count_documents({'x': 1})
          3
          >>> result = await db.test.delete_many({'x': 1})
          >>> result.deleted_count
          3
          >>> await db.test.count_documents({'x': 1})
          0

        :param filter: A query that matches the documents to delete.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.

        :return: - An instance of :class:`~pymongo.results.DeleteResult`.

        .. versionchanged:: 4.1
           Added ``let`` parameter.
           Added ``comment`` parameter.
        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
          Added the `collation` option.
        .. versionadded:: 3.0
        Trf  Nrg  rh  rV   rV   rW   delete_many|  rj  zAsyncCollection.delete_manyOptional[_DocumentType]c                   sZ   |durt |tjsd|i}| j|g|R i |}|d2 z	3 dH W }|  S 6 dS )az  Get a single document from the database.

        All arguments to :meth:`find` are also valid arguments for
        :meth:`find_one`, although any `limit` argument will be
        ignored. Returns a single document, or ``None`` if no matching
        document is found.

        The :meth:`find_one` method obeys the :attr:`read_preference` of
        this :class:`AsyncCollection`.

        :param filter: a dictionary specifying
            the query to be performed OR any other type to be used as
            the value for a query for ``"_id"``.

        :param args: any additional positional arguments
            are the same as the arguments to :meth:`find`.

        :param kwargs: any additional keyword arguments
            are the same as the arguments to :meth:`find`.

            :: code-block: python

              >>> await collection.find_one(max_time_ms=100)

        Nr   r|   )r   r   r   findr\  )r   rM  r   rq   cursorr  rV   rV   rW   find_one  s   zAsyncCollection.find_oneAsyncCursor[_DocumentType]c                 O  s   t | g|R i |S )a)  Query the database.

        The `filter` argument is a query document that all results
        must match. For example:

        >>> db.test.find({"hello": "world"})

        only matches documents that have a key "hello" with value
        "world".  Matches can have other keys *in addition* to
        "hello". The `projection` argument is used to specify a subset
        of fields that should be included in the result documents. By
        limiting results to a certain subset of fields you can cut
        down on network traffic and decoding time.

        Raises :class:`TypeError` if any of the arguments are of
        improper type. Returns an instance of
        :class:`~pymongo.asynchronous.cursor.AsyncCursor` corresponding to this query.

        The :meth:`find` method obeys the :attr:`read_preference` of
        this :class:`AsyncCollection`.

        :param filter: A query document that selects which documents
            to include in the result set. Can be an empty document to include
            all documents.
        :param projection: a list of field names that should be
            returned in the result set or a dict specifying the fields
            to include or exclude. If `projection` is a list "_id" will
            always be returned. Use a dict to exclude fields from
            the result (e.g. projection={'_id': False}).
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param skip: the number of documents to omit (from
            the start of the result set) when returning the results
        :param limit: the maximum number of results to
            return. A limit of 0 (the default) is equivalent to setting no
            limit.
        :param no_cursor_timeout: if False (the default), any
            returned cursor is closed by the server after 10 minutes of
            inactivity. If set to True, the returned cursor will never
            time out on the server. Care should be taken to ensure that
            cursors with no_cursor_timeout turned on are properly closed.
        :param cursor_type: the type of cursor to return. The valid
            options are defined by :class:`~pymongo.cursor.CursorType`:

            - :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of
              this find call will return a standard cursor over the result set.
            - :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this
              find call will be a tailable cursor - tailable cursors are only
              for use with capped collections. They are not closed when the
              last data is retrieved but are kept open and the cursor location
              marks the final document position. If more data is received
              iteration of the cursor will continue from the last document
              received. For details, see the `tailable cursor documentation
              <https://www.mongodb.com/docs/manual/core/tailable-cursors/>`_.
            - :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result
              of this find call will be a tailable cursor with the await flag
              set. The server will wait for a few seconds after returning the
              full result set so that it can capture and return additional data
              added during the query.
            - :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this
              find call will be an exhaust cursor. MongoDB will stream batched
              results to the client without waiting for the client to request
              each batch, reducing latency. See notes on compatibility below.

        :param sort: a list of (key, direction) pairs
            specifying the sort order for this query. See
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.sort` for details.
        :param allow_partial_results: if True, mongos will return
            partial results if some shards are down instead of returning an
            error.
        :param oplog_replay: **DEPRECATED** - if True, set the
            oplogReplay query flag. Default: False.
        :param batch_size: Limits the number of documents returned in
            a single batch.
        :param collation: An instance of
            :class:`~pymongo.collation.Collation`.
        :param return_key: If True, return only the index keys in
            each document.
        :param show_record_id: If True, adds a field ``$recordId`` in
            each document with the storage engine's internal record identifier.
        :param snapshot: **DEPRECATED** - If True, prevents the
            cursor from returning a document more than once because of an
            intervening write operation.
        :param hint: An index, in the same format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). Pass this as an alternative to calling
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.hint` on the cursor to tell Mongo the
            proper index to use for the query.
        :param 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. Pass
            this as an alternative to calling
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.max_time_ms` on the cursor.
        :param max_scan: **DEPRECATED** - The maximum number of
            documents to scan. Pass this as an alternative to calling
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.max_scan` on the cursor.
        :param min: A list of field, limit pairs specifying the
            inclusive lower bound for all keys of a specific index in order.
            Pass this as an alternative to calling
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.min` on the cursor. ``hint`` must
            also be passed to ensure the query utilizes the correct index.
        :param max: A list of field, limit pairs specifying the
            exclusive upper bound for all keys of a specific index in order.
            Pass this as an alternative to calling
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.max` on the cursor. ``hint`` must
            also be passed to ensure the query utilizes the correct index.
        :param comment: A string to attach to the query to help
            interpret and trace the operation in the server logs and in profile
            data. Pass this as an alternative to calling
            :meth:`~pymongo.asynchronous.cursor.AsyncCursor.comment` on the cursor.
        :param 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. The option has no effect if
            MongoDB can satisfy the specified sort using an index, or if the
            blocking sort requires less memory than the 100 MiB limit. This
            option is only supported on MongoDB 4.4 and above.

        .. note:: There are a number of caveats to using
          :attr:`~pymongo.cursor.CursorType.EXHAUST` as cursor_type:

          - The `limit` option can not be used with an exhaust cursor.

          - Exhaust cursors are not supported by mongos and can not be
            used with a sharded cluster.

          - A :class:`~pymongo.cursor.AsyncCursor` instance created with the
            :attr:`~pymongo.cursor.CursorType.EXHAUST` cursor_type requires an
            exclusive :class:`~socket.socket` connection to MongoDB. If the
            :class:`~pymongo.asynchronous.cursor.AsyncCursor` is discarded without being
            completely iterated the underlying :class:`~socket.socket`
            connection will be closed and discarded without being returned to
            the connection pool.

        .. versionchanged:: 4.0
           Removed the ``modifiers`` option.
           Empty projections (eg {} or []) are passed to the server as-is,
           rather than the previous behavior which substituted in a
           projection of ``{"_id": 1}``. This means that an empty projection
           will now return the entire document, not just the ``"_id"`` field.

        .. versionchanged:: 3.11
           Added the ``allow_disk_use`` option.
           Deprecated the ``oplog_replay`` option. Support for this option is
           deprecated in MongoDB 4.4. The query engine now automatically
           optimizes queries against the oplog without requiring this
           option to be set.

        .. versionchanged:: 3.7
           Deprecated the ``snapshot`` option, which is deprecated in MongoDB
           3.6 and removed in MongoDB 4.0.
           Deprecated the ``max_scan`` option. Support for this option is
           deprecated in MongoDB 4.0. Use ``max_time_ms`` instead to limit
           server-side execution time.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.5
           Added the options ``return_key``, ``show_record_id``, ``snapshot``,
           ``hint``, ``max_time_ms``, ``max_scan``, ``min``, ``max``, and
           ``comment``.
           Deprecated the ``modifiers`` option.

        .. versionchanged:: 3.4
           Added support for the ``collation`` option.

        .. versionchanged:: 3.0
           Changed the parameter names ``spec``, ``fields``, ``timeout``, and
           ``partial`` to ``filter``, ``projection``, ``no_cursor_timeout``,
           and ``allow_partial_results`` respectively.
           Added the ``cursor_type``, ``oplog_replay``, and ``modifiers``
           options.
           Removed the ``network_timeout``, ``read_preference``, ``tag_sets``,
           ``secondary_acceptable_latency_ms``, ``max_scan``, ``snapshot``,
           ``tailable``, ``await_data``, ``exhaust``, ``as_class``, and
           slave_okay parameters.
           Removed ``compile_re`` option: PyMongo now always
           represents BSON regular expressions as :class:`~bson.regex.Regex`
           objects. Use :meth:`~bson.regex.Regex.try_compile` to attempt to
           convert from a BSON regular expression to a Python regular
           expression object.
           Soft deprecated the ``manipulate`` option.

        .. seealso:: The MongoDB documentation on `find <https://dochub.mongodb.org/core/find>`_.
        )r'   r   rV   rV   rW   rm    s    ;zAsyncCollection.find"AsyncRawBatchCursor[_DocumentType]c                 O  s(   | j jjr	tdt| g|R i |S )a  Query the database and retrieve batches of raw BSON.

        Similar to the :meth:`find` method but returns a
        :class:`~pymongo.asynchronous.cursor.AsyncRawBatchCursor`.

        This example demonstrates how to work with raw batches, but in practice
        raw batches should be passed to an external library that can decode
        BSON into another data type, rather than used with PyMongo's
        :mod:`bson` module.

          >>> import bson
          >>> cursor = db.test.find_raw_batches()
          >>> async for batch in cursor:
          ...     print(bson.decode_all(batch))

        .. note:: find_raw_batches does not support auto encryption.

        .. versionchanged:: 3.12
           Instead of ignoring the user-specified read concern, this method
           now sends it to the server when connected to MongoDB 3.6+.

           Added session support.

        .. versionadded:: 3.6
        z1find_raw_batches does not support auto encryption)r   r   
_encrypterr.   r(   r   rV   rV   rW   find_raw_batches  s   
z AsyncCollection.find_raw_batchesdict[str, Any]Optional[Collation]c              	     s0   | j |||| j| j||dI dH }t|d S )zInternal count command helper.)ri   rg   rm   r   ro   NrC  )r   r   rm   r   )r   ro   r   ri   r   r   resrV   rV   rW   
_count_cmd  s   		zAsyncCollection._count_cmdc              
     sP   | j |||dg| j| j||dI dH }d|vrdS |d d }|r&|d S dS )zAInternal helper to run an aggregate that returns a single result.   )r   rg   rm   r   ro   Nrn  
firstBatchr   )r   r   rm   )r   r   ri   r   r   ro   r  batchrV   rV   rW   _aggregate_one_result  s   	z%AsyncCollection._aggregate_one_resultc                   sJ   d v r	t d|dur| d< d fdd}j|dtjdI dH S )a  Get an estimate of the number of documents in this collection using
        collection metadata.

        The :meth:`estimated_document_count` method is **not** supported in a
        transaction.

        All optional parameters should be passed as keyword arguments
        to this method. Valid options include:

          - `maxTimeMS` (int): The maximum amount of time to allow this
            operation to run, in milliseconds.

        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: See list of options above.

        .. versionchanged:: 4.2
           This method now always uses the `count`_ command. Due to an oversight in versions
           5.0.0-5.0.8 of MongoDB, the count command was not included in V1 of the
           :ref:`versioned-api-ref`. Users of the Stable API with estimated_document_count are
           recommended to upgrade their server version to 5.0.9+ or set
           :attr:`pymongo.server_api.ServerApi.strict` to ``False`` to avoid encountering errors.

        .. versionadded:: 3.7
        .. _count: https://mongodb.com/docs/manual/reference/command/count/
        ro   z2estimated_document_count does not support sessionsNr   rp   _serverr]   r   r\   ri   rj   rr   r   c                   s0   dj i}|  j| |||d dI d H S )Ncount)r   )r   r   rw  )ro   r|  r   ri   r   rq   r   rV   rW   _cmd  s   

z6AsyncCollection.estimated_document_count.<locals>._cmdr   
ro   rp   r|  r]   r   r\   ri   rj   rr   r   )r,   _retryable_non_cursor_readr<   COUNT)r   r   rq   r  rV   r~  rW   estimated_document_count  s   
z(AsyncCollection.estimated_document_countc                   s   d|ig}d|v r| d|di d|v r"| d|di |dur*||d< | dd	d
d	idi j|i d d|v rQt|d tsQt|d |d< t|dd | d fdd}	||t
jI dH S )a
  Count the number of documents in this collection.

        .. note:: For a fast count of the total documents in a collection see
           :meth:`estimated_document_count`.

        The :meth:`count_documents` method is supported in a transaction.

        All optional parameters should be passed as keyword arguments
        to this method. Valid options include:

          - `skip` (int): The number of matching documents to skip before
            returning results.
          - `limit` (int): The maximum number of documents to count. Must be
            a positive integer. If not provided, no limit is imposed.
          - `maxTimeMS` (int): The maximum amount of time to allow this
            operation to run, in milliseconds.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.
          - `hint` (string or list of tuples): The index to use. Specify either
            the index name as a string or the index specification as a list of
            tuples (e.g. [('a', pymongo.ASCENDING), ('b', pymongo.ASCENDING)]).

        The :meth:`count_documents` method obeys the :attr:`read_preference` of
        this :class:`AsyncCollection`.

        .. note:: When migrating from :meth:`count` to :meth:`count_documents`
           the following query operators must be replaced:

           +-------------+-------------------------------------+
           | Operator    | Replacement                         |
           +=============+=====================================+
           | $where      | `$expr`_                            |
           +-------------+-------------------------------------+
           | $near       | `$geoWithin`_ with `$center`_       |
           +-------------+-------------------------------------+
           | $nearSphere | `$geoWithin`_ with `$centerSphere`_ |
           +-------------+-------------------------------------+

        :param filter: A query document that selects which documents
            to count in the collection. Can be an empty document to count all
            documents.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: See list of options above.


        .. versionadded:: 3.7

        .. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/
        .. _$geoWithin: https://mongodb.com/docs/manual/reference/operator/query/geoWithin/
        .. _$center: https://mongodb.com/docs/manual/reference/operator/query/center/
        .. _$centerSphere: https://mongodb.com/docs/manual/reference/operator/query/centerSphere/
        z$matchskipz$skipr\  z$limitNr   z$grouprN   z$sum)r   rC  )	aggregater   rn  r7  r   ro   rp   r|  r]   r   r\   ri   rj   rr   r   c                   s*    || | I d H }|sdS |d S )Nr   rC  )r{  )ro   r|  r   ri   r  r   r   r   rV   rW   r  `  s   

z-AsyncCollection.count_documents.<locals>._cmdr  )r)  r  r   r   rd   r   rF  r)   r   r  r<   r  )r   rM  ro   r   rq   r   r  rV   r  rW   count_documents  s    
>
zAsyncCollection.count_documentsfuncpCallable[[Optional[AsyncClientSession], Server, AsyncConnection, Optional[_ServerMode]], Coroutine[Any, Any, T]]rL   c              	     sh   | j j}||4 I dH }||| |||I dH W  d  I dH  S 1 I dH s-w   Y  dS )z;Non-cursor read helper to handle implicit session creation.N)r   r   r   _retryable_readr   )r   r  ro   r   r   r   rV   rV   rW   r  o  s
   
0z*AsyncCollection._retryable_non_cursor_readindexesSequence[IndexModel]	list[str]c                   s8   t d| |dur||d< | j||fi |I dH S )a  Create one or more indexes on this collection.

          >>> from pymongo import IndexModel, ASCENDING, DESCENDING
          >>> index1 = IndexModel([("hello", DESCENDING),
          ...                      ("world", ASCENDING)], name="hello_world")
          >>> index2 = IndexModel([("goodbye", DESCENDING)])
          >>> await db.test.create_indexes([index1, index2])
          ["hello_world", "goodbye_-1"]

        :param indexes: A list of :class:`~pymongo.operations.IndexModel`
            instances.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.




        .. note:: The :attr:`~pymongo.asynchronous.collection.AsyncCollection.write_concern` of
           this collection is automatically applied to this operation.

        .. versionchanged:: 3.6
           Added ``session`` parameter. Added support for arbitrary keyword
           arguments.

        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4.
        .. versionadded:: 3.0

        .. _createIndexes: https://mongodb.com/docs/manual/reference/command/createIndexes/
        r  Nr   )r   r  _create_indexes)r   r  ro   r   rq   rV   rV   rW   create_indexes}  s
   *zAsyncCollection.create_indexesc              	     s   g | j |tjdI dH 4 I dH C}|jdk}d fdd}| jt| d}|| d	|v r8|s8td
| j||t	j
t| ||dI dH  W d  I dH  S 1 I dH s[w   Y  S )ay  Internal createIndexes helper.

        :param indexes: A list of :class:`~pymongo.operations.IndexModel`
            instances.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param kwargs: optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.
        r   Nr]  rr   Iterator[Mapping[str, Any]]c                  3  sB     D ]} t | tst| d| j}|d  |V  qd S )Nz4 is not an instance of pymongo.operations.IndexModelrc   )r   r4   r   r#  r)  )indexr#  r  namesrV   rW   gen_indexes  s   
z4AsyncCollection._create_indexes.<locals>.gen_indexes)createIndexesr  commitQuorumzRMust be connected to MongoDB 4.4+ to use the commitQuorum option for createIndexes)ri   rg   rk   ro   rr   r  )r   r<   CREATE_INDEXESr   rc   r.  r   r,   r   r>   r   r1   r   )r   r  ro   rq   r   supports_quorumr  r   rV   r  rW   r    s.    


zAsyncCollection._create_indexeskeysr:   c                   s\   i }d|v r| d|d< |dur||d< t|fi |}| j|g|fi |I dH d S )af  Creates an index on this collection.

        Takes either a single key or a list containing (key, direction) pairs
        or keys.  If no direction is given, :data:`~pymongo.ASCENDING` will
        be assumed.
        The key(s) must be an instance of :class:`str` and the direction(s) must
        be one of (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
        :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOSPHERE`,
        :data:`~pymongo.HASHED`, :data:`~pymongo.TEXT`).

        To create a single key ascending index on the key ``'mike'`` we just
        use a string argument::

          >>> await my_collection.create_index("mike")

        For a compound index on ``'mike'`` descending and ``'eliot'``
        ascending we need to use a list of tuples::

          >>> await my_collection.create_index([("mike", pymongo.DESCENDING),
          ...                             "eliot"])

        All optional index creation parameters should be passed as
        keyword arguments to this method. For example::

          >>> await my_collection.create_index([("mike", pymongo.DESCENDING)],
          ...                            background=True)

        Valid options include, but are not limited to:

          - `name`: custom name to use for this index - if none is
            given, a name will be generated.
          - `unique`: if ``True``, creates a uniqueness constraint on the
            index.
          - `background`: if ``True``, this index should be created in the
            background.
          - `sparse`: if ``True``, omit from the index any documents that lack
            the indexed field.
          - `bucketSize`: for use with geoHaystack indexes.
            Number of documents to group together within a certain proximity
            to a given longitude and latitude.
          - `min`: minimum value for keys in a :data:`~pymongo.GEO2D`
            index.
          - `max`: maximum value for keys in a :data:`~pymongo.GEO2D`
            index.
          - `expireAfterSeconds`: <int> Used to create an expiring (TTL)
            collection. MongoDB will automatically delete documents from
            this collection after <int> seconds. The indexed field must
            be a UTC datetime or the data will not expire.
          - `partialFilterExpression`: A document that specifies a filter for
            a partial index.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.
          - `wildcardProjection`: Allows users to include or exclude specific
            field paths from a `wildcard index`_ using the {"$**" : 1} key
            pattern. Requires MongoDB >= 4.2.
          - `hidden`: if ``True``, this index will be hidden from the query
            planner and will not be evaluated as part of query plan
            selection. Requires MongoDB >= 4.4.

        See the MongoDB documentation for a full list of supported options by
        server version.

        .. warning:: `dropDups` is not supported by MongoDB 3.0 or newer. The
          option is silently ignored by the server and unique index builds
          using the option will fail if a duplicate value is detected.

        .. note:: The :attr:`~pymongo.asynchronous.collection.AsyncCollection.write_concern` of
           this collection is automatically applied to this operation.

        :param keys: a single key or a list of (key, direction)
            pairs specifying the index to create
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: any additional index creation
            options (see the above list) should be passed as keyword
            arguments.

        .. versionchanged:: 4.4
           Allow passing a list containing (key, direction) pairs
           or keys for the ``keys`` parameter.
        .. versionchanged:: 4.1
           Added ``comment`` parameter.
        .. versionchanged:: 3.11
           Added the ``hidden`` option.
        .. versionchanged:: 3.6
           Added ``session`` parameter. Added support for passing maxTimeMS
           in kwargs.
        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4. Support the `collation` option.
        .. versionchanged:: 3.2
           Added partialFilterExpression to support partial indexes.
        .. versionchanged:: 3.0
           Renamed `key_or_list` to `keys`. Removed the `cache_for` option.
           :meth:`create_index` no longer caches index names. Removed support
           for the drop_dups and bucket_size aliases.

        .. seealso:: The MongoDB documentation on `indexes <https://dochub.mongodb.org/core/indexes>`_.

        .. _wildcard index: https://dochub.mongodb.org/core/index-wildcard/
        	maxTimeMSNr   r   )r  r4   r  )r   r  ro   r   rq   cmd_optionsr  rV   rV   rW   r    s   n zAsyncCollection.create_indexc                   s0   |dur	||d< | j dd|i|I dH  dS )a  Drops all indexes on this collection.

        Can be used on non-existent collections or collections with no indexes.
        Raises OperationFailure on an error.

        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        .. note:: The :attr:`~pymongo.asynchronous.collection.AsyncCollection.write_concern` of
           this collection is automatically applied to this operation.

        .. versionchanged:: 3.6
           Added ``session`` parameter. Added support for arbitrary keyword
           arguments.

        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4.
        Nr   *ro   )r  _drop_index)r   ro   r   rq   rV   rV   rW   drop_indexesO	  s   zAsyncCollection.drop_indexesindex_or_namec                   s"   | j |||fi |I dH  dS )a.  Drops the specified index on this collection.

        Can be used on non-existent collections or collections with no
        indexes.  Raises OperationFailure on an error (e.g. trying to
        drop an index that does not exist). `index_or_name`
        can be either an index name (as returned by `create_index`),
        or an index specifier (as passed to `create_index`). An index
        specifier should be a list of (key, direction) pairs. Raises
        TypeError if index is not an instance of (str, unicode, list).

        .. warning::

          if a custom name was used on index creation (by
          passing the `name` parameter to :meth:`create_index`) the index
          **must** be dropped by name.

        :param index_or_name: index (or name of index) to drop
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.



        .. note:: The :attr:`~pymongo.asynchronous.collection.AsyncCollection.write_concern` of
           this collection is automatically applied to this operation.


        .. versionchanged:: 3.6
           Added ``session`` parameter. Added support for arbitrary keyword
           arguments.

        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4.

        Nr  )r   r  ro   r   rq   rV   rV   rW   
drop_indexp	  s    /zAsyncCollection.drop_indexc              	     s   |}t |trt|}t |tstdt| | j|d}|| |d ur.||d< | j	|t
jdI d H 4 I d H  }| j||tjddg| ||dI d H  W d   I d H  d S 1 I d H scw   Y  d S )Nz6index_or_name must be an instance of str or list, not )dropIndexesr  r   r   ns not foundrx  )ri   r   rk   ro   )r   r.  r   _gen_index_namerd   r   r   r   r   r   r<   DROP_INDEXESr   r>   r   r   )r   r  ro   r   rq   rc   r   r   rV   rV   rW   r  	  s(   



 .zAsyncCollection._drop_index,AsyncCommandCursor[MutableMapping[str, Any]]c                   s   |  ||I dH S )a  Get a cursor over the index documents for this collection.

          >>> async for index in await db.test.list_indexes():
          ...     print(index)
          ...
          SON([('v', 2), ('key', SON([('_id', 1)])), ('name', '_id_')])

        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.

        :return: An instance of :class:`~pymongo.asynchronous.command_cursor.AsyncCommandCursor`.

        .. versionchanged:: 4.1
           Added ``comment`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionadded:: 3.0
        N)_list_indexes)r   ro   r   rV   rV   rW   list_indexes	  s   zAsyncCollection.list_indexesc              	     s   t t tttttf  j tj	d|r|
 ptj	}|d ud fdd}jj|d4 I d H }jjj|||tjdI d H W  d   I d H  S 1 I d H sZw   Y  d S )N)rg   ri   ro   rp   r|  r]   r   r\   ri   r?   rr   r  c              
     s   j i d}d ur|d< zj||| | dI d H d }W n ty= } z|jdkr. dg d}W Y d }~nd }~ww t||j| |dd}||I d H  |S )	N)listIndexesrn  r   )ro   rn  rx  r   )idry  )ro   explicit_sessionr   )r   r   r/   coder%   addressr   _maybe_pin_connection)ro   r|  r   ri   r   rn  exc
cmd_cursorrg   collr   r  r   rV   rW   r  	  s0   
z+AsyncCollection._list_indexes.<locals>._cmdFr   )
ro   rp   r|  r]   r   r\   ri   r?   rr   r  )r   r   r   r`   r   rd   r   r   r>   r   _txn_read_preferencer   r   r   r  r<   LIST_INDEXES)r   ro   r   	read_prefr  r   rV   r  rW   r  	  s   

0zAsyncCollection._list_indexesc                   s\   | j ||dI dH }i }|2 z3 dH W }t|d  |d< t|}|||d< q6 |S )a  Get information on this collection's indexes.

        Returns a dictionary where the keys are index names (as
        returned by create_index()) and the values are dictionaries
        containing information about each index. The dictionary is
        guaranteed to contain at least a single key, ``"key"`` which
        is a list of (key, direction) pairs specifying the index (as
        passed to create_index()). It will also contain any other
        metadata about the indexes, except for the ``"ns"`` and
        ``"name"`` keys, which are cleaned. Example output might look
        like this:

        >>> await db.test.create_index("x", unique=True)
        'x_1'
        >>> await db.test.index_information()
        {'_id_': {'key': [('_id', 1)]},
         'x_1': {'unique': True, 'key': [('x', 1)]}}

        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.

        .. versionchanged:: 4.1
           Added ``comment`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        )ro   r   Nr  rc   )r  r.  itemsr   r  )r   ro   r   rn  infor  rV   rV   rW   index_information
  s   "z!AsyncCollection.index_information%AsyncCommandCursor[Mapping[str, Any]]c              
     s   |du rdi ig}ndd|iig}| j ttjttd}t|t|||du|dddiid}| jj	j
|j||||j tjd	I dH S )
a  Return a cursor over search indexes for the current collection.

        :param name: If given, the name of the index to search
            for.  Only indexes with matching index names will be returned.
            If not given, all search indexes for the current collection
            will be returned.
        :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.

        :return: A :class:`~pymongo.asynchronous.command_cursor.AsyncCommandCursor` over the result
          set.

        .. note:: requires a MongoDB server version 7.0+ Atlas cluster.

        .. versionadded:: 4.5
        Nz$listSearchIndexesrc   )rg   ri   rk   rm   rn  ry  rN   )r  r   r   	retryabler   )r   r   r>   r   rI   r=   r!   r%   r   r   r  
get_cursorget_read_preference_performs_writer<   LIST_SEARCH_INDEX)r   rc   ro   r   rq   r   r  r   rV   rV   rW   list_search_indexes6
  s4   

z#AsyncCollection.list_search_indexesmodel*Union[Mapping[str, Any], SearchIndexModel]c                   s<   t |tstdi |}| j|g||fi |I dH d S )a  Create a single search index for the current collection.

        :param model: The model for the new search index.
            It can be given as a :class:`~pymongo.operations.SearchIndexModel`
            instance or a dictionary with a model "definition"  and optional
            "name".
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the createSearchIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        :return: The name of the new search index.

        .. note:: requires a MongoDB server version 7.0+ Atlas cluster.

        .. versionadded:: 4.5
        Nr   rV   )r   r7   _create_search_indexes)r   r  ro   r   rq   rV   rV   rW   create_search_indexk
  s   
"z#AsyncCollection.create_search_indexmodelslist[SearchIndexModel]c                   s   | j |||fi |I dH S )a  Create multiple search indexes for the current collection.

        :param models: A list of :class:`~pymongo.operations.SearchIndexModel` instances.
        :param session: a :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the createSearchIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        :return: A list of the newly created search index names.

        .. note:: requires a MongoDB server version 7.0+ Atlas cluster.

        .. versionadded:: 4.5
        N)r  )r   r  ro   r   rq   rV   rV   rW   create_search_indexes
  s   z%AsyncCollection.create_search_indexesc           	   	     s   |d ur	||d< d fdd}| j t| d}|| | j|tjdI d H 4 I d H !}| j||tjt	dI d H }d	d
 |d D W  d   I d H  S 1 I d H sTw   Y  d S )Nr   rr   r  c                  3  s0     D ]} t | tst| d| jV  qd S )Nz: is not an instance of pymongo.operations.SearchIndexModel)r   r7   r   r#  )r  r  rV   rW   r  
  s   

z;AsyncCollection._create_search_indexes.<locals>.gen_indexes)createSearchIndexesr  r   )ri   rg   c                 S  s   g | ]}|d  qS )rc   rV   )rt   r  rV   rV   rW   
<listcomp>
  s    z:AsyncCollection._create_search_indexes.<locals>.<listcomp>indexesCreatedr  )
rc   r.  r   r   r<   CREATE_SEARCH_INDEXESr   r>   r   r1   )	r   r  ro   r   rq   r  r   r   resprV   r  rW   r  
  s$   
0z&AsyncCollection._create_search_indexesc              	     s   | j |d}|| |dur||d< | j|tjdI dH 4 I dH }| j||tjddgtdI dH  W d  I dH  dS 1 I dH sEw   Y  dS )a"  Delete a search index by index name.

        :param name: The name of the search index to be deleted.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the dropSearchIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        .. note:: requires a MongoDB server version 7.0+ Atlas cluster.

        .. versionadded:: 4.5
        )dropSearchIndexrc   Nr   r   r  rx  ri   r   rg   )	r   r   r   r<   DROP_SEARCH_INDEXESr   r>   r   r1   )r   rc   ro   r   rq   r   r   rV   rV   rW   drop_search_index
  s   
 .z!AsyncCollection.drop_search_index
definitionc              	     s   | j ||d}|| |dur||d< | j|tjdI dH 4 I dH }| j||tjddgtdI dH  W d  I dH  dS 1 I dH sFw   Y  dS )a  Update a search index by replacing the existing index definition with the provided definition.

        :param name: The name of the search index to be updated.
        :param definition: The new search index definition.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: optional arguments to the updateSearchIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        .. note:: requires a MongoDB server version 7.0+ Atlas cluster.

        .. versionadded:: 4.5
        )updateSearchIndexrc   r  Nr   r   r  rx  r  )	r   r   r   r<   UPDATE_SEARCH_INDEXr   r>   r   r1   )r   rc   r  ro   r   rq   r   r   rV   rV   rW   update_search_index
  s   
 .z#AsyncCollection.update_search_indexc                   s   | j j| j j| j| j| j| j}|j|d| j	i|dI dH }d}|2 z	3 dH W }|} n6 |s3i S |
di }|dus?J d|v rF|d= |S )aN  Get the options set on this collection.

        Returns a dictionary of options and their values - see
        :meth:`~pymongo.asynchronous.database.AsyncDatabase.create_collection` for more
        information on the possible options. Returns an empty
        dictionary if the collection has not been created yet.

        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        rc   )ro   rM  r   Nr   re   )r   r   rW  rc   rg   ri   rk   rm   list_collectionsr   r   )r   ro   r   rY  rn  r  r  r   rV   rV   rW   r     s.   zAsyncCollection.optionsaggregation_commandType[_AggregationCommand]rH   cursor_classType[AsyncCommandCursor]r  !AsyncCommandCursor[_DocumentType]c           
   
     s\   |d ur	||d< || |||||dddiid}	| j jj|	j|	|||	j tjdI d H S )Nr   rn  ry  rN   )r   r  )r   r   r  r  r  r  r<   	AGGREGATE)
r   r  r   r  ro   r  r  r   rq   r   rV   rV   rW   
_aggregate5  s&   

zAsyncCollection._aggregatec              	     sv   | j jj|dd4 I dH  }| jt|tf||du||d|I dH W  d  I dH  S 1 I dH s4w   Y  dS )a  Perform an aggregation using the aggregation framework on this
        collection.

        The :meth:`aggregate` method obeys the :attr:`read_preference` of this
        :class:`AsyncCollection`, except when ``$out`` or ``$merge`` are used on
        MongoDB <5.0, in which case
        :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY` is used.

        .. note:: This method does not support the 'explain' option. Please
           use `PyMongoExplain <https://pypi.org/project/pymongoexplain/>`_
           instead. An example is included in the :ref:`aggregate-examples`
           documentation.

        .. note:: The :attr:`~pymongo.asynchronous.collection.AsyncCollection.write_concern` of
           this collection is automatically applied to this operation.

        :param pipeline: a list of aggregation pipeline stages
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: A dict of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. ``"$$var"``). This option is
            only supported on MongoDB >= 5.0.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: extra `aggregate command`_ parameters.

        All optional `aggregate command`_ parameters should be passed as
        keyword arguments to this method. Valid options include, but are not
        limited to:

          - `allowDiskUse` (bool): Enables writing to temporary files. When set
            to True, aggregation stages can write data to the _tmp subdirectory
            of the --dbpath directory. The default is False.
          - `maxTimeMS` (int): The maximum amount of time to allow the operation
            to run in milliseconds.
          - `batchSize` (int): The maximum number of documents to return per
            batch. Ignored if the connected mongod or mongos does not support
            returning aggregate results using a cursor.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.
          - `bypassDocumentValidation` (bool): If ``True``, allows the write to opt-out of document level validation.


        :return: A :class:`~pymongo.asynchronous.command_cursor.AsyncCommandCursor` over the result
          set.

        .. versionchanged:: 4.1
           Added ``comment`` parameter.
           Added ``let`` parameter.
           Support $merge and $out executing on secondaries according to the
           collection's :attr:`read_preference`.
        .. versionchanged:: 4.0
           Removed the ``useCursor`` option.
        .. versionchanged:: 3.9
           Apply this collection's read concern to pipelines containing the
           `$out` stage when connected to MongoDB >= 4.2.
           Added support for the ``$merge`` pipeline stage.
           Aggregations that write always use read preference
           :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`.
        .. versionchanged:: 3.6
           Added the `session` parameter. Added the `maxAwaitTimeMS` option.
           Deprecated the `useCursor` option.
        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4. Support the `collation` option.
        .. versionchanged:: 3.0
           The :meth:`aggregate` method always returns an AsyncCommandCursor. The
           pipeline argument must be a list.

        .. seealso:: :doc:`/examples/aggregation`

        .. _aggregate command:
            https://mongodb.com/docs/manual/reference/command/aggregate
        FcloseN)ro   r  r  r   )r   r   r   r  r!   r%   )r   r   ro   r  r   rq   r   rV   rV   rW   r  U  s   T
0zAsyncCollection.aggregatec              	     s   | j jjr
td|dur||d< | j jj|dd4 I dH #}ttt | jt	|t
f||dud|I dH W  d  I dH  S 1 I dH sHw   Y  dS )ab  Perform an aggregation and retrieve batches of raw BSON.

        Similar to the :meth:`aggregate` method but returns a
        :class:`~pymongo.asynchronous.cursor.AsyncRawBatchCursor`.

        This example demonstrates how to work with raw batches, but in practice
        raw batches should be passed to an external library that can decode
        BSON into another data type, rather than used with PyMongo's
        :mod:`bson` module.

          >>> import bson
          >>> cursor = await db.test.aggregate_raw_batches([
          ...     {'$project': {'x': {'$multiply': [2, '$x']}}}])
          >>> async for batch in cursor:
          ...     print(bson.decode_all(batch))

        .. note:: aggregate_raw_batches does not support auto encryption.

        .. versionchanged:: 3.12
           Added session support.

        .. versionadded:: 3.6
        z6aggregate_raw_batches does not support auto encryptionNr   Fr  )ro   r  )r   r   rr  r.   r   r   r(   rF   r  r"   r&   )r   r   ro   r   rq   r   rV   rV   rW   aggregate_raw_batches  s(   

0z%AsyncCollection.aggregate_raw_batchesnew_namec           	   
     sv  t |tstdt| |rd|v rtd|d dks%|d dkr)tdd|v r6|d	s6td
| jj d| }| j|d}|	| |durR||d< | 
||}| j|tjdI dH 4 I dH G}| jj|4 I dH %}|jd||d|| jjdI dH W  d  I dH  W  d  I dH  S 1 I dH sw   Y  W d  I dH  dS 1 I dH sw   Y  dS )a  Rename this collection.

        If operating in auth mode, client must be authorized as an
        admin to perform this operation. Raises :class:`TypeError` if
        `new_name` is not an instance of :class:`str`.
        Raises :class:`~pymongo.errors.InvalidName`
        if `new_name` is not a valid collection name.

        :param new_name: new name for this collection
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: additional arguments to the rename command
            may be passed as keyword arguments to this helper method
            (i.e. ``dropTarget=True``)

        .. note:: The :attr:`~pymongo.asynchronous.collection.AsyncCollection.write_concern` of
           this collection is automatically applied to this operation.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4.

        z)new_name must be an instance of str, not rw   rx   r   r{   r|   z/collection names must not start or end with '.'ry   rz   z%collection names must not contain '$')renameCollectiontoNr   r   adminT)rk   r   ro   r   )r   rd   r   r   r-   r   r   rc   r   r   r   r   r<   RENAMEr   r   r   )	r   r  ro   r   rq   r   rk   r   r   rV   rV   rW   rename  s:   
$
 
.zAsyncCollection.renamer  r.  c                   s   t |tstdt| j|d |dur%d|v r!td||d< t|dd | |dur:| d< |durLt |tsHt	
|}| d< d fdd}j||tjdI dH S )aM  Get a list of distinct values for `key` among all documents
        in this collection.

        Raises :class:`TypeError` if `key` is not an instance of
        :class:`str`.

        All optional distinct parameters should be passed as keyword arguments
        to this method. Valid options include:

          - `maxTimeMS` (int): The maximum amount of time to allow the count
            command to run, in milliseconds.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`.

        The :meth:`distinct` method obeys the :attr:`read_preference` of
        this :class:`AsyncCollection`.

        :param key: name of the field for which we want to get the distinct
            values
        :param filter: A query document that specifies the documents
            from which to retrieve the distinct values.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param comment: A user-provided comment to attach to this
            command.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index`
            (e.g. ``[('field', ASCENDING)]``).
        :param kwargs: See list of options above.

        .. versionchanged:: 4.12
           Added ``hint`` parameter.

        .. versionchanged:: 3.6
           Added ``session`` parameter.

        .. versionchanged:: 3.4
           Support the `collation` option.

        z$key must be an instance of str, not )distinctr  Nqueryz can't pass both filter and queryr   r   r7  ro   rp   r|  r]   r   r\   ri   rj   rr   r.  c              	     s*   j | |j| ddidI d H d S )NvaluesrN   )ri   rm   r   ro   r   )r   rm   )ro   r|  r   ri   r  rV   rW   r  g  s   
	z&AsyncCollection.distinct.<locals>._cmdr   )
ro   rp   r|  r]   r   r\   ri   rj   rr   r.  )r   rd   r   r   r   r,   r)   r  r   r   rF  r  r<   DISTINCT)r   r  rM  ro   r   r7  rq   r  rV   r  rW   r  %  s$   
2


zAsyncCollection.distinct
projection1Optional[Union[Mapping[str, Any], Iterable[str]]]Optional[_IndexList]return_documentc
                   s  t d| t|tstdt| t|
ddj||d|	dur2t d|	 |	d< 	|
 |durCt
|dd< |durNt
|d	< |dur[td
| |d
< durittsit
|d fdd}jjjj||tjdI dH S )zInternal findAndModify helper.rM  zKreturn_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER, not r   N)findAndModifyr  newr  r  fieldsr9  r3  ro   rp   r   r\   r   r   rr   r   c              
     s   j } d ur|stdt d< d ur0|jdk r!td|s,|jdk r,tdd< j|tj| |tdI d H }t| |	d	S )
Nr>  r?  r@  zJMust be connected to MongoDB 4.2+ to use hint on find and modify commands.r]  zYMust be connected to MongoDB 4.4+ to use hint on unacknowledged find and modify commands.r7  )ri   rk   r   ro   r   r   rM   )
r   r,   r.  r   r   r>   r   _FIND_AND_MODIFY_DOC_FIELDSr0   r   )ro   r   r   r   outr5  r   r   r7  r   rk   rV   rW   _find_and_modify_helper  s<   


zAAsyncCollection._find_and_modify.<locals>._find_and_modify_helperr   )ro   rp   r   r\   r   r   rr   r   )r   r  r   r   r   r   r)   r  r   r   r   _fields_list_to_dictrF  rK   rd   r   r   r   r!  r   r<   FIND_AND_MODIFY)r   rM  r  r9  r3  r  r5  r7  ro   r  rq   r  rV   r  rW   _find_and_modify{  s<   




"z AsyncCollection._find_and_modifyrF   c           	        s>   d|d< |dur||d< | j |||f|||d|I dH S )a  Finds a single document and deletes it, returning the document.

          >>> await db.test.count_documents({'x': 1})
          2
          >>> await db.test.find_one_and_delete({'x': 1})
          {'x': 1, '_id': ObjectId('54f4e12bfba5220aa4d6dee8')}
          >>> await db.test.count_documents({'x': 1})
          1

        If multiple documents match *filter*, a *sort* can be applied.

          >>> async for doc in db.test.find({'x': 1}):
          ...     print(doc)
          ...
          {'x': 1, '_id': 0}
          {'x': 1, '_id': 1}
          {'x': 1, '_id': 2}
          >>> await db.test.find_one_and_delete(
          ...     {'x': 1}, sort=[('_id', pymongo.DESCENDING)])
          {'x': 1, '_id': 2}

        The *projection* option can be used to limit the fields returned.

          >>> await db.test.find_one_and_delete({'x': 1}, projection={'_id': False})
          {'x': 1}

        :param filter: A query that matches the document to delete.
        :param projection: a list of field names that should be
            returned in the result document or a mapping specifying the fields
            to include or exclude. If `projection` is a list "_id" will
            always be returned. Use a mapping to exclude fields from
            the result (e.g. projection={'_id': False}).
        :param sort: a list of (key, direction) pairs
            specifying the sort order for the query. If multiple documents
            match the query, they are sorted and the first is deleted.
        :param hint: An index to use to support the query predicate
            specified either by its string name, or in the same format as
            passed to :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index`
            (e.g. ``[('field', ASCENDING)]``). This option is only supported
            on MongoDB 4.4 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: additional command arguments can be passed
            as keyword arguments (for example maxTimeMS can be used with
            recent server versions).

        .. versionchanged:: 4.1
           Added ``let`` parameter.
        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.2
           Respects write concern.

        .. warning:: Starting in PyMongo 3.2, this command uses the
           :class:`~pymongo.write_concern.WriteConcern` of this
           :class:`~pymongo.asynchronous.collection.AsyncCollection` when connected to MongoDB >=
           3.2. Note that using an elevated write concern with this command may
           be slower compared to using the default write concern.

        .. versionchanged:: 3.4
           Added the `collation` option.
        .. versionadded:: 3.0
        TremoveNr   r  r7  ro   )r  )	r   rM  r  r9  r7  ro   r  r   rq   rV   rV   rW   find_one_and_delete  s   Rz#AsyncCollection.find_one_and_deletec                   sL   t | ||d< |
dur|
|d< | j|||||f|	||d|I dH S )a0  Finds a single document and replaces it, returning either the
        original or the replaced document.

        The :meth:`find_one_and_replace` method differs from
        :meth:`find_one_and_update` by replacing the document matched by
        *filter*, rather than modifying the existing document.

          >>> async for doc in db.test.find({}):
          ...     print(doc)
          ...
          {'x': 1, '_id': 0}
          {'x': 1, '_id': 1}
          {'x': 1, '_id': 2}
          >>> await db.test.find_one_and_replace({'x': 1}, {'y': 1})
          {'x': 1, '_id': 0}
          >>> async for doc in db.test.find({}):
          ...     print(doc)
          ...
          {'y': 1, '_id': 0}
          {'x': 1, '_id': 1}
          {'x': 1, '_id': 2}

        :param filter: A query that matches the document to replace.
        :param replacement: The replacement document.
        :param projection: A list of field names that should be
            returned in the result document or a mapping specifying the fields
            to include or exclude. If `projection` is a list "_id" will
            always be returned. Use a mapping to exclude fields from
            the result (e.g. projection={'_id': False}).
        :param sort: a list of (key, direction) pairs
            specifying the sort order for the query. If multiple documents
            match the query, they are sorted and the first is replaced.
        :param upsert: When ``True``, inserts a new document if no
            document matches the query. Defaults to ``False``.
        :param return_document: If
            :attr:`ReturnDocument.BEFORE` (the default),
            returns the original document before it was replaced, or ``None``
            if no document matches. If
            :attr:`ReturnDocument.AFTER`, returns the replaced
            or inserted document.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: additional command arguments can be passed
            as keyword arguments (for example maxTimeMS can be used with
            recent server versions).

        .. versionchanged:: 4.1
           Added ``let`` parameter.
        .. versionchanged:: 3.11
           Added the ``hint`` option.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
           Added the ``collation`` option.
        .. versionchanged:: 3.2
           Respects write concern.

        .. warning:: Starting in PyMongo 3.2, this command uses the
           :class:`~pymongo.write_concern.WriteConcern` of this
           :class:`~pymongo.asynchronous.collection.AsyncCollection` when connected to MongoDB >=
           3.2. Note that using an elevated write concern with this command may
           be slower compared to using the default write concern.

        .. versionadded:: 3.0
        r   Nr   r  )r   rO  r  )r   rM  rN  r  r9  r3  r  r7  ro   r  r   rq   rV   rV   rW   find_one_and_replace#  s$   
[	z$AsyncCollection.find_one_and_replacec                   sZ   t | t d| ||d< |dur||d< | j||||||f||
|	d|I dH S )a  Finds a single document and updates it, returning either the
        original or the updated document.

          >>> await db.test.find_one_and_update(
          ...    {'_id': 665}, {'$inc': {'count': 1}, '$set': {'done': True}})
          {'_id': 665, 'done': False, 'count': 25}}

        Returns ``None`` if no document matches the filter.

          >>> await db.test.find_one_and_update(
          ...    {'_exists': False}, {'$inc': {'count': 1}})

        When the filter matches, by default :meth:`find_one_and_update`
        returns the original version of the document before the update was
        applied. To return the updated (or inserted in the case of
        *upsert*) version of the document instead, use the *return_document*
        option.

          >>> from pymongo import ReturnDocument
          >>> await db.example.find_one_and_update(
          ...     {'_id': 'userid'},
          ...     {'$inc': {'seq': 1}},
          ...     return_document=ReturnDocument.AFTER)
          {'_id': 'userid', 'seq': 1}

        You can limit the fields returned with the *projection* option.

          >>> await db.example.find_one_and_update(
          ...     {'_id': 'userid'},
          ...     {'$inc': {'seq': 1}},
          ...     projection={'seq': True, '_id': False},
          ...     return_document=ReturnDocument.AFTER)
          {'seq': 2}

        The *upsert* option can be used to create the document if it doesn't
        already exist.

          >>> (await db.example.delete_many({})).deleted_count
          1
          >>> await db.example.find_one_and_update(
          ...     {'_id': 'userid'},
          ...     {'$inc': {'seq': 1}},
          ...     projection={'seq': True, '_id': False},
          ...     upsert=True,
          ...     return_document=ReturnDocument.AFTER)
          {'seq': 1}

        If multiple documents match *filter*, a *sort* can be applied.

          >>> async for doc in db.test.find({'done': True}):
          ...     print(doc)
          ...
          {'_id': 665, 'done': True, 'result': {'count': 26}}
          {'_id': 701, 'done': True, 'result': {'count': 17}}
          >>> await db.test.find_one_and_update(
          ...     {'done': True},
          ...     {'$set': {'final': True}},
          ...     sort=[('_id', pymongo.DESCENDING)])
          {'_id': 701, 'done': True, 'result': {'count': 17}}

        :param filter: A query that matches the document to update.
        :param update: The update operations to apply.
        :param projection: A list of field names that should be
            returned in the result document or a mapping specifying the fields
            to include or exclude. If `projection` is a list "_id" will
            always be returned. Use a dict to exclude fields from
            the result (e.g. projection={'_id': False}).
        :param sort: a list of (key, direction) pairs
            specifying the sort order for the query. If multiple documents
            match the query, they are sorted and the first is updated.
        :param upsert: When ``True``, inserts a new document if no
            document matches the query. Defaults to ``False``.
        :param return_document: If
            :attr:`ReturnDocument.BEFORE` (the default),
            returns the original document before it was updated. If
            :attr:`ReturnDocument.AFTER`, returns the updated
            or inserted document.
        :param array_filters: A list of filters specifying which
            array elements an update should apply.
        :param hint: An index to use to support the query
            predicate specified either by its string name, or in the same
            format as passed to
            :meth:`~pymongo.asynchronous.collection.AsyncCollection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
        :param session: a
            :class:`~pymongo.asynchronous.client_session.AsyncClientSession`.
        :param let: Map of parameter names and values. Values must be
            constant or closed expressions that do not reference document
            fields. Parameters can then be accessed as variables in an
            aggregate expression context (e.g. "$$var").
        :param comment: A user-provided comment to attach to this
            command.
        :param kwargs: additional command arguments can be passed
            as keyword arguments (for example maxTimeMS can be used with
            recent server versions).

        .. versionchanged:: 3.11
           Added the ``hint`` option.
        .. versionchanged:: 3.9
           Added the ability to accept a pipeline as the ``update``.
        .. versionchanged:: 3.6
           Added the ``array_filters`` and ``session`` options.
        .. versionchanged:: 3.4
           Added the ``collation`` option.
        .. versionchanged:: 3.2
           Respects write concern.

        .. warning:: Starting in PyMongo 3.2, this command uses the
           :class:`~pymongo.write_concern.WriteConcern` of this
           :class:`~pymongo.asynchronous.collection.AsyncCollection` when connected to MongoDB >=
           3.2. Note that using an elevated write concern with this command may
           be slower compared to using the default write concern.

        .. versionadded:: 3.0
        r5  r   Nr   )r7  r  ro   )r   rS  rT  r  )r   rM  r   r  r9  r3  r  r5  r7  ro   r  r   rq   rV   rV   rW   find_one_and_update  s*    

z#AsyncCollection.find_one_and_update)FNNNNN)ra   rb   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   ro   rp   rq   r   rr   rs   )rc   rd   rr   r   )rr   rd   )r   r   rr   r   )rr   r   )rr   r   )rr   rb   )N...)
rg   rs   ri   rj   rk   rl   rm   rn   rr   r   )...)
rg   r   ri   rj   rk   rl   rm   rn   rr   r   )NNNN)
rg   r   ri   rj   rk   rl   rm   rn   rr   r   )r   r   ro   rp   rr   rJ   )r   r   rq   r   rr   r   )NNNNNNNNNNNN)r   r   r   r   r   r   r   r   r   r   r   r   r   r   ro   rp   r   r   r   r   r   r   r   rf   rr   r   )ro   rp   r   rd   rr   r   )
NNTNNNNNFN)r   r\   r   r   ri   rj   rg   r   r   r   r   r   rm   rn   rk   rl   r   r   ro   rp   r   r   r   r   rr   r   )NF)rc   rd   r   r   r   r   ro   rp   r   r   r   r   rr   rs   )r   r   ro   rp   rr   rs   )TNNNN)r  r	  r
  r   r  rf   ro   rp   r   r   r  r  rr   r@   r   )r  r   r
  r   rk   rJ   r  r   r  rf   ro   rp   r   r   rr   r   )NNN)
r#  r$  r  rf   ro   rp   r   r   rr   rC   )TNNN)r  r'  r
  r   r  rf   ro   rp   r   r   rr   rB   )FFNNTNNNNNFNNN)$r   r\   r1  r   r#  r2  r3  r   r4  r   rk   rl   r  r   r
  r   r  rf   r   r   r5  r6  r7  r8  ro   rp   r   r   r  r   r9  r   r   r   rr   r   )FFNNTNNNNNNNN)"r1  r   r#  r2  r   rd   r3  r   r4  r   rk   rl   r  r   r
  r   r  rf   r   r   r5  r6  r7  r8  ro   rp   r  r   r9  r   r   r   rr   r   )FNNNNNNN)rM  r   rN  r   r3  r   r  rf   r   r   r7  r8  ro   rp   r  r   r9  r   r   r   rr   rD   )	FNNNNNNNN)rM  r   r   r2  r3  r   r  rf   r   r   r5  r6  r7  r8  ro   rp   r  r   r9  r   r   r   rr   rD   )rM  r   r   r2  r3  r   r5  r6  r  rf   r   r   r7  r8  ro   rp   r  r   r   r   rr   rD   )ro   rp   r   r   r   r   rr   rs   )	NNTNNNFNN)r   r\   r1  r   r4  r   rk   rl   r  r   r
  r   r   r   r7  r8  ro   rp   r   r   r  r   r   r   rr   r   )NNTNNNNN)r1  r   r4  r   rk   rl   r  r   r
  r   r   r   r7  r8  ro   rp   r  r   r   r   rr   r   )NNNNN)rM  r   r   r   r7  r8  ro   rp   r  r   r   r   rr   rA   )rM  r   r   r   rq   r   rr   rl  )r   r   rq   r   rr   rp  )r   r   rq   r   rr   rq  )ro   rp   r   r\   ri   rj   r   rt  r   ru  rr   r   )r   r\   ri   rj   r   rt  r   r   ro   rp   rr   r   )r   r   rq   r   rr   r   )NN)
rM  r   ro   rp   r   r   rq   r   rr   r   )r  r  ro   rp   r   rd   rr   rL   )
r  r  ro   rp   r   r   rq   r   rr   r  )r  r  ro   rp   rq   r   rr   r  )
r  r:   ro   rp   r   r   rq   r   rr   rd   )ro   rp   r   r   rq   r   rr   rs   )
r  r:   ro   rp   r   r   rq   r   rr   rs   )ro   rp   r   r   rr   r  )ro   rp   r   r   rr   r   )
rc   r   ro   rp   r   r   rq   r   rr   r  )
r  r  ro   rp   r   r   rq   r   rr   rd   )
r  r  ro   rp   r   r   rq   r   rr   r  )
rc   rd   ro   rp   r   r   rq   r   rr   rs   )rc   rd   r  r   ro   rp   r   r   rq   r   rr   rs   )r  r  r   rH   r  r  ro   rp   r  r   r  r   r   r   rq   r   rr   r  )r   rH   ro   rp   r  r   r   r   rq   r   rr   r  )
r   rH   ro   rp   r   r   rq   r   rr   rq  )
r  rd   ro   rp   r   r   rq   r   rr   r   )r  rd   rM  r   ro   rp   r   r   r7  r8  rq   r   rr   r.  )rM  r   r  r  r9  r  r3  rf   r  r   r5  r6  r7  r8  ro   rp   r  r  rq   r   rr   r   )NNNNNN)rM  r   r  r  r9  r  r7  r8  ro   rp   r  r   r   r   rq   r   rr   rF   )rM  r   rN  r   r  r  r9  r  r3  r   r  r   r7  r8  ro   rp   r  r   r   r   rq   r   rr   rF   )rM  r   r   r2  r  r  r9  r  r3  r   r  r   r5  r6  r7  r8  ro   rp   r  r   r   r   rq   r   rr   rF   )PrP   rQ   rR   rS   r   r   r   r   r   r   r   r   propertyr   rc   ra   r   r   r   __iter__r   nextr   r   r   r   r   r   r   applyr  r"  r&  r0  rI  rL  rQ  rU  rV  rZ  ra  rd  ri  rk  ro  rm  rs  rw  r{  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  rO   rT   r  r  r  r  __classcell__rV   rV   r   rW   r`      sX    	-
 	@#i.@Oe7q|g0<+DB# =/[//x!03,8!#&&."c0B[R]or`   )xrS   
__future__r   r   collectionsr   typingr   r   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   bson.codec_optionsr   r   bson.objectidr   bson.raw_bsonr   bson.sonr   bson.timestampr   pymongor   r   r   r   r     pymongo.asynchronous.aggregationr!   r"   pymongo.asynchronous.bulkr#   "pymongo.asynchronous.change_streamr$   #pymongo.asynchronous.command_cursorr%   r&   pymongo.asynchronous.cursorr'   r(   pymongo.collationr)   pymongo.commonr*   r+   pymongo.errorsr,   r-   r.   r/   pymongo.helpers_sharedr0   pymongo.messager1   pymongo.operationsr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   pymongo.read_concernr=   pymongo.read_preferencesr>   r?   pymongo.resultsr@   rA   rB   rC   rD   pymongo.typingsrE   rF   rG   rH   pymongo.write_concernrI   rJ   rK   r   rL   r  _WriteOprO   bsonrX   #pymongo.asynchronous.client_sessionrY   r   r[   pymongo.asynchronous.poolr\   pymongo.asynchronous.serverr]   r^   r_   
BaseObjectr`   rV   rV   rV   rW   <module>   sd   P4
