
    h`M                       d Z ddlZddlZddlmZ ddlmZ ddlmZm	Z	m
Z
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 dd
lmZmZ ddl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&m'Z' ddl(m)Z)m*Z*m+Z+m,Z,m-Z- ddl.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8m9Z9m:Z:m;Z;m<Z< ddl=m>Z> dZ?ddiZ@dZA G d deB      ZC G d dej                        ZEy) z%Collection level utilities for Mongo.    N)Code)ObjectId)_unicodeabcinteger_typesstring_type)RawBSONDocument)CodecOptions)SON)commonhelpersmessage)_CollectionAggregationCommand _CollectionRawAggregationCommand)BulkOperationBuilder_Bulk)CommandCursorRawBatchCommandCursor)ORDERED_TYPES)validate_collation_or_noneCollectionChangeStream)CursorRawBatchCursor)BulkWriteErrorConfigurationErrorInvalidNameInvalidOperationOperationFailure)_check_write_command_response_raise_last_error)_UNICODE_REPLACE_CODEC_OPTIONS)
IndexModel)ReadPreference)BulkWriteResultDeleteResultInsertOneResultInsertManyResultUpdateResult)WriteConcernz%s.%svalue   zgeoHaystack indexes are deprecated as of MongoDB 4.4. Instead, create a 2d index and use $geoNear or $geoWithin. See https://dochub.mongodb.org/core/4.4-deprecate-geoHaystackc                       e Zd ZdZdZ	 dZy)ReturnDocumentzAn enum used with
    :meth:`~pymongo.collection.Collection.find_one_and_replace` and
    :meth:`~pymongo.collection.Collection.find_one_and_update`.
    FTN)__name__
__module____qualname____doc__BEFOREAFTER     U/var/www/html/ranktracker/api/venv/lib/python3.12/site-packages/pymongo/collection.pyr.   r.   A   s     F E;r6   r.   c                   <    e Zd ZdZ	 	 	 dN fd	Zd Zd Z	 	 	 	 	 	 	 	 	 dOdZd Zd	 Z	d
 Z
d Zd Zd Zed        Zed        Zed        Z	 	 dPdZdQdZdQdZ	 	 dRdZd Zd Z	 	 	 dSdZ	 	 dTdZ	 	 dRdZ	 	 	 	 	 dUdZ	 	 	 	 	 dVdZ	 	 	 dWdZ	 	 	 	 dXdZ	 	 	 dYdZdZdZ 	 	 d[d Z!	 	 d\d!Z"d]d"Z#d]d#Z$dZd$Z%d% Z&d& Z'dZd'Z(d^d(Z)	 d^d)Z*d* Z+dZd+Z,d^d,Z-dZd-Z.d. Z/dZd/Z0d_d0Z1dZd1Z2dZd2Z3dZd3Z4dZd4Z5dZd5Z6dZd6Z7d7 Z8dZd8Z9d9 Z:	 	 	 d`d:Z;dZd;Z<dZd<Z=d^d=Z>d> Z?dTd?Z@dTd@ZAdA ZBdeCj                  dddfdBZE	 	 dPdCZFdddeCj                  ddfdDZGdddeCj                  dddfdEZHdadFZI	 	 dbdGZJ	 	 dcdHZKdddIZLi dddddfdJZMdK ZNdL ZOeOZPdM ZQ xZRS )e
CollectionzA Mongo collection.
    FNc	                    t         t        |   |xs |j                  |xs |j                  |xs |j
                  |xs |j                         t        |t              st        dt        j                        |rd|v rt        d      d|v r0|j                  d      s|j                  d      st        d|z        |d   d	k(  s|d
   d	k(  rt        d|z        d|v rt        d      t        |	j                  dd            }
|| _        t!        |      | _        t$        | j                  j&                  | j"                  fz  | _        |s|	s|
r| j+                  |	|
|       | j                  j-                  dt.              | _        y)a  Get / create a Mongo collection.

        Raises :class:`TypeError` if `name` is not an instance of
        :class:`basestring` (:class:`str` in python 3). 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.database.Database.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.

        :Parameters:
          - `database`: the database to get a collection from
          - `name`: the name of the collection to get
          - `create` (optional): if ``True``, force collection
            creation even without options being set
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) database.codec_options is used.
          - `read_preference` (optional): The read preference to use. If
            ``None`` (the default) database.read_preference is used.
          - `write_concern` (optional): An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) database.write_concern is used.
          - `read_concern` (optional): An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) database.read_concern is used.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. If a collation is provided,
            it will be passed to the create collection command. This option is
            only supported on MongoDB 3.4 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession` that is used with
            the create collection command
          - `**kwargs` (optional): additional keyword arguments will
            be passed as options for the create collection command

        .. 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.collection.Collection` no longer returns an
           instance of :class:`~pymongo.collection.Collection` for attribute
           names with leading underscores. You must use dict-style lookups
           instead::

               collection['__my_collection__']

           Not:

               collection.__my_collection__

        .. versionchanged:: 2.2
           Removed deprecated argument: options

        .. versionadded:: 2.1
           uuid_subtype attribute

        .. mongodoc:: collections
        zname must be an instance of .. collection names cannot be empty$oplog.$mainz$cmdz)collection names must not contain '$': %rr   .z3collection names must not start or end with '.': %r z4collection names must not contain the null character	collationNreplace)unicode_decode_error_handlerdocument_class)superr9   __init__codec_optionsread_preferencewrite_concernread_concern
isinstancer   	TypeErrorr/   r   
startswithr   pop_Collection__databaser   _Collection__name_UJOINname_Collection__full_name_Collection__create_replacedict)_Collection__write_response_codec_options)selfdatabaserS   createrH   rI   rJ   rK   sessionkwargsrB   	__class__s              r7   rG   zCollection.__init__R   s   Z 	j$(3X337x773X331H11		3 $,'2';';> ? ? tt|@AA$; > $ 7 0267 8 87c>T"X_ 46:; < <T> / 0 0.vzz+t/LM	"tn!T__%9%94;;$GGVyMM&)W5.2.@.@.I.I)2 /J /!+r6   c                 l    | j                   j                  j                  | j                  |      |      S N)rP   client_socket_for_reads_read_preference_forrY   r\   s     r7   rb   zCollection._socket_for_reads   s/    %%77%%g.9 	9r6   c                 L    | j                   j                  j                  |      S r`   )rP   ra   _socket_for_writesrd   s     r7   rf   zCollection._socket_for_writes   s    %%88AAr6   c                 J   | j                   j                  j                  |      5 }|j                  | j                   j                  |||xs | j                  |      |xs | j                  ||||	d|
|| j                   j                  ||      cddd       S # 1 sw Y   yxY w)a  Internal command helper.

        :Parameters:
          - `sock_info` - A SocketInfo instance.
          - `command` - The command itself, as a SON instance.
          - `slave_ok`: whether to set the SlaveOkay wire protocol bit.
          - `codec_options` (optional) - An instance of
            :class:`~bson.codec_options.CodecOptions`.
          - `check`: raise OperationFailure if there are errors
          - `allowable_errors`: errors to ignore if `check` is True
          - `read_concern` (optional) - An instance of
            :class:`~pymongo.read_concern.ReadConcern`.
          - `write_concern`: An instance of
            :class:`~pymongo.write_concern.WriteConcern`. This option is only
            valid for MongoDB 3.4 and above.
          - `collation` (optional) - An instance of
            :class:`~pymongo.collation.Collation`.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `retryable_write` (optional): True if this command is a retryable
            write.
          - `user_fields` (optional): Response fields that should be decoded
            using the TypeDecoders from codec_options, passed to
            bson._decode_all_selective.

        :Returns:
          The result document.
        T)rK   rJ   parse_write_concern_errorrB   r\   ra   retryable_writeuser_fieldsN)rP   ra   _tmp_sessioncommandrS   rc   rH   )rY   	sock_inforl   slave_okrI   rH   checkallowable_errorsrK   rJ   rB   r\   ri   rj   ss                  r7   _commandzCollection._command   s    J __##009 	)Q$$$$E4#<#<W#E3!3!3 )+*.#-- /' % )	) 	) 	)s   A)BB"c           	      8   t        d| j                  fg      }|r&d|v rt        |d         |d<   |j                  |       | j	                  |      5 }| j                  ||t        j                  | j                  |      ||       ddd       y# 1 sw Y   yxY w)z7Sends a create command with the given options.
        r[   size)rI   rJ   rB   r\   N)	r   rQ   floatupdaterf   rr   r$   PRIMARY_write_concern_for)rY   optionsrB   r\   cmdrm   s         r7   __createzCollection.__create   s     Hdkk*+, "'"8JJw$$W- 	6MM30F0F"55g>#W  6	6 	6 	6s   5BBc           	          |j                  d      r*t        | j                  |fz  }t        d|d|d|d      | j	                  |      S )zGet a sub-collection of this collection by name.

        Raises InvalidName if an invalid collection name is used.

        :Parameters:
          - `name`: the name of the collection to get
        _zCollection has no attribute z. To access the z collection, use database['z'].)rN   rR   rQ   AttributeError__getitem__)rY   rS   	full_names      r7   __getattr__zCollection.__getattr__  sQ     ??3$++t!44I  )Y01 1 %%r6   c           	          t        | j                  t        | j                  |fz  d| j                  | j
                  | j                  | j                        S )NF)r9   rP   rR   rQ   rH   rI   rJ   rK   )rY   rS   s     r7   r   zCollection.__getitem__  sM    $// DKK#66,,..,,++- 	-r6   c                 <    d| j                   d| j                  dS )NzCollection(z, ))rP   rQ   rY   s    r7   __repr__zCollection.__repr__&  s    '+DDr6   c                     t        |t              r4| j                  |j                  k(  xr | j                  |j
                  k(  S t        S r`   )rL   r9   rP   rZ   rQ   rS   NotImplementedrY   others     r7   __eq__zCollection.__eq__)  s<    eZ(OOu~~5 .KK5::-/r6   c                     | |k(   S r`   r5   r   s     r7   __ne__zCollection.__ne__/  s    5=  r6   c                     | j                   S )zzThe full name of this :class:`Collection`.

        The full name is of the form `database_name.collection_name`.
        )rT   r   s    r7   r   zCollection.full_name2  s     r6   c                     | j                   S )z%The name of this :class:`Collection`.)rQ   r   s    r7   rS   zCollection.name:  s     {{r6   c                     | j                   S )zdThe :class:`~pymongo.database.Database` that this
        :class:`Collection` is a part of.
        )rP   r   s    r7   rZ   zCollection.database?  s    
 r6   c           
          t        | j                  | j                  d|xs | j                  |xs | j                  |xs | j
                  |xs | j                        S )a0  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)

        :Parameters:
          - `codec_options` (optional): An instance of
            :class:`~bson.codec_options.CodecOptions`. If ``None`` (the
            default) the :attr:`codec_options` of this :class:`Collection`
            is used.
          - `read_preference` (optional): The read preference to use. If
            ``None`` (the default) the :attr:`read_preference` of this
            :class:`Collection` is used. See :mod:`~pymongo.read_preferences`
            for options.
          - `write_concern` (optional): An instance of
            :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the
            default) the :attr:`write_concern` of this :class:`Collection`
            is used.
          - `read_concern` (optional): An instance of
            :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the
            default) the :attr:`read_concern` of this :class:`Collection`
            is used.
        F)r9   rP   rQ   rH   rI   rJ   rK   )rY   rH   rI   rJ   rK   s        r7   with_optionszCollection.with_optionsF  sY    > $//++'=4+=+=)AT-A-A'=4+=+=&;$*;*;= 	=r6   c                 T    t        j                  dt        d       t        | d|      S )aa  **DEPRECATED** - Initialize an unordered batch of write operations.

        Operations will be performed on the server in arbitrary order,
        possibly in parallel. All operations will be attempted.

        :Parameters:
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.

        Returns a :class:`~pymongo.bulk.BulkOperationBuilder` instance.

        See :ref:`unordered_bulk` for examples.

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

        .. versionchanged:: 3.5
           Deprecated. Use :meth:`~pymongo.collection.Collection.bulk_write`
           instead.

        .. versionchanged:: 3.2
           Added bypass_document_validation support

        .. versionadded:: 2.7
        z*initialize_unordered_bulk_op is deprecated   
stacklevelFwarningswarnDeprecationWarningr   rY   bypass_document_validations     r7   initialize_unordered_bulk_opz'Collection.initialize_unordered_bulk_opm  s(    6 	B(Q	8#D%1KLLr6   c                 T    t        j                  dt        d       t        | d|      S )as  **DEPRECATED** - Initialize an ordered batch of write operations.

        Operations will be performed on the server serially, in the
        order provided. If an error occurs all remaining operations
        are aborted.

        :Parameters:
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.

        Returns a :class:`~pymongo.bulk.BulkOperationBuilder` instance.

        See :ref:`ordered_bulk` for examples.

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

        .. versionchanged:: 3.5
           Deprecated. Use :meth:`~pymongo.collection.Collection.bulk_write`
           instead.

        .. versionchanged:: 3.2
           Added bypass_document_validation support

        .. versionadded:: 2.7
        z(initialize_ordered_bulk_op is deprecatedr   r   Tr   r   s     r7   initialize_ordered_bulk_opz%Collection.initialize_ordered_bulk_op  s(    8 	@(Q	8#D$0JKKr6   c                 *   t        j                  d|       t        | ||      }|D ]  }	 |j                  |        | j                  |      }|j                  ||      }|t        |d      S t        i d      S # t        $ r t        |d      w xY w)aU
  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`).

          >>> for doc in db.test.find({}):
          ...     print(doc)
          ...
          {u'x': 1, u'_id': ObjectId('54f62e60fba5226811f634ef')}
          {u'x': 1, u'_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 = db.test.bulk_write(requests)
          >>> result.inserted_count
          1
          >>> result.deleted_count
          1
          >>> result.modified_count
          0
          >>> result.upserted_ids
          {2: ObjectId('54f62ee28891e756a6e1abd5')}
          >>> for doc in db.test.find({}):
          ...     print(doc)
          ...
          {u'x': 1, u'_id': ObjectId('54f62e60fba5226811f634f0')}
          {u'y': 1, u'_id': ObjectId('54f62ee2fba5226811f634f1')}
          {u'z': 1, u'_id': ObjectId('54f62ee28891e756a6e1abd5')}

        :Parameters:
          - `requests`: A list of write operations (see examples above).
          - `ordered` (optional): 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.
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

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

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

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

        .. versionchanged:: 3.2
          Added bypass_document_validation support

        .. versionadded:: 3.0
        requestsz is not a valid requestTF)	r   validate_listr   _add_to_bulkr~   rM   rx   executer%   )	rY   r   orderedr   r\   blkrequestrJ   bulk_api_results	            r7   
bulk_writezCollection.bulk_write  s    F 	Z2D'#=> 	JGJ$$S)	J //8++mW=&"?D99r5)) " Jw HIIJs   A::Bc           	         |r|j                   dk\  rt        d      | j                  j                  j                  }|j
                  }	|	rt        j                  j                         }
||j                  fz   } || \  }}}|	rrt        j                  j                         
z
  }|j                  || j                  j                  ||j                  |       t        j                  j                         }
	 |j                  |||d      }|	rb|t%        j&                  |||      }nddi}t        j                  j                         
z
  z   }|j)                  |||||j                  |       |S # t        $ r}|	rt        j                  j                         
z
  z   }t        |t              rY|j                   }|j#                  d      rQd|v rMt%        j&                  |||      }|j)                  |||||j                  |        t%        j*                  |      }|j-                  |||||j                  |        d}~ww xY w)z,Internal legacy unacknowledged write helper.   zGCannot set bypass_document_validation with unacknowledged write concernFoknNr,   )max_wire_versionr   rZ   ra   _event_listenersenabled_for_commandsdatetimenowcompression_contextpublish_command_startrP   rS   addresslegacy_write	ExceptionrL   detailsgetr   _convert_write_resultpublish_command_success_convert_exceptionpublish_command_failure)rY   rm   rS   rz   op_idbypass_doc_valfuncargs	listenerspublishstartrqst_idmsgmax_sizedurationresultexcdurr   replys                       r7   _legacy_writezCollection._legacy_write  s1    i88A=" $C D DMM((99	00%%))+Ey4466!%th((,,.6H++T__))7I4E4EuN%%))+E	++GS(EJF$ !55dCH q	 ))--/%78CH--%w	0A0A5J5  	((,,.6(Bc#34!kkG{{4(SG^ ' = = #w!0!99gy7H7H%Q%88=G11$1B1BEK!	s   7E1 1	I:CH??Ic	                    
 |rY j                   j                         t        t              sdvrt	               d<    j                   j                         xs  j                  j                  
t        d j                  fd|fdgfg      j                  sj                  d<   
 fd}	 j                   j                  j                  
|	|       t        t              sj                  d      S y)z0Internal helper for inserting a single document._idinsertr   	documentswriteConcernc                    |j                   sLsJ
j                  |d	t        j                  
j                  gdj
                  d
j                        S r|j                  dk\  rdd<   |j                  
j                  j                  
j                  | 
j                  j                  |      }t        |       y )Nr   Fr   TbypassDocumentValidation)rJ   rH   
check_keysr\   ra   ri   )op_msg_enabledr   r   r   rT   documentrX   r   rl   rP   rS   ra   r    )r\   rm   ri   r   acknowledgedr   r   rl   docr   rY   rJ   s       r7   _insert_commandz/Collection._insert_one.<locals>._insert_commandB  s    ++L))x%"GNND4D4DE:um.D.De77	9 9 )"<"<"A6:23&&$$+"AA%-- / ' 1F *&1r6   N)rP   _apply_incoming_manipulatorsrL   r	   r   $_apply_incoming_copying_manipulatorsrJ   r   r   rS   is_server_defaultr   ra   _retryable_writer   )rY   r   r   r   
manipulaterJ   r   r   r\   r   r   rl   s   `` ` ```  @@r7   _insert_onezCollection._insert_one/  s    
 //>>sDICc?3S8H%ZE
//FFsGKMC%;););$11$)),!7+#cU+- . ..&3&<&<GN#	2 	20 	///7	4 #/775>! 0r6   c	           
          t        t        j                        r j                  |||||||      S g |r fd}	nfd}	|xs  j	                  |      }t         ||      }
 |	       D cg c]  }t        j                  |f c}|
_        	 |
j                  ||       S c c}w # t        $ r }t        |j                         Y d}~S d}~ww xY w)zInternal insert helper.c               3      K   j                   } D ]_  }| j                  |      }t        |t              sd|v st	               |d<   | j                  |      }j                  |d          | a yw)ztGenerator that applies SON manipulators to each document
                and adds _id if necessary.
                r   N)rP   r   rL   r	   r   r   append)_dbr   docsidsrY   s     r7   genzCollection._insert.<locals>.genl  sw      oo 
C ::3EC&sO<%-ZE
BB3MCJJs5z*I
s   A2A5c               3      K   D ]6  } t        | t              s j                  | j                  d             |  8 yw)z)Generator that only tracks existing _ids.r   N)rL   r	   r   r   )r   r   r   s    r7   r   zCollection._insert.<locals>.gen}  s9      C%c?;

3775>2I	s   =A r\   N)rL   r   Mappingr   rx   r   r   _INSERTopsr   r   r!   r   )rY   r   r   r   r   rJ   r   r   r\   r   r   r   bwer   s   ``           @r7   _insertzCollection._insert`  s     dCKK(##gz:}e) ) " &I)@)@)ID'>258U;cGOOS);	+KKwK7 
 <  	+ckk**
	+s   3B*B/ /	C8CCc                     t        j                  d|       t        |t              sd|v st	               |d<   | j                  |      }t        | j                  ||||      |j                        S )a  Insert a single document.

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

        :Parameters:
          - `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.
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

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

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

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

        .. versionchanged:: 3.2
          Added bypass_document_validation support

        .. versionadded:: 3.0
        r   r   )rJ   r   r\   )	r   validate_is_document_typerL   r	   r   rx   r'   r   r   )rY   r   r   r\   rJ   s        r7   
insert_onezCollection.insert_one  su    L 	((X>8_5(9J&jHUO//8LL'4(B!(  * &&( 	(r6   c                 0  	 t        t        j                        rst        d      g 		fd}| j	                  |      }t        | ||      } |       D cg c]  }| c}|_        |j                  ||       t        	|j                        S c c}w )a  Insert an iterable of documents.

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

        :Parameters:
          - `documents`: A iterable of documents to insert.
          - `ordered` (optional): 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.
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

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

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

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

        .. versionchanged:: 3.2
          Added bypass_document_validation support

        .. versionadded:: 3.0
        z"documents must be a non-empty listc               3      K   D ]a  } t        j                  d|        t        | t              s%d| vrt	               | d<   j                  | d          t        j                  | f c yw)z6A generator that validates documents and handles _ids.r   r   N)r   r   rL   r	   r   r   r   r   )r   r   inserted_idss    r7   r   z#Collection.insert_many.<locals>.gen  sd     % 200XF!(O<H,*2* ''8112s   A(A+r   )
rL   r   IterablerM   rx   r   r   r   r(   r   )
rY   r   r   r   r\   r   rJ   r   r   r   s
    `       @r7   insert_manyzCollection.insert_many  s    R )S\\2)@AA	2 //8D'#=>"%%(33(M73m.H.HII )s   	Bc                    t        j                  d|       |r| j                  j                  ||       }t	        |      }|xs | j
                  }|j                  }t        d|fd|fd|fd|fg      }|,|j                  dk  rt        d      |st        d      ||d	<   |,|j                  d
k  rt        d      |st        d      ||d<   |Q|j                  dk  rt        d      |st        d      t        |t              st        j                  |      }||d<   t        d| j                  fd|
fd|gfg      }|j                  s|j                   |d<   |j"                  sM|sK| j%                  |d||	|t&        j(                  | j*                  ||||d|j                   || j,                        S |r|j                  dk\  rd|d<   |j/                  | j                  j                  ||| j,                  || j                  j0                  |      j3                         }t5        |       |j7                  d      r
d|vrd|d<   nd|d<   d|v r|d   d   d   |d<   |sy|S )!Internal update / replace helper.upsertqumultiN   4Must be connected to MongoDB 3.4+ to use collations.3Collation is unsupported for unacknowledged writes.rB      z7Must be connected to MongoDB 3.6+ to use array_filters.6arrayFilters is unsupported for unacknowledged writes.arrayFilters.Must be connected to MongoDB 3.4+ to use hint..hint is unsupported for unacknowledged writes.hintrv   r   updatesr   Fr   Tr   rJ   rH   r\   ra   ri   r   upsertedupdatedExistingr   r   )r   validate_booleanrP   _fix_incomingr   rJ   r   r   r   r   rL   r   r   _index_documentrS   r   r   r   r   r   rv   rT   rX   rl   ra   copyr    r   )rY   rm   criteriar   r   r   r   r   rJ   r   r   r   rB   array_filtersr  r\   ri   r   
update_docrl   r   s                        r7   _updatezCollection._update  s    	&144XtDH.y9	%;););$113//"E*#V,. /
  ))A-(JL L!(IK K +4
;'$))A-(MO O!(LN N .;
>*))A-(DF F!(DF FdK0..t4!%Jv$)),!7+!J<02 3 ..&3&<&<GN#''%%8We0@0@&x5-2H2HD??	A A i88A=26G./ ""OO  '==??))+ # - .2TV 	 	&f-::c?z7(,F$%(-F$% V#%+J%7%:5%Az"r6   c                     	
 
	 fd} j                   j                  j                  xs  j                  j                  xr  ||      S )r   c                 F    j                  |
	| |      S )N)r   r   r   r   rJ   r   r   r   rB   r  r  r\   ri   )r  )r\   rm   ri   r  r   r   rB   r  r   r  r   r   r   r   rY   r   rJ   s      r7   r  z-Collection._update_retryable.<locals>._update[  s?    <<8Xf%Uz+5'-+$ /   1 1r6   rP   ra   r   rJ   r   )rY   r  r   r   r   r   r   rJ   r   r   r   rB   r  r  r\   r  s   ``````````````  r7   _update_retryablezCollection._update_retryableT  sR    	1 	1 	1 %%660d00>>Lu9W 	r6   c                     t        j                  d|       t        j                  |       | j                  |      }t	        | j                  ||||||||      |j                        S )a	  Replace a single document matching the filter.

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

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

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

        :Parameters:
          - `filter`: A query that matches the document to replace.
          - `replacement`: The new document.
          - `upsert` (optional): If ``True``, perform an insert if no documents
            match the filter.
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``. This option is only supported on MongoDB 3.2 and above.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.2 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

        .. 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
        filter)rJ   r   rB   r  r\   )r   validate_is_mappingvalidate_ok_for_replacerx   r)   r  r   )	rY   r  replacementr   r   rB   r  r\   rJ   s	            r7   replace_onezCollection.replace_oneh  ss    D 	""8V4&&{3//8""V+9#$	 # A
 &&( 	(r6   c	                    t        j                  d|       t        j                  |       t        j                  d|       | j	                  |      }	t        | j                  |||d|	|||||
      |	j                        S )an	  Update a single document matching the filter.

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

        :Parameters:
          - `filter`: A query that matches the document to update.
          - `update`: The modifications to apply.
          - `upsert` (optional): If ``True``, perform an insert if no documents
            match the filter.
          - `bypass_document_validation`: (optional) If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``. This option is only supported on MongoDB 3.2 and above.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `array_filters` (optional): A list of filters specifying which
            array elements an update should apply. This option is only
            supported on MongoDB 3.6 and above.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.2 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

        .. 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
        r  r  F)r   rJ   r   rB   r  r  r\   r   r  validate_ok_for_updatevalidate_list_or_nonerx   r)   r  r   )
rY   r  rv   r   r   rB   r  r  r\   rJ   s
             r7   
update_onezCollection.update_one  s    ~ 	""8V4%%f-$$_mD//8""5+9#=7 # , &&( 	(r6   c	                    t        j                  d|       t        j                  |       t        j                  d|       | j	                  |      }	t        | j                  |||dd|	|||||      |	j                        S )aj	  Update one or more documents that match the filter.

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

        :Parameters:
          - `filter`: A query that matches the documents to update.
          - `update`: The modifications to apply.
          - `upsert` (optional): If ``True``, perform an insert if no documents
            match the filter.
          - `bypass_document_validation` (optional): If ``True``, allows the
            write to opt-out of document level validation. Default is
            ``False``. This option is only supported on MongoDB 3.2 and above.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `array_filters` (optional): A list of filters specifying which
            array elements an update should apply. This option is only
            supported on MongoDB 3.6 and above.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.2 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

        .. 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
        r  r  FT)r   r   rJ   r   rB   r  r  r\   r  )
rY   r  rv   r   r  r   rB   r  r\   rJ   s
             r7   update_manyzCollection.update_many  s    | 	""8V4%%f-$$_mD//8""5+9#=7 # , &&( 	(r6   c                    | j                   j                  j                  | j                   j                  | j                  | j
                  | j                  | j                        }|j                  | j                  |       y)a  Alias for :meth:`~pymongo.database.Database.drop_collection`.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        The following two calls are equivalent:

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

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

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r   N)
rP   ra   get_databaserS   rH   rI   rJ   rK   drop_collectionrQ   )rY   r\   dbos      r7   dropzCollection.dropO  sh    $ oo$$11OO     	DKK9r6   c                    t        j                  d|       |xs | j                  }|j                  }t	        d|fdt        |       fg      }t        |      }|,|j                  dk  rt        d      |st        d      ||d<   |Q|j                  dk  rt        d      |st        d	      t        |t              st        j                  |      }||d
<   t	        d| j                  fd|fd|gfg      }|j                  s|j                  |d<   |j                   sT|sR| j#                  |d||dt$        j&                  | j(                  |d|j                  | j*                  t        |             S |j-                  | j.                  j                  ||| j*                  |	| j.                  j0                  |
      }t3        |       |S )Internal delete helper.r  r   limitr   r   r   rB   r  r  r  deleter   deletesr   Fr  )r   r  rJ   r   r   intr   r   r   rL   r   r   r  rS   r   r   r   r   r   r+  rT   rX   rl   rP   ra   r    )rY   rm   r  r   rJ   r   r   rB   r  r\   ri   r   
delete_docrl   r   s                  r7   _deletezCollection._deletei  s   
 	""8X6%;););$113/"CE	N35 6
.y9	 ))A-(JL L!(IK K +4
;'))A-(DF F!(DF FdK0..t4!%Jv$)),!7+!J<02 3 ..&3&<&<GN#''%%8Wew~~t'7'7}--33I    ""OO  '==??))+ # - 	&f-r6   c	                       fd}	 j                   j                  j                  xs  j                  j                  xr  |	|      S )r)  c                 :    	j                  |
| |
      S )N)rJ   r   r   rB   r  r\   ri   )r/  )r\   rm   ri   rB   r  r  r   r   r   rY   rJ   s      r7   r/  z-Collection._delete_retryable.<locals>._delete  s1    <<8U+5'#$ /	   1 1r6   r  )
rY   r  r   rJ   r   r   rB   r  r\   r/  s
   ````````  r7   _delete_retryablezCollection._delete_retryable  sL    
	1 	1 %%660d00>>Lu9W 	r6   c           
      z    | j                  |      }t        | j                  |d||||      |j                        S )a!  Delete a single document matching the filter.

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

        :Parameters:
          - `filter`: A query that matches the document to delete.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
          Added the `collation` option.
        .. versionadded:: 3.0
        FrJ   rB   r  r\   rx   r&   r2  r   rY   r  rB   r  r\   rJ   s         r7   
delete_onezCollection.delete_one  sP    H //8""+#$ # A &&( 	(r6   c           
      z    | j                  |      }t        | j                  |d||||      |j                        S )a'  Delete one or more documents matching the filter.

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

        :Parameters:
          - `filter`: A query that matches the documents to delete.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

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

        .. versionchanged:: 3.11
           Added ``hint`` parameter.
        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
          Added the `collation` option.
        .. versionadded:: 3.0
        Tr4  r5  r6  s         r7   delete_manyzCollection.delete_many  sP    H //8""+#$ # A &&( 	(r6   c                     |t        |t        j                        sd|i} | j                  |g|i |}|j	                  d      D ]  }|c S  y)a  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:`Collection`.

        :Parameters:

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

          - `*args` (optional): any additional positional arguments
            are the same as the arguments to :meth:`find`.

          - `**kwargs` (optional): any additional keyword arguments
            are the same as the arguments to :meth:`find`.

              >>> collection.find_one(max_time_ms=100)
        Nr   r@   )rL   r   r   findr*  )rY   r  r   r]   cursorr   s         r7   find_onezCollection.find_one	  s[    2 63;;/V_F63D3F3ll2& 	FM	r6   c                      t        | g|i |S )a)+  Query the database.

        The `filter` argument is a prototype 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.cursor.Cursor` corresponding to this query.

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

        :Parameters:
          - `filter` (optional): a SON object specifying elements which
            must be present for a document to be included in the
            result set
          - `projection` (optional): 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}).
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `skip` (optional): the number of documents to omit (from
            the start of the result set) when returning the results
          - `limit` (optional): the maximum number of results to
            return. A limit of 0 (the default) is equivalent to setting no
            limit.
          - `no_cursor_timeout` (optional): 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.
          - `cursor_type` (optional): 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
              <http://www.mongodb.org/display/DOCS/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.

          - `sort` (optional): a list of (key, direction) pairs
            specifying the sort order for this query. See
            :meth:`~pymongo.cursor.Cursor.sort` for details.
          - `allow_partial_results` (optional): if True, mongos will return
            partial results if some shards are down instead of returning an
            error.
          - `oplog_replay` (optional): **DEPRECATED** - if True, set the
            oplogReplay query flag. Default: False.
          - `batch_size` (optional): Limits the number of documents returned in
            a single batch.
          - `manipulate` (optional): **DEPRECATED** - If True, apply any
            outgoing SON manipulators before returning. Default: True.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `return_key` (optional): If True, return only the index keys in
            each document.
          - `show_record_id` (optional): If True, adds a field ``$recordId`` in
            each document with the storage engine's internal record identifier.
          - `snapshot` (optional): **DEPRECATED** - If True, prevents the
            cursor from returning a document more than once because of an
            intervening write operation.
          - `hint` (optional): An index, in the same format as passed to
            :meth:`~pymongo.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). Pass this as an alternative to calling
            :meth:`~pymongo.cursor.Cursor.hint` on the cursor to tell Mongo the
            proper index to use for the query.
          - `max_time_ms` (optional): 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.cursor.Cursor.max_time_ms` on the cursor.
          - `max_scan` (optional): **DEPRECATED** - The maximum number of
            documents to scan. Pass this as an alternative to calling
            :meth:`~pymongo.cursor.Cursor.max_scan` on the cursor.
          - `min` (optional): 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.cursor.Cursor.min` on the cursor. ``hint`` must
            also be passed to ensure the query utilizes the correct index.
          - `max` (optional): 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.cursor.Cursor.max` on the cursor. ``hint`` must
            also be passed to ensure the query utilizes the correct index.
          - `comment` (optional): 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.cursor.Cursor.comment` on the cursor.
          - `modifiers` (optional): **DEPRECATED** - A dict specifying
            additional MongoDB query modifiers. Use the keyword arguments listed
            above instead.
          - `allow_disk_use` (optional): 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.Cursor` instance created with the
            :attr:`~pymongo.cursor.CursorType.EXHAUST` cursor_type requires an
            exclusive :class:`~socket.socket` connection to MongoDB. If the
            :class:`~pymongo.cursor.Cursor` 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:: 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.

        .. versionchanged:: 2.7
           Added ``compile_re`` option. If set to False, PyMongo represented
           BSON regular expressions as :class:`~bson.regex.Regex` objects
           instead of attempting to compile BSON regular expressions as Python
           native regular expressions, thus preventing errors for some
           incompatible patterns, see `PYTHON-500`_.

        .. versionchanged:: 2.3
           Added the ``tag_sets`` and ``secondary_acceptable_latency_ms``
           parameters.

        .. _PYTHON-500: https://jira.mongodb.org/browse/PYTHON-500

        .. mongodoc:: find

        )r   rY   r   r]   s      r7   r;  zCollection.find+  s    P d,T,V,,r6   c                     d|v rt        d      | j                  j                  j                  rt	        d      t        | g|i |S )a  Query the database and retrieve batches of raw BSON.

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

        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()
          >>> for batch in cursor:
          ...     print(bson.decode_all(batch))

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

        .. versionadded:: 3.6
        r\   z*find_raw_batches does not support sessionsz1find_raw_batches does not support auto encryption)r   rP   ra   
_encrypterr   r   r?  s      r7   find_raw_batcheszCollection.find_raw_batches  sZ    . $<> > ??!!,,"CE E d4T4V44r6   c                 &   t        j                  dt        d       t        d| j                  fd|fg      }|j                  |       | j                  |      5 \  }}|j                  | j                  j                  ||| j                  |      | j                  | j                  d|| j                  j                  	      }ddd       g }d	   D ]0  }	|j                  t        | |	d
   j                   ||du             2 |S # 1 sw Y   ExY w)a2  **DEPRECATED**: Scan this entire collection in parallel.

        Returns a list of up to ``num_cursors`` cursors that can be iterated
        concurrently. As long as the collection is not modified during
        scanning, each document appears once in one of the cursors result
        sets.

        For example, to process each document in a collection using some
        thread-safe ``process_document()`` function:

          >>> def process_cursor(cursor):
          ...     for document in cursor:
          ...     # Some thread-safe processing function:
          ...     process_document(document)
          >>>
          >>> # Get up to 4 cursors.
          ...
          >>> cursors = collection.parallel_scan(4)
          >>> threads = [
          ...     threading.Thread(target=process_cursor, args=(cursor,))
          ...     for cursor in cursors]
          >>>
          >>> for thread in threads:
          ...     thread.start()
          >>>
          >>> for thread in threads:
          ...     thread.join()
          >>>
          >>> # All documents have now been processed.

        The :meth:`parallel_scan` method obeys the :attr:`read_preference` of
        this :class:`Collection`.

        :Parameters:
          - `num_cursors`: the number of cursors to return
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs`: additional options for the parallelCollectionScan
            command can be passed as keyword arguments.

        .. note:: Requires server version **>= 2.5.5**.

        .. versionchanged:: 3.7
           Deprecated.

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

        .. versionchanged:: 3.4
           Added back support for arbitrary keyword arguments. MongoDB 3.4
           adds support for maxTimeMS as an option to the
           parallelCollectionScan command.

        .. versionchanged:: 3.0
           Removed support for arbitrary keyword arguments, since
           the parallelCollectionScan command has no optional arguments.
        zXparallel_scan is deprecated. MongoDB 4.2 will remove the parallelCollectionScan command.r   r   parallelCollectionScan
numCursorsT)rK   rh   r\   ra   Ncursorsr<  r\   explicit_session)r   r   r   r   rQ   rv   rb   rl   rP   rS   rc   rH   rK   ra   r   r   r   )
rY   num_cursorsr\   r]   rz   rm   rn   r   rF  r<  s
             r7   parallel_scanzCollection.parallel_scan  s(   t 	 <(Q	8 ,dkk: +.0 1

6##G, 	/0EH &&$$))'2""!..*.-- ' 	/F	/ Y' 	HFNN=fX&	(9(9'2EG H	H
 )	/ 	/s   A)DDc                       fd} j                   j                  j                  | j                  |      |      S )zInternal count helper.c           
          j                  ||dgj                  j                  |       }|j                  dd      dk(  ryt	        |d         S )Nz
ns missing)rp   rH   rK   rB   r\   errmsg r   r   )rr   rX   rK   r   r-  )r\   serverrm   rn   resrz   rB   rY   s        r7   _cmdzCollection._count.<locals>._cmdr  sb    --"."AA!..#   !C wwx$4s3x= r6   )rP   ra   _retryable_readrc   )rY   rz   rB   r\   rQ  s   ```  r7   _countzCollection._countn  s9    	! %%55$++G4g? 	?r6   c           	      |    | j                  |||| j                  | j                  ||      }|d   d   }|r|d   S dS )zAInternal helper to run an aggregate that returns a single result.)rH   rK   rB   r\   r<  
firstBatchr   N)rr   rX   rK   )rY   rm   rn   rz   rB   r\   r   batchs           r7   _aggregate_one_resultz Collection._aggregate_one_result  sZ     ==**   x . uQx*d*r6   c                     d|v rt        d      t        d| j                  fg      }|j                  |       | j	                  |      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.

        :Parameters:
          - `**kwargs` (optional): See list of options above.

        .. versionadded:: 3.7
        r\   z2estimated_document_count does not support sessionscount)r   r   rQ   rv   rS  )rY   r]   rz   s      r7   estimated_document_countz#Collection.estimated_document_count  sO    $ $DF FGT[[)*+

6{{3r6   c                 L    d|ig}d|v r"|j                  d|j                  d      i       d|v r"|j                  d|j                  d      i       |j                  ddddid	i       t        d
 j                  fd|fdi fg      d|v r.t	        |d   t
              st        j                  |d         |d<   t        |j                  dd            j                  |        fd} j                  j                  j                  | j                  |      |      S )aF  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`. This option is only supported
            on MongoDB 3.4 and above.
          - `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)]).
            This option is only supported on MongoDB 3.6 and above.

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

        .. 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`_ |
           +-------------+-------------------------------------+

           $expr requires MongoDB 3.6+

        :Parameters:
          - `filter` (required): A query document that selects which documents
            to count in the collection. Can be an empty document to count all
            documents.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): See list of options above.

        .. versionadded:: 3.7

        .. _$expr: https://docs.mongodb.com/manual/reference/operator/query/expr/
        .. _$geoWithin: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/
        .. _$center: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center
        .. _$centerSphere: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
        z$matchskipz$skipr*  z$limitz$groupr,   z$sum)r   r   	aggregatepipeliner<  r  rB   Nc                 >    j                  |||       }|sy|d   S )Nr   r   )rW  )r\   rO  rm   rn   r   rz   rB   rY   s        r7   rQ  z(Collection.count_documents.<locals>._cmd  s.    //8S)W>F#;r6   )r   rO   r   rQ   rL   r   r   r  r   rv   rP   ra   rR  rc   )rY   r  r\   r]   r^  rQ  rz   rB   s   `     @@r7   count_documentszCollection.count_documents  s    t v&'VOOWfjj&89:fOOXvzz'':;<1FA;#?@AK-)b># $ VJvf~{$K$44VF^DF6N.vzz+t/LM	

6	 %%55$++G4g? 	?r6   c                 x   t        j                  dt        d       t        d| j                  fg      }|d|v rt        d      ||d<   d|v r.t        |d   t              st        j                  |d         |d<   t        |j                  d	d            }|j                  |       | j                  |||      S )
an  **DEPRECATED** - Get the number of documents in this collection.

        The :meth:`count` method is deprecated and **not** supported in a
        transaction. Please use :meth:`count_documents` or
        :meth:`estimated_document_count` instead.

        All optional count 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. A limit
            of 0 (the default) is equivalent to setting no limit.
          - `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`. This option is only supported
            on MongoDB 3.4 and above.
          - `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` method obeys the :attr:`read_preference` of
        this :class:`Collection`.

        .. 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`_ |
           +-------------+-------------------------------------+

           $expr requires MongoDB 3.6+

        :Parameters:
          - `filter` (optional): A query document that selects which documents
            to count in the collection.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): See list of options above.

        .. versionchanged:: 3.7
           Deprecated.

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

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

        .. _$expr: https://docs.mongodb.com/manual/reference/operator/query/expr/
        .. _$geoWithin: https://docs.mongodb.com/manual/reference/operator/query/geoWithin/
        .. _$center: https://docs.mongodb.com/manual/reference/operator/query/center/#op._S_center
        .. _$centerSphere: https://docs.mongodb.com/manual/reference/operator/query/centerSphere/#op._S_centerSphere
        zcount is deprecated. Use estimated_document_count or count_documents instead. Please note that $where must be replaced by $expr, $near must be replaced by $geoWithin with $center, and $nearSphere must be replaced by $geoWithin with $centerSpherer   r   rY  Nquery can't pass both filter and queryr  rB   )r   r   r   r   rQ   r   rL   r   r   r  r   rO   rv   rS  )rY   r  r\   r]   rz   rB   s         r7   rY  zCollection.count  s    | 	 B
 )Q	8 GT[[)*+& ()KLL$F7OVJvf~{$K$44VF^DF6N.vzz+t/LM	

6{{3	733r6   c                 V    t        j                  d|        | j                  ||fi |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)])
          >>> db.test.create_indexes([index1, index2])
          ["hello_world", "goodbye_-1"]

        :Parameters:
          - `indexes`: A list of :class:`~pymongo.operations.IndexModel`
            instances.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        .. note:: `create_indexes` uses the `createIndexes`_ command
           introduced in MongoDB **2.6** and cannot be used with earlier
           versions.

        .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
           this collection is automatically applied to this operation when using
           MongoDB >= 3.4.

        .. 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://docs.mongodb.com/manual/reference/command/createIndexes/
        indexes)r   r   _Collection__create_indexes)rY   re  r\   r]   s       r7   create_indexeszCollection.create_indexesK  s/    J 	Y0$t$$Wg@@@r6   c           
        	 g | j                  |      5 }|j                  dk\  	|j                  dk\  }	fd}t        d| j                  fdt	         |             fg      }|j                  |       d|v r|st        d      | j                  ||t        j                  t        | j                  |      |       d	d	d	       S # 1 sw Y   S xY w)
a  Internal createIndexes helper.

        :Parameters:
          - `indexes`: A list of :class:`~pymongo.operations.IndexModel`
            instances.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.
        r   	   c               3   
  K   D ]y  } t        | t              st        | d      | j                  }d|v rst	        d      d|v r t        j                  t        t        d       j                  |d          | { y w)Nz4 is not an instance of pymongo.operations.IndexModelrB   r   
bucketSizer   r   rS   )
rL   r#   rM   r   r   r   r   _HAYSTACK_MSGr   r   )indexr   re  namessupports_collationss     r7   gen_indexesz0Collection.__create_indexes.<locals>.gen_indexes  s     $ #E%eZ8'?DGH H  %~~H"h.7J067 7 $x/ )+=!MLL&!12"N#s   B BcreateIndexesre  commitQuorumzRMust be connected to MongoDB 4.4+ to use the commitQuorum option for createIndexes)rI   rH   rJ   r\   N)rf   r   r   rS   listrv   r   rr   r$   rw   r"   rx   )
rY   re  r\   r]   rm   supports_quorumrp  rz   rn  ro  s
    `      @@r7   __create_indexeszCollection.__create_indexess  s     $$W- "	!"+"<"<"A'88A=O#$ 3!4#679 :CJJv'(<= = MM30F0F<"55g>	  !="	!F G"	!F s   B)C

Cc                 ~    i }d|v r|j                  d      |d<   t        |fi |} | j                  |g|fi |d   S )aM  Creates an index on this collection.

        Takes either a single key or a list of (key, direction) pairs.
        The key(s) must be an instance of :class:`basestring`
        (:class:`str` in python 3), and the direction(s) must be one of
        (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`,
        :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOHAYSTACK`,
        :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::

          >>> my_collection.create_index("mike")

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

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

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

          >>> 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. Requires MongoDB >=3.2.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. Requires MongoDB >= 3.4.
          - `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.collection.Collection.write_concern` of
           this collection is automatically applied to this operation when using
           MongoDB >= 3.4.

        :Parameters:
          - `keys`: a single key or a list of (key, direction)
            pairs specifying the index to create
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): any additional index creation
            options (see the above list) should be passed as keyword
            arguments

        .. 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.

        .. mongodoc:: indexes

        .. _wildcard index: https://docs.mongodb.com/master/core/index-wildcard/#wildcard-index-core
        	maxTimeMSr   )rO   r#   rf  )rY   keysr\   r]   cmd_optionsrm  s         r7   create_indexzCollection.create_index  sU    F & '-zz+'>K$4*6*$t$$eWgEEaHHr6   c                 j   t        j                  dt        d       t        |t              st        |t
              st        d      d|v r|j                  d      |d<   d|v r|j                  d      |d<   t        |fi |}|j                  d	   }| j                  j                  j                  | j                  j                  | j                  |      s\| j                  |gd
       | j                  j                  j!                  | j                  j                  | j                  ||       |S y
)z**DEPRECATED** - Ensures that an index exists on this collection.

        .. versionchanged:: 3.0
            **DEPRECATED**
        z5ensure_index is deprecated. Use create_index instead.r   r   z&cache_for must be an integer or float.	drop_dupsdropDupsbucket_sizerk  rS   Nr   )r   r   r   rL   r   ru   rM   rO   r#   r   rP   ra   _cachedrS   rQ   rf  _cache_index)rY   key_or_list	cache_forr]   rm  rS   s         r7   ensure_indexzCollection.ensure_index  s
    	M(Q	8 9m49e,DEE& !'K!8F:F"#)::m#<F< ;1&1~~f% %%--doo.B.B.2kk4A!!5'4!8OO""//0D0D04T9NKr6   c                     | j                   j                  j                  | j                   j                  | j                          | j
                  dd|i| y)a  Drops all indexes on this collection.

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

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
           this collection is automatically applied to this operation when using
           MongoDB >= 3.4.

        .. 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.

        r\   N)*)rP   ra   _purge_indexrS   rQ   
drop_index)rY   r\   r]   s      r7   drop_indexeszCollection.drop_indexes1  sB    2 	++DOO,@,@$++N7W77r6   c           
      "   |}t        |t              rt        j                  |      }t        |t              st        d      | j                  j                  j                  | j                  j                  | j                  |       t        d| j                  fd|fg      }|j                  |       | j                  |      5 }| j                  ||t        j                   ddg| j#                  |      |       ddd       y# 1 sw Y   yxY w)a  Drops the specified index on this collection.

        Can be used on non-existant 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` or
          :meth:`ensure_index`) the index **must** be dropped by name.

        :Parameters:
          - `index_or_name`: index (or name of index) to drop
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): optional arguments to the createIndexes
            command (like maxTimeMS) can be passed as keyword arguments.

        .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
           this collection is automatically applied to this operation when using
           MongoDB >= 3.4.

        .. 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.

        z+index_or_name must be an index name or listdropIndexesrm  zns not found   )rI   rp   rJ   r\   N)rL   rs  r   _gen_index_namer   rM   rP   ra   r  rS   rQ   r   rv   rf   rr   r$   rw   rx   )rY   index_or_namer\   r]   rS   rz   rm   s          r7   r  zCollection.drop_indexM  s    J mT***=9D$,IJJ++OO  $++t	5M4;;/'4AB

6$$W- 	+MM)*8*@*@,:B+?(,(?(?(H")  +	+ 	+ 	+s   7DDc                     t        j                  dt        d       t        d| j                  fg      }|j                  |       | j                  |      5 }| j                  ||t        j                  |      cddd       S # 1 sw Y   yxY w)a  Rebuilds all indexes on this collection.

        **DEPRECATED** - The :meth:`~reindex` method is deprecated and will be
        removed in PyMongo 4.0. Use :meth:`~pymongo.database.Database.command`
        to run the ``reIndex`` command directly instead::

          db.command({"reIndex": "<collection_name>"})

        .. note:: Starting in MongoDB 4.6, the `reIndex` command can only be
          run when connected to a standalone mongod.

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): optional arguments to the reIndex
            command (like maxTimeMS) can be passed as keyword arguments.

        .. warning:: reindex blocks all other operations (indexes
           are built in the foreground) and will be slow for large
           collections.

        .. versionchanged:: 3.11
           Deprecated.

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

        .. versionchanged:: 3.5
           We no longer apply this collection's write concern to this operation.
           MongoDB 3.4 silently ignored the write concern. MongoDB 3.6+ returns
           an error if we include the write concern.

        .. versionchanged:: 3.4
           Apply this collection's write concern automatically to this operation
           when connected to MongoDB >= 3.4.
        zThe reindex method is deprecated and will be removed in PyMongo 4.0. Use the Database.command method to run the reIndex command instead.r   r   reIndex)rI   r\   N)
r   r   r   r   rQ   rv   rf   rr   r$   rw   )rY   r\   r]   rz   rm   s        r7   reindexzCollection.reindex  s    L 	 1 )Q	8 It{{+,-

6$$W- 	!==30F0F ! !	! 	! 	!s   #BBc                     t        t               j                  t        j                        |xr |j                         xs t        j                   fd} j                  j                  j                  ||      S )a&  Get a cursor over the index documents for this collection.

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

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        :Returns:
          An instance of :class:`~pymongo.command_cursor.CommandCursor`.

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

        .. versionadded:: 3.0
        )rH   rI   c                    t        dj                  fdi fg      }|j                  dkD  rfj                  j                  j                  | d      5 }	 j                  |||	|      d   }d d d        t        
|j                  | d u	      S t        j                  |j                  j                  d
dj                  id|	|j                  j                  j                   
      }|d   }t        
||j                        S # t        $ r}|j                  dk7  r dg d}Y d }~d }~ww xY w# 1 sw Y   xY w)NlistIndexesr<  r   Fr   r  r   )idrU  rG  zsystem.indexesns)r   rQ   r   rP   ra   rk   rr   r   coder   r   r   _first_batchrS   rT   rZ   r   )r\   rO  rm   rn   rz   rq   r<  r   rP  rH   coll	read_prefrY   s            r7   rQ  z%Collection.list_indexes.<locals>._cmd  sW   t{{3h^DEC))A-__++88%H =A
=!%y#x/8/<78 "/ ": ;C"D= %T693D3D-.6=T6IK K **t335E4++,a=sMM((99	;
 X %T693D3DEE% , = 88r>!()!<== =s0   D5D

	D2D-(D5-D22D55D>)	r
   r   r   r$   rw   _txn_read_preferencerP   ra   rR  )rY   r\   rQ  rH   r  r  s   `  @@@r7   list_indexeszCollection.list_indexes  s    ( %S)  }1?1G1G ! I@'">">"@ /&.. 		F: %%55)W& 	&r6   c                     | j                  |      }i }|D ]7  }|d   j                         |d<   t        |      }|||j                  d      <   9 |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:

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

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        r   keyrS   )r  itemsrW   rO   )rY   r\   r<  inform  s        r7   index_informationzCollection.index_information  sd    4 ""7"3 	,E <--/E%LKE&+D6"#	, r6   c                 `   | j                   j                  j                  | j                   j                  | j                  | j
                  | j                  | j                        }|j                  |d| j                  i      }d}|D ]  }|} n |si S |j                  di       }d|v r|d= |S )a  Get the options set on this collection.

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

        :Parameters:
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        rS   )r\   r  Nry   r[   )rP   ra   r$  rS   rH   rI   rJ   rK   list_collectionsrQ   r   )rY   r\   r&  r<  r   r   ry   s          r7   ry   zCollection.options	  s     oo$$11OO     %%VT[[$9 & ;  	CF	 I**Y+w!r6   c           
      R   d}d|v rBt        j                  dt        d       t        j                  d|j                  dd            } || ||||dddii|	      }| j                  j                  j                  |j                  |j                  |      ||j                   
      S )NT	useCursorzEThe useCursor option is deprecated and will be removed in PyMongo 4.0r   r   r<  rU  r,   )rj   
use_cursor)	retryable)r   r   r   r   r
  rO   rP   ra   rR  
get_cursorget_read_preference_performs_write)	rY   aggregation_commandr^  cursor_classr\   rH  r]   r  rz   s	            r7   
_aggregatezCollection._aggregate8	  s     
& MM5"q2  00VZZT:<J ",&2B!L!#45*N %%55NNC33G<g--- 6 / 	/r6   c                     | j                   j                  j                  |d      5 } | j                  t        |t
        f||dud|cddd       S # 1 sw Y   yxY w)aW  Perform an aggregation using the aggregation framework on this
        collection.

        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, or `useCursor` is
            ``False``.
          - `collation` (optional): An instance of
            :class:`~pymongo.collation.Collation`. This option is only supported
            on MongoDB 3.4 and above.
          - `useCursor` (bool): Deprecated. Will be removed in PyMongo 4.0.

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

        .. note:: This method does not support the 'explain' option. Please
           use :meth:`~pymongo.database.Database.command` instead. An
           example is included in the :ref:`aggregate-examples` documentation.

        .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
           this collection is automatically applied to this operation when using
           MongoDB >= 3.4.

        :Parameters:
          - `pipeline`: a list of aggregation pipeline stages
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): See list of options above.

        :Returns:
          A :class:`~pymongo.command_cursor.CommandCursor` over the result
          set.

        .. 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 a CommandCursor. The
           pipeline argument must be a list.
        .. versionchanged:: 2.7
           When the cursor option is used, return
           :class:`~pymongo.command_cursor.CommandCursor` instead of
           :class:`~pymongo.cursor.Cursor`.
        .. versionchanged:: 2.6
           Added cursor support.
        .. versionadded:: 2.3

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

        .. _aggregate command:
            https://docs.mongodb.com/manual/reference/command/aggregate
        F)closeNrG  )rP   ra   rk   r  r   r   )rY   r^  r\   r]   rq   s        r7   r]  zCollection.aggregateK	  sl    R __##000F 	-!"4??#@#+#0- ,-4;44G	-
 &,-	- 	- 	-s   "AAc                     d|v rt        d      | j                  j                  j                  rt	        d       | j
                  t        |t        fddd|S )a  Perform an aggregation and retrieve batches of raw BSON.

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

        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.aggregate_raw_batches([
          ...     {'$project': {'x': {'$multiply': [2, '$x']}}}])
          >>> for batch in cursor:
          ...     print(bson.decode_all(batch))

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

        .. versionadded:: 3.6
        r\   z/aggregate_raw_batches does not support sessionsz6aggregate_raw_batches does not support auto encryptionNFrG  )r   rP   ra   rA  r   r  r   r   )rY   r^  r]   s      r7   aggregate_raw_batchesz Collection.aggregate_raw_batches	  sz    0 $AC C ??!!,,"HJ J t?'4) (,05	)
 "() 	)r6   c
                 *    t        | |||||||||	
      S )a  Watch changes on this collection.

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

        Introduced in MongoDB 3.6.

        .. code-block:: python

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

        The :class:`~pymongo.change_stream.CollectionChangeStream` iterable
        blocks until the next change document is returned or an error is
        raised. If the
        :meth:`~pymongo.change_stream.CollectionChangeStream.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:
                with db.collection.watch(
                        [{'$match': {'operationType': 'insert'}}]) as stream:
                    for insert_change in stream:
                        print(insert_change)
            except pymongo.errors.PyMongoError:
                # The ChangeStream 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.collection.Collection.aggregate` with a
            ``$changeStream`` stage, for the purpose of supporting
            resumability.

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

        :Parameters:
          - `pipeline` (optional): 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.
          - `full_document` (optional): The fullDocument to pass as an option
            to the ``$changeStream`` stage. Allowed values: 'updateLookup'.
            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.
          - `resume_after` (optional): 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.
          - `max_await_time_ms` (optional): The maximum time in milliseconds
            for the server to wait for changes before responding to a getMore
            operation.
          - `batch_size` (optional): The maximum number of documents to return
            per batch.
          - `collation` (optional): The :class:`~pymongo.collation.Collation`
            to use for the aggregation.
          - `start_at_operation_time` (optional): 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.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `start_after` (optional): The same as `resume_after` except that
            `start_after` can resume notifications after an invalidate event.
            This option and `resume_after` are mutually exclusive.

        :Returns:
          A :class:`~pymongo.change_stream.CollectionChangeStream` cursor.

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

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

        .. versionadded:: 3.6

        .. mongodoc:: changeStreams

        .. _change streams specification:
            https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.rst
        r   )
rY   r^  full_documentresume_aftermax_await_time_ms
batch_sizerB   start_at_operation_timer\   start_afters
             r7   watchzCollection.watch	  s+    F &(M<9J	#:G 	r6   c           	         t        j                  dt        d       i }t        |t              rt        |      |d<   n|dt        j                  |d      i}| j                  |d<   t        |      |d<   ||d	<   ||d
<   |t        |      |d<   t        d|fg      }t        |j                  dd            }	|j                  |       | j                  d      5 \  }
}| j                  |
|||	ddi      d   cddd       S # 1 sw Y   yxY w)a   Perform a query similar to an SQL *group by* operation.

        **DEPRECATED** - The group command was deprecated in MongoDB 3.4. The
        :meth:`~group` method is deprecated and will be removed in PyMongo 4.0.
        Use :meth:`~aggregate` with the `$group` stage or :meth:`~map_reduce`
        instead.

        .. versionchanged:: 3.5
           Deprecated the group method.
        .. versionchanged:: 3.4
           Added the `collation` option.
        .. versionchanged:: 2.2
           Removed deprecated argument: command
        zThe group method is deprecated and will be removed in PyMongo 4.0. Use the aggregate method with the $group stage or the map_reduce method instead.r   r   z$keyfNr  r  z$reducecondinitialfinalizegrouprB   r   retvalr,   )rB   rj   )r   r   r   rL   r   r   r   _fields_list_to_dictrQ   r   r   rO   rv   rb   rr   )rY   r  	conditionr  reducer  r]   r  rz   rB   rm   rn   s               r7   r  zCollection.group,
  s'    	 @ )Q	8 c;'!#YE'N_G88eDEEkkd<i!f"i $XE*GU#$%.vzz+t/LM	

6##D#1 	F5Ji==C+4.6] ! <<DF	F 	F 	Fs   DDc           
         t        |t              st        dt        j                        |rd|v rt	        d      |d   dk(  s|d   dk(  rt	        d      d|v r|j                  d	      st	        d
      | j                  j                  d|}t        d| j                  fd|fg      }|j                  |       | j                  ||      }| j                  |      5 }| j                  j                  j                  |      5 }|j                  d||d|| j                  j                        cddd       cddd       S # 1 sw Y   nxY w	 ddd       y# 1 sw Y   yxY w)av  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:`basestring`
        (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName`
        if `new_name` is not a valid collection name.

        :Parameters:
          - `new_name`: new name for this collection
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): additional arguments to the rename command
            may be passed as keyword arguments to this helper method
            (i.e. ``dropTarget=True``)

        .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
           this collection is automatically applied to this operation when using
           MongoDB >= 3.4.

        .. 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 r;   r<   r   r?   r@   z.collecion names must not start or end with '.'r=   r>   z%collection names must not contain '$'renameCollectiontoadminT)rJ   rh   r\   ra   N)rL   r   rM   r/   r   rN   rP   rS   r   rT   rv   _write_concern_for_cmdrf   ra   rk   rl   )rY   new_namer\   r]   rz   rJ   rm   rq   s           r7   renamezCollection.renameT
  sn   : (K00;0D0DG H H 48+@AAA;#"!4NOO(?8#6#6}#EEFF"oo22H=&(8(89D(;KLM

633CA$$W- 	>''44W= > ((S"/.2doo&<&<	 ) >> >	> 	>> > >	> 	> 	>s$   #&E	+E4	EE	EE&c                     t        |t              st        dt        j                        t	        d j
                  fd|fg      |d|v rt        d      ||d<   t        |j                  dd            j                  |        fd} j                  j                  j                  | j                  |      |      S )	a  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:`basestring` (:class:`str` in python 3).

        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`. This option is only supported
            on MongoDB 3.4 and above.

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

        :Parameters:
          - `key`: name of the field for which we want to get the distinct
            values
          - `filter` (optional): A query document that specifies the documents
            from which to retrieve the distinct values.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): See list of options above.

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

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

        zkey must be an instance of distinctr  Nrb  rc  rB   c           
      R    j                  ||j                  | ddi      d   S )Nvaluesr,   )rK   rB   r\   rj   )rr   rK   )r\   rO  rm   rn   rz   rB   rY   s       r7   rQ  z!Collection.distinct.<locals>._cmd
  s>    ==3t7H7H#W%qM ! + ,45 5r6   )rL   r   rM   r/   r   rQ   r   r   rO   rv   rP   ra   rR  rc   )rY   r  r  r\   r]   rQ  rz   rB   s   `     @@r7   r  zCollection.distinct
  s    F #{+0;0D0DG H HJ,3<! "& ()KLL$F7O.vzz+t/LM	

6	5 %%55$++G4g? 	?r6   c                    t        d| j                  fd|fd|fd|fg      }t        |j                  dd            }|j	                  |       d|v }	|	rdd	i}
nd}
|xr |j                         xs |}| j                  j                  j                  ||      5 \  }}|j                  d
k\  rd|vr|	r| j                  }nd}d|vr|	s| j                  |      }nd}| j                  |||||||||
	      cddd       S # 1 sw Y   yxY w)zInternal mapReduce helper.	mapReducemapr  outrB   Ninlineresultsr,   r   readConcernr   )rK   rJ   rB   r\   rj   )r   rQ   r   rO   rv   r  rP   ra   rb   r   rK   rx   rr   )rY   r  r  r  r\   r  r]   rz   rB   r  rj   rm   rn   rK   rJ   s                  r7   _map_reducezCollection._map_reduce
  s9   K-3<f%3<! " /vzz+t/LM	

6S$a.KK@'">">"@ "! 	 __##55iI 	) N%8**a/"#-#00#S( $ 7 7 @ $==3))+#W' ! )	) 	) 	)s   AC>>Dc                    t        |t        t        j                  f      st	        dt        j
                  d       | j                  ||||t        j                  fi |}|s|j                  d      s|S t        |d   t              r,|d   d   }|d   d   }	| j                  j                  |   |	   S | j                  |d      S )a*	  Perform a map/reduce operation on this collection.

        If `full_response` is ``False`` (default) returns a
        :class:`~pymongo.collection.Collection` instance containing
        the results of the operation. Otherwise, returns the full
        response from the server to the `map reduce command`_.

        :Parameters:
          - `map`: map function (as a JavaScript string)
          - `reduce`: reduce function (as a JavaScript string)
          - `out`: output collection name or `out object` (dict). See
            the `map reduce command`_ documentation for available options.
            Note: `out` options are order sensitive. :class:`~bson.son.SON`
            can be used to specify multiple options.
            e.g. SON([('replace', <collection name>), ('db', <database name>)])
          - `full_response` (optional): if ``True``, return full response to
            this command - otherwise just return the result collection
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): additional arguments to the
            `map reduce command`_ may be passed as keyword arguments to this
            helper method, e.g.::

            >>> db.test.map_reduce(map, reduce, "myresults", limit=2)

        .. note:: The :meth:`map_reduce` method does **not** obey the
           :attr:`read_preference` of this :class:`Collection`. To run
           mapReduce on a secondary use the :meth:`inline_map_reduce` method
           instead.

        .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of
           this collection is automatically applied to this operation (if the
           output is not inline) when using MongoDB >= 3.4.

        .. 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.

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

        .. versionchanged:: 3.4
           Added the `collation` option.
        .. versionchanged:: 2.2
           Removed deprecated arguments: merge_output and reduce_output

        .. _map reduce command: http://docs.mongodb.org/manual/reference/command/mapReduce/

        .. mongodoc:: mapreduce

        z'out' must be an instance of z or a mappingr   db
collection)rL   r   r   r   rM   r/   r  r$   rw   r   rW   rP   ra   )
rY   r  r  r  full_responser\   r]   responsedbaser  s
             r7   
map_reducezCollection.map_reduce
  s    n #S[[9:1<1E1EH I I $4##Cg$2$:$:F>DF X 6O*D1X&t,EH%l3D??))%066??8H#566r6   c                 r     | j                   ||ddi|| j                  fi |}|r|S |j                  d      S )a   Perform an inline map/reduce operation on this collection.

        Perform the map/reduce operation on the server in RAM. A result
        collection is not created. The result set is returned as a list
        of documents.

        If `full_response` is ``False`` (default) returns the
        result documents in a list. Otherwise, returns the full
        response from the server to the `map reduce command`_.

        The :meth:`inline_map_reduce` method obeys the :attr:`read_preference`
        of this :class:`Collection`.

        :Parameters:
          - `map`: map function (as a JavaScript string)
          - `reduce`: reduce function (as a JavaScript string)
          - `full_response` (optional): if ``True``, return full response to
            this command - otherwise just return the result collection
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): additional arguments to the
            `map reduce command`_ may be passed as keyword arguments to this
            helper method, e.g.::

            >>> db.test.inline_map_reduce(map, reduce, limit=2)

        .. versionchanged:: 3.6
           Added ``session`` parameter.
        .. versionchanged:: 3.4
           Added the `collation` option.
        r  r,   r  )r  rI   r   )rY   r  r  r  r\   r]   rP  s          r7   inline_map_reducezCollection.inline_map_reduce.  sM    B dsFXqM7#33?7=? J779%%r6   c                 `    |j                  d      }|t        di |S | j                  |      S )Nr   r5   )r   r*   rx   )rY   rz   r\   raw_wcs       r7   r  z!Collection._write_concern_for_cmdW  s5    ()&))**733r6   c	                     t        j                  d|       t        |t              st	        d      t        |	j                  dd            t        d j                  fd|fd|fg      j                  |	       |t        j                  |d      d	<   |t        j                  |      d
<   |t        j                  d|       |d<   %t        t              st        j                         j                  |       fd}
 j                   j"                  j%                  j&                  |
|      S )zInternal findAndModify helper.r  zEreturn_document must be ReturnDocument.BEFORE or ReturnDocument.AFTERrB   NfindAndModifyrb  new
projectionfieldssortr   c           
         6|j                   dk  rt        d      	j                  st        d      d<   6|j                   dk  rt        d      	j                  st        d      d<   |j                   d	k\  r	j                  s	j                  d
<   j                  |t        j                  	| |t              }t        |       |j                  d      S )Nr   z6Must be connected to MongoDB 3.6+ to use arrayFilters.r  r     z.Must be connected to MongoDB 4.2+ to use hint.r  r  r   r   )rI   rJ   rB   r\   ri   rj   r+   )r   r   r   r   r   rr   r$   rw   _FIND_AND_MODIFY_DOC_FIELDSr    r   )
r\   rm   ri   r  r  rz   rB   r  rY   rJ   s
       r7   _find_and_modifyz6Collection.__find_and_modify.<locals>._find_and_modify{  s   (--1,() ) %11,"# # '4N#--1,HJ J$11,HJ J"F**a/%77&3&<&<N#--	30>0F0F.;*3W0?,G   IC *#.777##r6   )r   r  rL   bool
ValueErrorr   rO   r   rQ   rv   r   r  r  r
  r   r  rP   ra   r   r   )rY   r  r  r  r   return_documentr  r  r\   r]   r  rz   rB   rJ   s   `     ``   @@@r7   __find_and_modifyzCollection.__find_and_modify^  sF    	""8V4/40 M N N.vzz+t/LM	OT[[1V$?+- . 	

6!#889EGCM!11$7CK##Hf5"CMdK0..t433CA	$ 	$@ %%66&&(8'C 	Cr6   c                 <    d|d<    | j                   |||f||d|S )a  Finds a single document and deletes it, returning the document.

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

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

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

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

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

        :Parameters:
          - `filter`: A query that matches the document to delete.
          - `projection` (optional): 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}).
          - `sort` (optional): 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.
          - `hint` (optional): 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.collection.Collection.create_index`
            (e.g. ``[('field', ASCENDING)]``). This option is only supported
            on MongoDB 4.4 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): additional command arguments can be passed
            as keyword arguments (for example maxTimeMS can be used with
            recent server versions).

        .. 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.collection.Collection` 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remover  r\   )_Collection__find_and_modify)rY   r  r  r  r  r\   r]   s          r7   find_one_and_deletezCollection.find_one_and_delete  s@    F  x%t%%fj$ L+/LDJL 	Lr6   c	                 j    t        j                  |       ||	d<    | j                  |||||f||d|	S )a  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.

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

        :Parameters:
          - `filter`: A query that matches the document to replace.
          - `replacement`: The replacement document.
          - `projection` (optional): 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}).
          - `sort` (optional): 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.
          - `upsert` (optional): When ``True``, inserts a new document if no
            document matches the query. Defaults to ``False``.
          - `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.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): 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.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.collection.Collection` 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
        rv   r  )r   r  r  )
rY   r  r  r  r  r   r  r  r\   r]   s
             r7   find_one_and_replacezCollection.find_one_and_replace  sS    T 	&&{3&x%t%%fj&*FOL+/LDJL 	Lr6   c
                     t        j                  |       t        j                  d|       ||
d<    | j                  ||||||f||	d|
S )a  Finds a single document and updates it, returning either the
        original or the updated document.

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

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

          >>> 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
          >>> db.example.find_one_and_update(
          ...     {'_id': 'userid'},
          ...     {'$inc': {'seq': 1}},
          ...     return_document=ReturnDocument.AFTER)
          {u'_id': u'userid', u'seq': 1}

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

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

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

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

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

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

        :Parameters:
          - `filter`: A query that matches the document to update.
          - `update`: The update operations to apply.
          - `projection` (optional): 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}).
          - `sort` (optional): 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.
          - `upsert` (optional): When ``True``, inserts a new document if no
            document matches the query. Defaults to ``False``.
          - `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.
          - `array_filters` (optional): A list of filters specifying which
            array elements an update should apply. This option is only
            supported on MongoDB 3.6 and above.
          - `hint` (optional): 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.collection.Collection.create_index` (e.g.
            ``[('field', ASCENDING)]``). This option is only supported on
            MongoDB 4.4 and above.
          - `session` (optional): a
            :class:`~pymongo.client_session.ClientSession`.
          - `**kwargs` (optional): 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.collection.Collection` 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  rv   r  )r   r  r  r  )rY   r  rv   r  r  r   r  r  r  r\   r]   s              r7   find_one_and_updatezCollection.find_one_and_update5  sj    j 	%%f-$$_mD!x%t%%fj&*FO&3A:>.5A :@A 	Ar6   c           
      j   t        j                  dt        d       t        j                  d|       d}t        |j                  dd            }|rt        di |}t        |t              sd|v s| j                  |d|||      S | j                  d|d   i|d|d	|||
       |j                  d      S )a  Save a document in this collection.

        **DEPRECATED** - Use :meth:`insert_one` or :meth:`replace_one` instead.

        .. versionchanged:: 3.0
           Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
           operations.
        z9save is deprecated. Use insert_one or replace_one insteadr   r   to_saveNrB   r   TFrB   r5   )r   r   r   r   r   r   rO   r*   rL   r	   r   r  r   )rY   r  r   r   r]   rJ   rB   s          r7   savezCollection.save  s     	  !3	C((G<.vzz+t/LM	(262M7O48H<<z:}F F ""'$E:}# # % ;;u%%r6   c                     t        j                  dt        d       d}|rt        di |}| j	                  || |||      S )a  Insert a document(s) into this collection.

        **DEPRECATED** - Use :meth:`insert_one` or :meth:`insert_many` instead.

        .. versionchanged:: 3.0
           Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
           operations.
        z<insert is deprecated. Use insert_one or insert_many instead.r   r   Nr5   )r   r   r   r*   r   )rY   doc_or_docsr   r   continue_on_errorr]   rJ   s          r7   r   zCollection.insert  sR     	 !"4	D(262M||K->)>&
MC 	Cr6   c           
      j   t        j                  dt        d       t        j                  d|       t        j                  d|       |r't        t        |            }|j                  d      rd}d}	t        |j                  d	d            }
|rt        di |}	| j                  |||||||	|

      S )a'  Update a document(s) in this collection.

        **DEPRECATED** - Use :meth:`replace_one`, :meth:`update_one`, or
        :meth:`update_many` instead.

        .. versionchanged:: 3.0
           Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
           operations.
        zIupdate is deprecated. Use replace_one, update_one or update_many instead.r   r   specr   r=   FNrB   r  r5   )r   r   r   r   r  nextiterrN   r   rO   r*   r  )rY   r  r   r   r   r   r   r]   firstrJ   rB   s              r7   rv   zCollection.update  s     	 -.@Q	P""640"":x8 h(E$"
.vzz+t/LM	(262M%%(FJzY & 0 	0r6   c                     t        j                  dt        d       |i }t        |t        j
                        sd|i}d}t        |j                  dd            }|rt        di |}| j                  ||||      S )	a  Remove a document(s) from this collection.

        **DEPRECATED** - Use :meth:`delete_one` or :meth:`delete_many` instead.

        .. versionchanged:: 3.0
           Removed the `safe` parameter. Pass ``w=0`` for unacknowledged write
           operations.
        z<remove is deprecated. Use delete_one or delete_many instead.r   r   Nr   rB   r  r5   )
r   r   r   rL   r   r   r   rO   r*   r2  )rY   
spec_or_idr   r]   rJ   rB   s         r7   r  zCollection.remove  s     	 !"4	DJ*ckk2,J.vzz+t/LM	(262M%%}	 & C 	Cr6   c                     t        j                  dt        d       |s|j                  dd      st	        d      |r|j                  dd      rt	        d      |r||d<   |r||d	<   |r||d
<   |rt        |t              rt        j                  |      |d<   n[t        |t              st        |t              r0t        |      dk(  r"t        j                  dt        d       ||d<   nt        d      |j                  dd      }|t        j                  |d      |d<   t        |j                  dd            t!        d j"                  fg      j%                  |        j'                  d       fd}	 j(                  j*                  j-                  j.                  |	d      }
|r|
S |
j                  d      }|r j(                  j1                  |       }|S )zUpdate and return an object.

        **DEPRECATED** - Use :meth:`find_one_and_delete`,
        :meth:`find_one_and_replace`, or :meth:`find_one_and_update` instead.
        zlfind_and_modify is deprecated, use find_one_and_delete, find_one_and_replace, or find_one_and_update insteadr   r   r  NzMust either update or removezCan't do both update and removerb  rv   r   r  r,   z\Passing mapping types for `sort` is deprecated, use a list of (key, direction) pairs insteadzdsort must be a list of (key, direction) pairs, a dict of len 1, or an instance of SON or OrderedDictr  rB   r  c           	          |j                   dk\  rj                  sj                  d<   j                  |t        j
                  | |t              }t        |       |S )Nr   r   )rI   rB   r\   ri   rj   )r   r   r   rr   r$   rw   r  r    )r\   rm   ri   r   rz   rB   rY   rJ   s       r7   r  z4Collection.find_and_modify.<locals>._find_and_modifyL  sd    **a/%77&3&<&<N#]]30F0F#7	 # 9F *&1Mr6   r+   )r   r   r   r   r  rL   rs  r   r  r   rW   lenrM   rO   r  r   r   rQ   rv   r  rP   ra   r   r   _fix_outgoing)rY   rb  rv   r   r  r  r   r]   r  r  r  r   rz   rB   rJ   s   `           @@@r7   find_and_modifyzCollection.find_and_modify  s    	 O(Q	8 fjj48;<<fjj40>?? #F7O%F8%F8$%!(!8!8!>v T=1T4(SY!^ N0Q@ "&v !5 6 6 Hd+&;;FHMF8.vzz+t/LM	OT[[123

633C>	 oo$$55&&(8$@ Jwww'H??884HOr6   c                     | S r`   r5   r   s    r7   __iter__zCollection.__iter__d  s    r6   c                     t        d      )Nz#'Collection' object is not iterable)rM   r   s    r7   __next__zCollection.__next__g  s    =>>r6   c                     d| j                   vrt        d| j                   z        t        d| j                   j                  d      d   z        )zJThis is only here so that some API misusages are easier to debug.
        r?   z'Collection' object is not callable. If you meant to call the '%s' method on a 'Database' object it is failing because no such method exists.z'Collection' object is not callable. If you meant to call the '%s' method on a 'Collection' object it is failing because no such method exists.r@   )rQ   rM   splitr?  s      r7   __call__zCollection.__call__l  sc     dkk! & !KK	( ) )
  A ))#.r23 4 	4r6   )FNNNNN)FNNTNNNNNFN)NNNN)F)TFN)TTFNNFN)FN)FTFFNNTFNNNNF)FTFFNNTFNNNN)FFNNN)FFNNNN)FNFNNNr`   )NNTNNNF)NNTNNN)NNN)NN)i,  )	NNNNNNNNN)TT)TTF)FFFT)NT)Sr/   r0   r1   r2   rG   rb   rf   rr   rU   r   r   r   r   r   propertyr   rS   rZ   r   r   r   r   r   r   r   r   r   r  r  r  r   r"  r'  r/  r2  r7  r9  r=  r;  rB  rJ  rS  rW  rZ  r`  rY  rg  rf  rz  r  r  r  r  r  r  ry   r  r]  r  r  r  r  r  r  r  r  r  r.   r3   r  r  r  r  r  r   rv   r  r	  r  r  r   r  __classcell__)r^   s   @r7   r9   r9   N   s4    DHHLm!^9B 5:!%BF"#!&!5)n6& -E!         @D6:%=NM>L@ ,0=AP*d/b/"b 6:<@.2,\ ?D0(d .2>B:Jx =B9>8<DH9>	Vr .35:48@D#( 7<@D'+L(\ 16.3<@K(Z GK@D'+J(X:8 59EJ6t 59/3 *(X*(X DH-T 5DUn?, EI+ 2P?dM4^&AP/bgIR"H886+p/!b8&t D$L/&O-b&)P EIAEFJfP&FP3>j5?n%)NE7N'&R4 BF*8*?*?(,4>CB >B$(ELP )-4-;-B-B"&NLb (,$u,:,A,A*.T4{Az&8 .227C$ ?D'+0BC, %'t$4u#(KZ? D4r6   r9   )Fr2   r   r   	bson.coder   bson.objectidr   bson.py3compatr   r   r   r   bson.raw_bsonr	   bson.codec_optionsr
   bson.sonr   pymongor   r   r   pymongo.aggregationr   r   pymongo.bulkr   r   pymongo.command_cursorr   r   pymongo.commonr   pymongo.collationr   pymongo.change_streamr   pymongo.cursorr   r   pymongo.errorsr   r   r   r   r   pymongo.helpersr    r!   pymongo.messager"   pymongo.operationsr#   pymongo.read_preferencesr$   pymongo.resultsr%   r&   r'   r(   r)   pymongo.write_concernr*   rR   r  rl  objectr.   
BaseObjectr9   r5   r6   r7   <module>r*     s    ,    ") ) * +  C 4 G ( 8 8 1. .
0 : ) 3+ +
 /	&l E 
<V 
<j44"" j44r6   