+\h8dZddlmZddlZddlmZddlmZmZm Z m Z m Z m Z m Z mZmZmZmZmZmZmZmZmZmZddlmZmZddlmZddlmZdd lm Z dd l!m"Z"dd l#m$Z$m%Z%m&Z&m'Z'm(Z(dd l)m*Z*dd l+m,Z,m-Z-ddl.m/Z/m0Z0m1Z1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBddlCmDZDddlEmFZFmGZGddlHmIZImJZJmKZKmLZLmMZMddlNmOZOmPZPddlQmRZRddlSmTZTddlUmVZVmWZWddlXmYZYmZZZddl[m\Z\m]Z]m^Z^m_Z_ddl`maZambZbmcZcdZdedZeddiZfee;e]e9e8efZgGd d!Zher.ddliZidd"l)mjZjdd#lCmkZkdd$lNmlZldd%lmmnZndd&lompZpdd'lqmrZrdd(lsmtZtGd)d*e&je e]Zvy)+z%Collection level utilities for Mongo.) annotationsN)abc) TYPE_CHECKINGAnyCallableContextManagerGenericIterableIteratorMappingMutableMappingNoReturnOptionalSequenceTypeTypeVarUnioncastoverload)DEFAULT_CODEC_OPTIONS CodecOptions)ObjectId)RawBSONDocument)SON) Timestamp) ASCENDING_csotcommonhelpers_sharedmessage)validate_collation_or_none)_ecoc_coll_name_esc_coll_name)ConfigurationError InvalidNameInvalidOperationOperationFailure)_check_write_command_response)_UNICODE_REPLACE_CODEC_OPTIONS) DeleteMany DeleteOne IndexModel InsertOne ReplaceOneSearchIndexModel UpdateMany UpdateOne _IndexKeyHint _IndexList_Op)DEFAULT_READ_CONCERN)ReadPreference _ServerMode)BulkWriteResult DeleteResultInsertManyResultInsertOneResult UpdateResult)_CollectionAggregationCommand _CollectionRawAggregationCommand)_Bulk)CollectionChangeStream) CommandCursorRawBatchCommandCursor)CursorRawBatchCursor) _CollationIn _DocumentType_DocumentTypeArg _Pipeline)DEFAULT_WRITE_CONCERN WriteConcernvalidate_booleanTTvalueceZdZdZdZ dZy)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__BEFOREAFTERa/root/niggaflix-v3/playground/venv/lib/python3.12/site-packages/pymongo/synchronous/collection.pyrPrPps F E;rXrP) Collation) ReadConcern)_AggregationCommand) ClientSessionDatabase) Connection)Serverc  eZdZdZ dI dJfd ZdKdZdKdZdLdZdMdZdMd Z dNd Z dOd Z e dLd Z e dLd Ze dPdZe dQ dRdZe dS dTdZ dU dVdZ dWdZdZdOdZeZdXdZ dY dZdZ d[dZ d\ d]dZ d^ d_dZ d`dZej: da dbdZ dc dddZ de dfdZ ej: dg dhdZ! di djdZ" dk dldZ# dm dnd Z$ do dpd!Z% dm dqd"Z& de drd#Z' ds dtd$Z( du dvd%Z) dw dxd&Z* dw dxd'Z+ dc dyd(Z,dzd)Z-d{d*Z. d|d+Z/ d}d,Z0dcd~d-Z1 d dd.Z2 dd/Z3 d dd0Z4ej: dd1Z5 d dd2Z6 d dd3Z7ej: d dd4Z8ej: d dd5Z9 d dd6Z: d dd7Z; d dd8Z< de dd9Z= d dd:Z> d dd;Z? d dd<Z@ d dd=ZA d dd>ZB d dd?ZCej: d dd@ZD de ddAZE d ddBZFej: d ddCZG dU ddDZHdeIjddddf ddEZK d ddFZLdddeIjddddf ddGZMdddeIjdddddf ddHZNxZOS) CollectionzA Mongo collection.FNc  t ||xs |j|xs |j|xs |j|xs |j t |tstdt|ddl m } t || sFtdt|jDs!tdt|j|rd|vr tdd|vr|j!d std |z|dd k(s|d d k(rtd |zd|vr td||_||_|j"j&d |j$|_|jj+dt,|_|j0j2j4|_|s| r@t8r/t;j<dt>d|jA| |ytCdy)a Get / create a Mongo collection. Raises :class:`TypeError` if `name` is not an instance of :class:`str`. Raises :class:`~pymongo.errors.InvalidName` if `name` is not a valid collection name. Any additional keyword arguments will be used as options passed to the create command. See :meth:`~pymongo.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. :param database: the database to get a collection from :param name: the name of the collection to get :param create: If ``True``, force collection creation even without options being set. :param codec_options: An instance of :class:`~bson.codec_options.CodecOptions`. If ``None`` (the default) database.codec_options is used. :param read_preference: The read preference to use. If ``None`` (the default) database.read_preference is used. :param write_concern: An instance of :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the default) database.write_concern is used. :param read_concern: An instance of :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the default) database.read_concern is used. :param collation: An instance of :class:`~pymongo.collation.Collation`. If a collation is provided, it will be passed to the create collection command. :param session: A :class:`~pymongo.client_session.ClientSession` that is used with the create collection command. :param kwargs: Additional keyword arguments will be passed as options for the create collection command. .. versionchanged:: 4.2 Added the ``clusteredIndex`` and ``encryptedFields`` parameters. .. versionchanged:: 4.0 Removed the reindex, map_reduce, inline_map_reduce, parallel_scan, initialize_unordered_bulk_op, initialize_ordered_bulk_op, group, count, insert, save, update, remove, find_and_modify, and ensure_index methods. See the :ref:`pymongo4-migration-guide`. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Support the `collation` option. .. versionchanged:: 3.2 Added the read_concern option. .. versionchanged:: 3.0 Added the codec_options, read_preference, and write_concern options. Removed the uuid_subtype attribute. :class:`~pymongo.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__ .. seealso:: The MongoDB documentation on `collections `_. z%name must be an instance of str, not rr^c3:K|]}|jdk(yw)r_N)rQ).0clss rY z&Collection.__init__..sTcs||z1TszDatabase required but given .. collection names cannot be empty$) oplog.$mainz$cmdz)collection names must not contain '$': %r.z3collection names must not start or end with '.': %rz4collection names must not contain the null characterreplace)unicode_decode_error_handlerdocument_classzcThe `create` and `kwargs` arguments to Collection are deprecated and will be removed in PyMongo 5.0) stacklevelz?Collection does not support the `create` or `kwargs` arguments.N)"super__init__ codec_optionsread_preference write_concern read_concern isinstancestr TypeErrortypepymongo.synchronous.databaser_any__mro__rQr% startswith _database_namename _full_name_replacedict_write_response_codec_optionsclientoptionstimeout_timeout_IS_SYNCwarningswarnDeprecationWarning_create ValueError) selfdatabasercreaterwrxryrzsessionkwargsr_ __class__s rYrvzCollection.__init__sn   3X33  7x77  3X33  1H11  $$CDJ<PQ Q9(H-TT(^=S=STT">tH~?V?V>W XYYtt|@A A $;0G HIDPQ Q 7c>T"X_SVZZ[ [ T>TU U2: !^^0014::,?-1-?-?-H-H)24.I. *!//77 V y&   VW- !bccrXc |jdr;|jd|}tt|jd|d|d|d|j |S)zGet a sub-collection of this collection by name. Raises InvalidName if an invalid collection name is used. :param name: the name of the collection to get _rmz has no attribute z. To access the z collection, use database['z'].)rrAttributeErrorr~rQ __getitem__)rr full_names rY __getattr__zCollection.__getattr__sr ??3 ::,av.I :&&''9$AQR[Q\-i[= %%rXc t|j|jd|d|j|j|j |j S)NrmFrcrrrwrxryrz)rrs rYrzCollection.__getitem__sO NNzzl!D6 "             rXcft|jd|jd|jdS)N(z, ))r~rQrrrs rY__repr__zCollection.__repr__(s/t*%%&a'9DJJ>KKrXct|tr4|j|jk(xr|j|j k(St SN)r{rcrrrrNotImplementedrothers rY__eq__zCollection.__eq__+s7 eZ (>>U^^3P ejj8P PrXc||k( SrrWrs rY__ne__zCollection.__ne__0s5=  rXcDt|j|jfSr)hashrrrs rY__hash__zCollection.__hash__3sT^^TZZ011rXcDtt|jd)Nzq objects do not implement truth value testing or bool(). Please compare with None instead: collection is not None)NotImplementedErrorr~rQrs rY__bool__zCollection.__bool__6s)!Dz""#$8 8  rXc|jS)zzThe full name of this :class:`Collection`. The full name is of the form `database_name.collection_name`. )rrs rYrzCollection.full_name=s rXc|jS)z%The name of this :class:`Collection`.)rrs rYrzCollection.nameEszzrXc|jS)zdThe :class:`~pymongo.database.Database` that this :class:`Collection` is a part of. )rrs rYrzCollection.databaseJs ~~rXcyrrWrrwrxryrzs rY with_optionszCollection.with_optionsQ rXcyrrWrs rYrzCollection.with_options[rrXc t|j|jd|xs |j|xs |j|xs |j |xs |j S)aGet a clone of this collection changing the specified settings. >>> coll1.read_preference Primary() >>> from pymongo import ReadPreference >>> coll2 = coll1.with_options(read_preference=ReadPreference.SECONDARY) >>> coll1.read_preference Primary() >>> coll2.read_preference Secondary(tag_sets=None) :param codec_options: An instance of :class:`~bson.codec_options.CodecOptions`. If ``None`` (the default) the :attr:`codec_options` of this :class:`Collection` is used. :param read_preference: 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. :param write_concern: An instance of :class:`~pymongo.write_concern.WriteConcern`. If ``None`` (the default) the :attr:`write_concern` of this :class:`Collection` is used. :param read_concern: An instance of :class:`~pymongo.read_concern.ReadConcern`. If ``None`` (the default) the :attr:`read_concern` of this :class:`Collection` is used. Frrs rYrzCollection.with_optionses[F NN JJ   /T//  3t33  /T//  -D--  rXc`|jd}| tdi|S|j|S)N writeConcernrW)getrJ_write_concern_for)rcmdrraw_wcs rY_write_concern_for_cmdz!Collection._write_concern_for_cmds7(  )&) )**73 3rXctd)Nz#'Collection' object is not iterable)r}rs rY__next__zCollection.__next__s=>>rXc*d|jvr/tdt|jd|jztdt|jdt|jd|jj ddz)zAThis is only here so that some API misusages are easier to debug.rm'z' object is not callable. If you meant to call the '%s' method on a 'Database' object it is failing because no such method exists.zE' object is not callable. If you meant to call the '%s' method on a 'z5' object it is failing because no such method exists.rn)rr}r~rQsplitrargsrs rY__call__zCollection.__call__s djj DJ''()!JJ'  T ##$%**.t**=*=)>?5 57;zz7G7G7LR7P Q  rXc Tt|||||||||| | | | } | j| S)aWatch 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. .. 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.coll.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. :param pipeline: A list of aggregation pipeline stages to append to an initial ``$changeStream`` stage. Not all pipeline stages are valid after a ``$changeStream`` stage, see the MongoDB documentation on change streams for the supported stages. :param full_document: The fullDocument to pass as an option to the ``$changeStream`` stage. Allowed values: 'updateLookup', 'whenAvailable', 'required'. When set to 'updateLookup', the change notification for partial updates will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred. :param full_document_before_change: Allowed values: 'whenAvailable' and 'required'. Change events may now result in a 'fullDocumentBeforeChange' response field. :param resume_after: A resume token. If provided, the change stream will start returning changes that occur directly after the operation specified in the resume token. A resume token is the _id value of a change document. :param max_await_time_ms: The maximum time in milliseconds for the server to wait for changes before responding to a getMore operation. :param batch_size: The maximum number of documents to return per batch. :param collation: The :class:`~pymongo.collation.Collation` to use for the aggregation. :param start_at_operation_time: If provided, the resulting change stream will only return changes that occurred at or after the specified :class:`~bson.timestamp.Timestamp`. Requires MongoDB >= 4.0. :param session: a :class:`~pymongo.client_session.ClientSession`. :param start_after: The same as `resume_after` except that `start_after` can resume notifications after an invalidate event. This option and `resume_after` are mutually exclusive. :param comment: A user-provided comment to attach to this command. :param show_expanded_events: Include expanded events such as DDL events like `dropIndexes`. :return: A :class:`~pymongo.change_stream.CollectionChangeStream` cursor. .. versionchanged:: 4.3 Added `show_expanded_events` parameter. .. versionchanged:: 4.2 Added ``full_document_before_change`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.9 Added the ``start_after`` parameter. .. versionchanged:: 3.7 Added the ``start_at_operation_time`` parameter. .. versionadded:: 3.6 .. seealso:: The MongoDB documentation on `changeStreams `_. .. _change streams specification: https://github.com/mongodb/specifications/blob/master/source/change-streams/change-streams.md )r@_initialize_cursor)rpipeline full_document resume_aftermax_await_time_ms batch_size collationstart_at_operation_timer start_aftercommentfull_document_before_changeshow_expanded_events change_streams rYwatchzCollection.watchsJt/        #    '  ((*rXcN|jjj||Sr)rr_conn_for_writes)rr operations rYrzCollection._conn_for_writes?s!~~$$55gyIIrXc H|jjj| 5} |j|jj||xs|j | |xs |j ||||d| | |jj| | cdddS#1swYyxYw)aInternal command helper. :param conn` - A Connection instance. :param command` - The command itself, as a :class:`~bson.son.SON` instance. :param read_preference` (optional) - The read preference to use. :param codec_options` (optional) - An instance of :class:`~bson.codec_options.CodecOptions`. :param check: raise OperationFailure if there are errors :param allowable_errors: errors to ignore if `check` is True :param read_concern` (optional) - An instance of :class:`~pymongo.read_concern.ReadConcern`. :param write_concern: An instance of :class:`~pymongo.write_concern.WriteConcern`. :param collation` (optional) - An instance of :class:`~pymongo.collation.Collation`. :param session: a :class:`~pymongo.client_session.ClientSession`. :param retryable_write: True if this command is a retryable write. :param user_fields: Response fields that should be decoded using the TypeDecoders from codec_options, passed to bson._decode_all_selective. :return: The result document. T)rzryparse_write_concern_errorrrrretryable_write user_fieldsN)rr _tmp_sessioncommandr_read_preference_forrw)rconnrrxrwcheckallowable_errorsrzryrrrrss rY_commandzCollection._commandDsP^^ " " / / 8 A<<##E4#<#= 21 (MongoDB >=7.0))rxryrrN) floatupdaterr4CREATEmax_wire_versionr$rr6PRIMARYr) rrrrrencrypted_fields qev2_requiredrrs rY_create_helperzCollection._create_helper~s (. %5C! "  "'"8 JJw   " "7cjj " A T!6!6!;(**.*?*?)@@np MM . 6 6"55g>#     s AB==Cct|jdd}|jdd}|rtjd|dddiddi}|j t ||j |d|d |j t||j |d||j |j |||| |jd tfg|y|j |j |||y) NrrrclusteredIndex_idrNT)keyunique)r)r__safeContent__) r!poprvalidate_is_mappingrr#rr" create_indexr)rrrrroptss rYrzCollection._creates /w{{;/MN ";;'8$?   & &'9;K L$uajD&IJD   /<"     0@$** MtUY[b c    GYJZ      19=> H    GY HrXcPtjd|t|||||}|D]} |j||j |} |j| |tj} | t| dStidS#t$rt |ddwxYw)a Send a batch of write operations to the server. Requests are passed as a list of write operation instances ( :class:`~pymongo.operations.InsertOne`, :class:`~pymongo.operations.UpdateOne`, :class:`~pymongo.operations.UpdateMany`, :class:`~pymongo.operations.ReplaceOne`, :class:`~pymongo.operations.DeleteOne`, or :class:`~pymongo.operations.DeleteMany`). >>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634ef')} {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} >>> # DeleteMany, UpdateOne, and UpdateMany are also available. ... >>> from pymongo import InsertOne, DeleteOne, ReplaceOne >>> requests = [InsertOne({'y': 1}), DeleteOne({'x': 1}), ... ReplaceOne({'w': 1}, {'z': 1}, upsert=True)] >>> result = 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) ... {'x': 1, '_id': ObjectId('54f62e60fba5226811f634f0')} {'y': 1, '_id': ObjectId('54f62ee2fba5226811f634f1')} {'z': 1, '_id': ObjectId('54f62ee28891e756a6e1abd5')} :param requests: A list of write operations (see examples above). :param ordered: If ``True`` (the default) requests will be performed on the server serially, in the order provided. If an error occurs all remaining operations are aborted. If ``False`` requests will be performed on the server in arbitrary order, possibly in parallel, and all operations will be attempted. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :return: An instance of :class:`~pymongo.results.BulkWriteResult`. .. seealso:: :ref:`writes-and-ids` .. note:: `bypass_document_validation` requires server version **>= 3.2** .. versionchanged:: 4.1 Added ``comment`` parameter. Added ``let`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.2 Added bypass_document_validation support .. versionadded:: 3.0 requests)rletz is not a valid requestNTF) r validate_listr? _add_to_bulkrr}rexecuter4INSERTr8) rrorderedbypass_document_validationrrrblkrequestrybulk_api_results rY bulk_writezCollection.bulk_writesf Z2D'#=wTWX QG Q$$S) Q //8 ++mWcjjI  &"?D9 9r5))" Q7+-D EFDP Qs B  B%cF xs jj}j||gd || d< d fd } jjj || |t jt|ts|jdSy)z0Internal helper for inserting a single document.)insertr  documentsNrc d<|jjjj|jj|}t |y)NbypassDocumentValidationryrwrrr)rrrrrr()rrrresultbypass_doc_valrrrys rY_insert_commandz/Collection._insert_one.._insert_command-sb)6D23\\##+"@@~~,, /"F *& 1rXrr)rOptional[ClientSession]rr`rboolreturnNone) ry acknowledgedrrr_retryable_writer4rr{rr) rdocr ryop_idrrrrrrs ` ` ` @rY _insert_onezCollection._insert_ones&;);); $11 !YY7#O  !(GI  2, 24> 2QU 2  2 2$ .. /7cjj / #/775> !rXc tjd|t|tsd|vs t |d<|j |}t |j|d|d||||jS)a6Insert 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}) {'x': 1, '_id': ObjectId('54f112defba522406c9cc208')} :param document: The document to insert. Must be a mutable mapping type. If the document does not have an _id field one will be added automatically. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :return: - An instance of :class:`~pymongo.results.InsertOneResult`. .. seealso:: :ref:`writes-and-ids` .. note:: `bypass_document_validation` requires server version **>= 3.2** .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.2 Added bypass_document_validation support .. versionadded:: 3.0 documentrTN)r ryrrrr) rvalidate_is_document_typer{rrrr;r r)rr"r rrrys rY insert_onezCollection.insert_oneGs\ ((X>8_5(9J&jHUO//8    +9    & &  rXcr ttjrttjss t dg d fd }|j |}t ||||}t||_|j||tjt |jS)a8Insert 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 :param documents: A iterable of documents to insert. :param ordered: If ``True`` (the default) documents will be inserted on the server serially, in the order provided. If an error occurs all remaining inserts are aborted. If ``False``, documents will be inserted on the server in arbitrary order, possibly in parallel, and all document inserts will be attempted. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :return: An instance of :class:`~pymongo.results.InsertManyResult`. .. seealso:: :ref:`writes-and-ids` .. note:: `bypass_document_validation` requires server version **>= 3.2** .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.2 Added bypass_document_validation support .. versionadded:: 3.0 z"documents must be a non-empty listc3KD]a}tjd|t|ts%d|vr t |d<j |dt j|fcyw)z6A generator that validates documents and handles _ids.r"rN)rr#r{rrappendr _INSERT)r"r inserted_idss rYgenz#Collection.insert_many..gensd% 200XF!(O<H,*2* ''811  2sA(A+)r)rz'Iterator[tuple[int, Mapping[str, Any]]])r{rr r r}rr?listopsrr4rr:r) rrr r rrr*ryr r)s ` @rY insert_manyzCollection.insert_manysh9cll3)S[[1@A A')  2//8 D'#=wOsu+ M7CJJ7 m.H.HIIrXc ttd|t| } |xs |j}|j}||||d}| |s t d| |d<| |s t d| |d<| F|s|j dkr t d t | tstj| } | |d <|7|s|j d kr t d tjd |||d <|j||gd}|tjd|||d<|||d<| | |d<|j|jj|||j| |jj |j#}t%||j'dr d|vrd|d<nd|d<d|vr|ddd|d<|sy|S)!Internal update / replace helper.upsert)qumultir0N3Collation is unsupported for unacknowledged writes.r6arrayFilters is unsupported for unacknowledged writes. arrayFilterszPMust be connected to MongoDB 4.2+ to use hint on unacknowledged update commands.hintzPMust be connected to MongoDB 8.0+ to use sort on unacknowledged update commands.sort)rr updatesrrrrnupsertedTupdatedExistingFrr)rKr!ryrr$rr{r|r_index_documentrrrrrrrcopyr(r)rrcriteriar"r0r3ryrr rr array_filtersr8rrrr:rr update_docrrs rY_updatezCollection._updates* 6*.y9 %;);); $11  &  ()^__*3 ;'  $()abb-: >*  D$9$9A$=(fdC(%55d;!%Jv   D$9$9B$>(f  & &vt 4!%Jv !YY7 |T ?  & &uc 2 GEN  !(GI   %2@G. / LL##+"@@~~,, /   $&  &f- ::c?z7(,F$ %(-F$ %V#%+J%7%:5%Az" rXc  d  fd }jjjxs jjxr || |S)r/cHj|   || S)N)r0r3ryrr rrrBr8rrrr:r)rD)rrrrBrrrrAr"r8rr3rr rr:r0rys rYrDz-Collection._update_retryable.._updateGsN<<+-#+ /#  rX)rrrr`rrrOptional[Mapping[str, Any]])rrrryr)rrAr"rr0r3ryrr rrrBr8rrr:rrDs``` ````````` ``` rY_update_retryablezCollection._update_retryable2sv* , 4> QU  (   .~~$$55  0d00 > > Lu9      rXc (tjd|tj||tjd||j|} t |j ||t j|| |||||| |  | jS)a Replace a single document matching the filter. >>> for doc in db.test.find({}): ... print(doc) ... {'x': 1, '_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) ... {'y': 1, '_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}) {'x': 1, '_id': ObjectId('54f11e5c8891e756a6e1abd4')} :param filter: A query that matches the document to replace. :param replacement: The new document. :param upsert: If ``True``, perform an insert if no documents match the filter. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param collation: An instance of :class:`~pymongo.collation.Collation`. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.2 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :param sort: Specify which document the operation updates if the query matches multiple documents. The first document matched by the sort order will be updated. This option is only supported on MongoDB 8.0 and above. :return: - An instance of :class:`~pymongo.results.UpdateResult`. .. versionchanged:: 4.11 Added ``sort`` parameter. .. versionchanged:: 4.1 Added ``let`` parameter. Added ``comment`` parameter. .. versionchanged:: 3.11 Added ``hint`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the `collation` option. .. versionchanged:: 3.2 Added bypass_document_validation support. .. versionadded:: 3.0 filterr)ryrrr8rrr:r) rrvalidate_ok_for_replacerr<rHr4UPDATEr) rrJ replacementr0r rr8rrr:rrys rY replace_onezCollection.replace_oneesl ""8V4&&{3 ?  & &uc 2//8   " " +9# #   & &  rXc &tjd|tj|tjd||j |} t |j ||tj|| |||||| | |  | jS)at Update a single document matching the filter. >>> for doc in db.test.find(): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_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) ... {'x': 4, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} If ``upsert=True`` and no documents match the filter, create a new document based on the filter criteria and update modifications. >>> result = db.test.update_one({'x': -10}, {'$inc': {'x': 3}}, upsert=True) >>> result.matched_count 0 >>> result.modified_count 0 >>> result.upserted_id ObjectId('626a678eeaa80587d4bb3fb7') >>> db.test.find_one(result.upserted_id) {'_id': ObjectId('626a678eeaa80587d4bb3fb7'), 'x': -7} :param filter: A query that matches the document to update. :param update: The modifications to apply. :param upsert: If ``True``, perform an insert if no documents match the filter. :param bypass_document_validation: (optional) If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param collation: An instance of :class:`~pymongo.collation.Collation`. :param array_filters: A list of filters specifying which array elements an update should apply. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.2 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param sort: Specify which document the operation updates if the query matches multiple documents. The first document matched by the sort order will be updated. This option is only supported on MongoDB 8.0 and above. :param comment: A user-provided comment to attach to this command. :return: - An instance of :class:`~pymongo.results.UpdateResult`. .. versionchanged:: 4.11 Added ``sort`` parameter. .. versionchanged:: 4.1 Added ``let`` parameter. Added ``comment`` parameter. .. versionchanged:: 3.11 Added ``hint`` parameter. .. versionchanged:: 3.9 Added the ability to accept a pipeline as the ``update``. .. versionchanged:: 3.6 Added the ``array_filters`` and ``session`` parameters. .. versionchanged:: 3.4 Added the ``collation`` option. .. versionchanged:: 3.2 Added ``bypass_document_validation`` support. .. versionadded:: 3.0 rJrB) ryrrrBr8rrr:r rrvalidate_ok_for_updatevalidate_list_or_nonerr<rHr4rLr) rrJrr0r rrBr8rrr:rrys rY update_onezCollection.update_ones@ ""8V4%%f-$$_mD//8   " " +9#+ #   & &!  rXc &tjd|tj|tjd||j |} t |j ||tj|d| |||||| |  | jS)a Update one or more documents that match the filter. >>> for doc in db.test.find(): ... print(doc) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_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) ... {'x': 4, '_id': 0} {'x': 4, '_id': 1} {'x': 4, '_id': 2} :param filter: A query that matches the documents to update. :param update: The modifications to apply. :param upsert: If ``True``, perform an insert if no documents match the filter. :param bypass_document_validation: If ``True``, allows the write to opt-out of document level validation. Default is ``False``. :param collation: An instance of :class:`~pymongo.collation.Collation`. :param array_filters: A list of filters specifying which array elements an update should apply. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.2 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :return: - An instance of :class:`~pymongo.results.UpdateResult`. .. versionchanged:: 4.1 Added ``let`` parameter. Added ``comment`` parameter. .. versionchanged:: 3.11 Added ``hint`` parameter. .. versionchanged:: 3.9 Added the ability to accept a pipeline as the `update`. .. versionchanged:: 3.6 Added ``array_filters`` and ``session`` parameters. .. versionchanged:: 3.4 Added the `collation` option. .. versionchanged:: 3.2 Added bypass_document_validation support. .. versionadded:: 3.0 rJrBT) r3ryrrrBr8rrrrP) rrJrr0rBr rr8rrrrys rY update_manyzCollection.update_manyJsZ ""8V4%%f-$$_mD//8   " " +9#+ #   & &!  rXc |jjj|jj|j|j |j |j}|j|j|||y)aEAlias for :meth:`~pymongo.database.Database.drop_collection`. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param encrypted_fields: **(BETA)** Document that describes the encrypted fields for Queryable Encryption. The following two calls are equivalent: >>> db.foo.drop() >>> db.drop_collection("foo") .. versionchanged:: 4.2 Added ``encrypted_fields`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.7 :meth:`drop` now respects this :class:`Collection`'s :attr:`write_concern`. .. versionchanged:: 3.6 Added ``session`` parameter. )rrrN) rr get_databaserrwrxryrzdrop_collectionr)rrrrdbos rYdropzCollection.dropss@nn##00 NN                JJK[  rXc jtjd||xs |j}|j} |t | d}t |}|| s t d||d<|F| s|jdkr t dt|tstj|}||d<|j||gd}| tjd | | |d <| | |d <|j|jj|||j | |jj"| }t%||S) Internal delete helper.rJ)r1limitr4r zPMust be connected to MongoDB 4.4+ to use hint on unacknowledged delete commands.r8)deleter deletesrrr)rrryrintr!r$rr{r|rr?rr#rrrrr()rrrAr3ryrr rr8rrrrr delete_docrrs rY_deletezCollection._deletesG ""8X6%;);); $11 #ce)n= .y9  ()^__*3 ;'  D$9$9A$=(fdC(%55d;!%Jv !YY7 |T ?  , ,UC 8 GEN  !(GI  NN   '<<>>((+  &f- rXc  d  f d } jjjxs jjxr | |t j S)r\c> j| || S)N) ryrr rr8rrrr)rc) rrrrrrAr8rr3rr rrys rYrcz-Collection._delete_retryable.._delete!s?<<+# /  rXr)rrrr`rrrMapping[str, Any])rrrryrr4DELETE) rrAr3ryrr rr8rrrrcs ```````` `` rY_delete_retryablezCollection._delete_retryablesz , 4> QU    $~~$$55  0d00 > > Lu9  jj 6  rXc ~|j|}t|j|d|||||||jS)asDelete 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 :param filter: A query that matches the document to delete. :param collation: An instance of :class:`~pymongo.collation.Collation`. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.4 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :return: - An instance of :class:`~pymongo.results.DeleteResult`. .. versionchanged:: 4.1 Added ``let`` parameter. Added ``comment`` parameter. .. versionchanged:: 3.11 Added ``hint`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the `collation` option. .. versionadded:: 3.0 Fryrr8rrrrr9rhrrrJrr8rrrrys rY delete_onezCollection.delete_one:sXd//8   " "+# #   & &  rXc ~|j|}t|j|d|||||||jS)ayDelete 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 :param filter: A query that matches the documents to delete. :param collation: An instance of :class:`~pymongo.collation.Collation`. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.4 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :return: - An instance of :class:`~pymongo.results.DeleteResult`. .. versionchanged:: 4.1 Added ``let`` parameter. Added ``comment`` parameter. .. versionchanged:: 3.11 Added ``hint`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the `collation` option. .. versionadded:: 3.0 Trjrkrls rY delete_manyzCollection.delete_many{sXd//8   " "+# #   & &  rXc|t|tjsd|i}|j|g|i|}|j dD]}|cSy)aoGet 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`. :param filter: a dictionary specifying the query to be performed OR any other type to be used as the value for a query for ``"_id"``. :param args: any additional positional arguments are the same as the arguments to :meth:`find`. :param kwargs: any additional keyword arguments are the same as the arguments to :meth:`find`. :: code-block: python >>> collection.find_one(max_time_ms=100) Nrrn)r{rr findr])rrJrrcursorrs rYfind_onezCollection.find_onesZ8  j&EV_F63D3F3ll2& FM rXc t|g|i|S)a@(Query the database. The `filter` argument is a query document that all results must match. For example: >>> db.test.find({"hello": "world"}) only matches documents that have a key "hello" with value "world". Matches can have other keys *in addition* to "hello". The `projection` argument is used to specify a subset of fields that should be included in the result documents. By limiting results to a certain subset of fields you can cut down on network traffic and decoding time. Raises :class:`TypeError` if any of the arguments are of improper type. Returns an instance of :class:`~pymongo.cursor.Cursor` corresponding to this query. The :meth:`find` method obeys the :attr:`read_preference` of this :class:`Collection`. :param filter: A query document that selects which documents to include in the result set. Can be an empty document to include all documents. :param projection: a list of field names that should be returned in the result set or a dict specifying the fields to include or exclude. If `projection` is a list "_id" will always be returned. Use a dict to exclude fields from the result (e.g. projection={'_id': False}). :param session: a :class:`~pymongo.client_session.ClientSession`. :param skip: the number of documents to omit (from the start of the result set) when returning the results :param limit: the maximum number of results to return. A limit of 0 (the default) is equivalent to setting no limit. :param no_cursor_timeout: if False (the default), any returned cursor is closed by the server after 10 minutes of inactivity. If set to True, the returned cursor will never time out on the server. Care should be taken to ensure that cursors with no_cursor_timeout turned on are properly closed. :param cursor_type: the type of cursor to return. The valid options are defined by :class:`~pymongo.cursor.CursorType`: - :attr:`~pymongo.cursor.CursorType.NON_TAILABLE` - the result of this find call will return a standard cursor over the result set. - :attr:`~pymongo.cursor.CursorType.TAILABLE` - the result of this find call will be a tailable cursor - tailable cursors are only for use with capped collections. They are not closed when the last data is retrieved but are kept open and the cursor location marks the final document position. If more data is received iteration of the cursor will continue from the last document received. For details, see the `tailable cursor documentation `_. - :attr:`~pymongo.cursor.CursorType.TAILABLE_AWAIT` - the result of this find call will be a tailable cursor with the await flag set. The server will wait for a few seconds after returning the full result set so that it can capture and return additional data added during the query. - :attr:`~pymongo.cursor.CursorType.EXHAUST` - the result of this find call will be an exhaust cursor. MongoDB will stream batched results to the client without waiting for the client to request each batch, reducing latency. See notes on compatibility below. :param sort: a list of (key, direction) pairs specifying the sort order for this query. See :meth:`~pymongo.cursor.Cursor.sort` for details. :param allow_partial_results: if True, mongos will return partial results if some shards are down instead of returning an error. :param oplog_replay: **DEPRECATED** - if True, set the oplogReplay query flag. Default: False. :param batch_size: Limits the number of documents returned in a single batch. :param collation: An instance of :class:`~pymongo.collation.Collation`. :param return_key: If True, return only the index keys in each document. :param show_record_id: If True, adds a field ``$recordId`` in each document with the storage engine's internal record identifier. :param snapshot: **DEPRECATED** - If True, prevents the cursor from returning a document more than once because of an intervening write operation. :param hint: An index, in the same format as passed to :meth:`~pymongo.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. :param max_time_ms: Specifies a time limit for a query operation. If the specified time is exceeded, the operation will be aborted and :exc:`~pymongo.errors.ExecutionTimeout` is raised. Pass this as an alternative to calling :meth:`~pymongo.cursor.Cursor.max_time_ms` on the cursor. :param max_scan: **DEPRECATED** - The maximum number of documents to scan. Pass this as an alternative to calling :meth:`~pymongo.cursor.Cursor.max_scan` on the cursor. :param min: A list of field, limit pairs specifying the inclusive lower bound for all keys of a specific index in order. Pass this as an alternative to calling :meth:`~pymongo.cursor.Cursor.min` on the cursor. ``hint`` must also be passed to ensure the query utilizes the correct index. :param max: A list of field, limit pairs specifying the exclusive upper bound for all keys of a specific index in order. Pass this as an alternative to calling :meth:`~pymongo.cursor.Cursor.max` on the cursor. ``hint`` must also be passed to ensure the query utilizes the correct index. :param comment: A string to attach to the query to help interpret and trace the operation in the server logs and in profile data. Pass this as an alternative to calling :meth:`~pymongo.cursor.Cursor.comment` on the cursor. :param allow_disk_use: if True, MongoDB may use temporary disk files to store data exceeding the system memory limit while processing a blocking sort operation. The option has no effect if MongoDB can satisfy the specified sort using an index, or if the blocking sort requires less memory than the 100 MiB limit. This option is only supported on MongoDB 4.4 and above. .. note:: There are a number of caveats to using :attr:`~pymongo.cursor.CursorType.EXHAUST` as cursor_type: - The `limit` option can not be used with an exhaust cursor. - Exhaust cursors are not supported by mongos and can not be used with a sharded cluster. - A :class:`~pymongo.cursor.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:: 4.0 Removed the ``modifiers`` option. Empty projections (eg {} or []) are passed to the server as-is, rather than the previous behavior which substituted in a projection of ``{"_id": 1}``. This means that an empty projection will now return the entire document, not just the ``"_id"`` field. .. versionchanged:: 3.11 Added the ``allow_disk_use`` option. Deprecated the ``oplog_replay`` option. Support for this option is deprecated in MongoDB 4.4. The query engine now automatically optimizes queries against the oplog without requiring this option to be set. .. versionchanged:: 3.7 Deprecated the ``snapshot`` option, which is deprecated in MongoDB 3.6 and removed in MongoDB 4.0. Deprecated the ``max_scan`` option. Support for this option is deprecated in MongoDB 4.0. Use ``max_time_ms`` instead to limit server-side execution time. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.5 Added the options ``return_key``, ``show_record_id``, ``snapshot``, ``hint``, ``max_time_ms``, ``max_scan``, ``min``, ``max``, and ``comment``. Deprecated the ``modifiers`` option. .. versionchanged:: 3.4 Added support for the ``collation`` option. .. versionchanged:: 3.0 Changed the parameter names ``spec``, ``fields``, ``timeout``, and ``partial`` to ``filter``, ``projection``, ``no_cursor_timeout``, and ``allow_partial_results`` respectively. Added the ``cursor_type``, ``oplog_replay``, and ``modifiers`` options. Removed the ``network_timeout``, ``read_preference``, ``tag_sets``, ``secondary_acceptable_latency_ms``, ``max_scan``, ``snapshot``, ``tailable``, ``await_data``, ``exhaust``, ``as_class``, and slave_okay parameters. Removed ``compile_re`` option: PyMongo now always represents BSON regular expressions as :class:`~bson.regex.Regex` objects. Use :meth:`~bson.regex.Regex.try_compile` to attempt to convert from a BSON regular expression to a Python regular expression object. Soft deprecated the ``manipulate`` option. .. seealso:: The MongoDB documentation on `find `_. )rCrs rYrqzCollection.findstd,T,V,,rXcv|jjjr tdt |g|i|S)aQuery 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 auto encryption. .. versionchanged:: 3.12 Instead of ignoring the user-specified read concern, this method now sends it to the server when connected to MongoDB 3.6+. Added session support. .. versionadded:: 3.6 z1find_raw_batches does not support auto encryption)rr _encrypterr&rDrs rYfind_raw_batcheszCollection.find_raw_batchess86 >> + +"#VW Wd4T4V44rXc v|j||||j|j||}t|dS)zInternal count command helper.)rxrwrzrrr<)rrrzra)rrrrxrrress rY _count_cmdzCollection._count_cmdsHmm  +<<** 3s8}rXc |j|||dg|j|j||}d|vry|dd}|r|dSdS)zAInternal helper to run an aggregate that returns a single result.)rrwrzrrrrN firstBatchr)rrrz)rrrxrrrrbatchs rY_aggregate_one_resultz Collection._aggregate_one_resultsj    T<<**   6 !x . uQx*d*rXc dvr td||d< dfd }j|dtjS)aGet an estimate of the number of documents in this collection using collection metadata. The :meth:`estimated_document_count` method is **not** supported in a transaction. All optional parameters should be passed as keyword arguments to this method. Valid options include: - `maxTimeMS` (int): The maximum amount of time to allow this operation to run, in milliseconds. :param comment: A user-provided comment to attach to this command. :param kwargs: See list of options above. .. versionchanged:: 4.2 This method now always uses the `count`_ command. Due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command was not included in V1 of the :ref:`versioned-api-ref`. Users of the Stable API with estimated_document_count are recommended to upgrade their server version to 5.0.9+ or set :attr:`pymongo.server_api.ServerApi.strict` to ``False`` to avoid encountering errors. .. versionadded:: 3.7 .. _count: https://mongodb.com/docs/manual/reference/command/count/ rz2estimated_document_count does not support sessionsNrcndji}|jj||||dS)Ncount)r)rrrz)r_serverrrxrrrs rY_cmdz1Collection.estimated_document_count.._cmds9 $+DJJ"7C JJv ??7D/3RV?W WrXr rrrrarr`rxOptional[_ServerMode]rra)r$_retryable_non_cursor_readr4COUNT)rrrrs` ` rYestimated_document_countz#Collection.estimated_document_counts6  $%YZ Z   'F9  X, X X X3  X   X..tTSYY.OOrXc *d|ig}d|vr"|jd|jdid|vr"|jd|jdi|||d<|jdd d d id ij|id d |vr.t|d tst j |d |d <t|jddj| dfd }j||tjS)a Count the number of documents in this collection. .. note:: For a fast count of the total documents in a collection see :meth:`estimated_document_count`. The :meth:`count_documents` method is supported in a transaction. All optional parameters should be passed as keyword arguments to this method. Valid options include: - `skip` (int): The number of matching documents to skip before returning results. - `limit` (int): The maximum number of documents to count. Must be a positive integer. If not provided, no limit is imposed. - `maxTimeMS` (int): The maximum amount of time to allow this operation to run, in milliseconds. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. - `hint` (string or list of tuples): The index to use. Specify either the index name as a string or the index specification as a list of tuples (e.g. [('a', pymongo.ASCENDING), ('b', pymongo.ASCENDING)]). The :meth:`count_documents` method obeys the :attr:`read_preference` of this :class:`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`_ | +-------------+-------------------------------------+ :param filter: A query document that selects which documents to count in the collection. Can be an empty document to count all documents. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: See list of options above. .. versionadded:: 3.7 .. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/ .. _$geoWithin: https://mongodb.com/docs/manual/reference/operator/query/geoWithin/ .. _$center: https://mongodb.com/docs/manual/reference/operator/query/center/ .. _$centerSphere: https://mongodb.com/docs/manual/reference/operator/query/centerSphere/ z$matchskipz$skipr]z$limitNrz$grouprNz$sum)rr<) aggregaterrrr8rc>j|||}|sy|dS)Nrr<)r)rrrrxrrrrs rYrz(Collection.count_documents.._cmd_s. //osIW^_F#; rXr) r'rrr{r|rr?r!rrr4r) rrJrrrrrrrs ` @@rYcount_documentszCollection.count_documentss-|v&' V  OOWfjj&89 : f  OOXvzz'':; <   'F9 1FA;#?@A JJHK V Jvf~s$C+;;F6NKF6N.vzz+t/LM  6 ,   3   ..tWciiHHrXc|jj}|j|5}|j||j |||cdddS#1swYyxYw)z;Non-cursor read helper to handle implicit session creation.N)rrr_retryable_readr)rfuncrrrrs rYrz%Collection._retryable_non_cursor_readls\&&   ) \Q))$0I0I!0LaQZ[ \ \ \s #AAc dtjd||||d<|j||fi|S)amCreate 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"] :param indexes: A list of :class:`~pymongo.operations.IndexModel` instances. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation. .. versionchanged:: 3.6 Added ``session`` parameter. Added support for arbitrary keyword arguments. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. .. versionadded:: 3.0 .. _createIndexes: https://mongodb.com/docs/manual/reference/command/createIndexes/ indexesr)rr_create_indexes)rrrrrs rYcreate_indexeszCollection.create_indexeszs?T Y0   'F9 #t##GW???rXc g|j|tj5}|jdk\}d fd }|jt |d}|j |d|vr |s td|j||tjt|j||dddS#1swYSxYw) agInternal createIndexes helper. :param indexes: A list of :class:`~pymongo.operations.IndexModel` instances. :param session: a :class:`~pymongo.client_session.ClientSession`. :param kwargs: optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments. rr^c3KD]D}t|tst|d|j}j |d|Fyw)Nz4 is not an instance of pymongo.operations.IndexModelr)r{r,r}r"r')indexr"rnamess rY gen_indexesz/Collection._create_indexes..gen_indexessY$#E%eZ8'$i'[\ %~~HLL&!12"N#sA A) createIndexesr commitQuorumzRMust be connected to MongoDB 4.4+ to use the commitQuorum option for createIndexes)rxrwryrNrzIterator[Mapping[str, Any]]) rr4CREATE_INDEXESrrr+rr$rr6rr)r) rrrrrsupports_quorumrrrs ` @rYrzCollection._create_indexess  " "7c6H6H " I T"33q8O #%)II${}:MNC JJv '(< MM . 6 6<"55g>  + : ; : s BB>>Cc i}d|vr|jd|d<|||d<t|fi|}|j|g|fi|dS)a0Creates an index on this collection. Takes either a single key or a list containing (key, direction) pairs or keys. If no direction is given, :data:`~pymongo.ASCENDING` will be assumed. The key(s) must be an instance of :class:`str` and the direction(s) must be one of (:data:`~pymongo.ASCENDING`, :data:`~pymongo.DESCENDING`, :data:`~pymongo.GEO2D`, :data:`~pymongo.GEOSPHERE`, :data:`~pymongo.HASHED`, :data:`~pymongo.TEXT`). To create a single key ascending index on the key ``'mike'`` we just use a string argument:: >>> 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"]) 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`: Used to create an expiring (TTL) collection. MongoDB will automatically delete documents from this collection after seconds. The indexed field must be a UTC datetime or the data will not expire. - `partialFilterExpression`: A document that specifies a filter for a partial index. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. - `wildcardProjection`: Allows users to include or exclude specific field paths from a `wildcard index`_ using the {"$**" : 1} key pattern. Requires MongoDB >= 4.2. - `hidden`: if ``True``, this index will be hidden from the query planner and will not be evaluated as part of query plan selection. Requires MongoDB >= 4.4. See the MongoDB documentation for a full list of supported options by server version. .. warning:: `dropDups` is not supported by MongoDB 3.0 or newer. The option is silently ignored by the server and unique index builds using the option will fail if a duplicate value is detected. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation. :param keys: a single key or a list of (key, direction) pairs specifying the index to create :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: any additional index creation options (see the above list) should be passed as keyword arguments. .. versionchanged:: 4.4 Allow passing a list containing (key, direction) pairs or keys for the ``keys`` parameter. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.11 Added the ``hidden`` option. .. versionchanged:: 3.6 Added ``session`` parameter. Added support for passing maxTimeMS in kwargs. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. Support the `collation` option. .. versionchanged:: 3.2 Added partialFilterExpression to support partial indexes. .. versionchanged:: 3.0 Renamed `key_or_list` to `keys`. Removed the `cache_for` option. :meth:`create_index` no longer caches index names. Removed support for the drop_dups and bucket_size aliases. .. seealso:: The MongoDB documentation on `indexes `_. .. _wildcard index: https://dochub.mongodb.org/core/index-wildcard/ maxTimeMSrr)rr,r)rkeysrrr cmd_optionsrs rYrzCollection.create_indexse\ & '-zz+'>K $  %,K "4*6*$$$eWgEEqIIrXc :|||d<|jdd|i|y)aDrops all indexes on this collection. Can be used on non-existent collections or collections with no indexes. Raises OperationFailure on an error. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation. .. versionchanged:: 3.6 Added ``session`` parameter. Added support for arbitrary keyword arguments. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. Nrr)* _drop_index)rrrrs rY drop_indexeszCollection.drop_indexesL s,:   'F9 8g88rXc .|j|||fi|y)a Drops the specified index on this collection. Can be used on non-existent collections or collections with no indexes. Raises OperationFailure on an error (e.g. trying to drop an index that does not exist). `index_or_name` can be either an index name (as returned by `create_index`), or an index specifier (as passed to `create_index`). An index specifier should be a list of (key, direction) pairs. Raises TypeError if index is not an instance of (str, unicode, list). .. warning:: if a custom name was used on index creation (by passing the `name` parameter to :meth:`create_index`) the index **must** be dropped by name. :param index_or_name: index (or name of index) to drop :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: optional arguments to the createIndexes command (like maxTimeMS) can be passed as keyword arguments. .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation. .. versionchanged:: 3.6 Added ``session`` parameter. Added support for arbitrary keyword arguments. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. Nr)r index_or_namerrrs rY drop_indexzCollection.drop_indexm s^ CFCrXc |}t|trtj|}t|tst dt ||j|d}|j||||d<|j|tj5}|j||tjddg|j||dddy#1swYyxYw)Nz6index_or_name must be an instance of str or list, not ) dropIndexesrrr ns not foundr|)rxrryr)r{r+r_gen_index_namer|r}r~rrrr4 DROP_INDEXESrr6rr)rrrrrrrrs rYrzCollection._drop_index s mT *!11-@D$$TUYZ^U_T`ab b"jj48 6  $C N  " "7c6F6F " G 4 MM . 6 6"0"!5"55g>     s 7CC c&|j||S)aGet 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_')]) :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :return: An instance of :class:`~pymongo.command_cursor.CommandCursor`. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionadded:: 3.0 ) _list_indexes)rrrs rY list_indexeszCollection.list_indexes s6!!'733rXctttttt t fjtj|xr|jxstj}|du dfd }jjj|d5}jjj|||tj cdddS#1swYyxYw)N)rwrxc 4 jid}  |d< j||||d}t ||j | |j d}|j||S#t$r}|jdk7rdgd}Yd}~`d}~wwxYw) N) listIndexesrrr)rrrr|r)idr})rexplicit_sessionr)rrr'coderAaddressr_maybe_pin_connection) rrrrxrrrexc cmd_cursorrwcollrrrs rYrz&Collection._list_indexes.._cmd s #'**;C"!(I 5MM$_mU\M]' !1 * J  , ,T 2 $ 588r> !4  5sA// B8BBFr) rrrrarr`rxr7r'CommandCursor[MutableMapping[str, Any]])rrrrcr r|rrr6r_txn_read_preferencerrrrr4 LIST_INDEXES) rrr read_prefrrrwrrs ` ` @@@rYrzCollection._list_indexes s '33&7  ~c3h/ 0   M>KaKa  b ?!=!=!?ZNDZDZ "$. ,   )   5   >^^ " " / / ? 1>>((88ic.>.>9   s <7C==Dc|j||}i}|D]@}t|dj|d<t|}|||j d<B|S)ajGet 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) 'x_1' >>> db.test.index_information() {'_id_': {'key': [('_id', 1)]}, 'x_1': {'unique': True, 'key': [('x', 1)]}} :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 4.1 Added ``comment`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. )rrrr)rr+itemsrr)rrrrrinfors rYindex_informationzCollection.index_information slD##GW#E ,Ee 2 2 45E%LKE&+D6" # , rXc n|diig}ndd|iig}|jttjtt }t |t|||du|dddii}|jjj|j|j|||j tj S) aReturn a cursor over search indexes for the current collection. :param name: If given, the name of the index to search for. Only indexes with matching index names will be returned. If not given, all search indexes for the current collection will be returned. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :return: A :class:`~pymongo.command_cursor.CommandCursor` over the result set. .. note:: requires a MongoDB server version 7.0+ Atlas cluster. .. versionadded:: 4.5 Nz$listSearchIndexesr)rwrxryrzrrr}rN)rrr retryabler)rrr6rrIr5r=rArrr get_cursorget_read_preference_performs_writer4LIST_SEARCH_INDEX)rrrrrrrrs rYlist_search_indexeszCollection.list_search_indexes3 s0 <$8"#=">H-~>?H  /*22/- !  ,    $D0!L!#45 ~~$$44 NN  # #G , ---++ 5  rXc jt|ts tdi|}|j|g||fi|dS)aCreate a single search index for the current collection. :param model: The model for the new search index. It can be given as a :class:`~pymongo.operations.SearchIndexModel` instance or a dictionary with a model "definition" and optional "name". :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: optional arguments to the createSearchIndexes command (like maxTimeMS) can be passed as keyword arguments. :return: The name of the new search index. .. note:: requires a MongoDB server version 7.0+ Atlas cluster. .. versionadded:: 4.5 rrW)r{r/_create_search_indexes)rmodelrrrs rYcreate_search_indexzCollection.create_search_indexh s@4%!12$-u-E+++UGWgPPRSTTrXc ,|j|||fi|S)awCreate multiple search indexes for the current collection. :param models: A list of :class:`~pymongo.operations.SearchIndexModel` instances. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: optional arguments to the createSearchIndexes command (like maxTimeMS) can be passed as keyword arguments. :return: A list of the newly created search index names. .. note:: requires a MongoDB server version 7.0+ Atlas cluster. .. versionadded:: 4.5 )r)rmodelsrrrs rYcreate_search_indexesz Collection.create_search_indexes s ,+t**67GNvNNrXc l|||d<dfd }|jt|d}|j||j|tj 5}|j ||tjt}|dD cgc]} | d c} cdddScc} w#1swYyxYw) Nrc3tKD].}t|tst|d|j0yw)Nz: is not an instance of pymongo.operations.SearchIndexModel)r{r/r}r")rrs rYrz6Collection._create_search_indexes..gen_indexes sE %!%)9:# )#]^nn$  %s58)createSearchIndexesrr)rxrwindexesCreatedrr) rr+rrr4CREATE_SEARCH_INDEXESrr6rr)) rrrrrrrrresprs ` rYrz!Collection._create_search_indexes s   'F9  %'+iiD>Bcj|jjj|jj|j|j |j |j}|j|d|ji|}d}|D]}|}n|siS|jdi}|Jd|vr|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. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. .. versionchanged:: 3.6 Added ``session`` parameter. r)rrJrNrr) rrrWrrwrxryrzlist_collectionsrr)rrrrYrrrrrs rYrzCollection.options s(nn##00 NN              %%gvtzz>R\c%d CF  I**Y+""" w !rXc |||d<|||||||dddii} |jjj| j| j ||| j t jS)Nrrrr}rN)rr)rrrrrrr4 AGGREGATE) raggregation_commandr cursor_classrrrrrrs rY _aggregatezCollection._aggregate. s   'F9 !      !L!#45 ~~$$44 NN  # #G , ---mm 5  rXc |jjj|d5}|jt|t f||du||d|cdddS#1swYyxYw)aPerform an aggregation using the aggregation framework on this collection. The :meth:`aggregate` method obeys the :attr:`read_preference` of this :class:`Collection`, except when ``$out`` or ``$merge`` are used on MongoDB <5.0, in which case :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY` is used. .. note:: This method does not support the 'explain' option. Please use `PyMongoExplain `_ 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. :param pipeline: a list of aggregation pipeline stages :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: A dict of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. ``"$$var"``). This option is only supported on MongoDB >= 5.0. :param comment: A user-provided comment to attach to this command. :param kwargs: extra `aggregate command`_ parameters. All optional `aggregate command`_ parameters should be passed as keyword arguments to this method. Valid options include, but are not limited to: - `allowDiskUse` (bool): Enables writing to temporary files. When set to True, aggregation stages can write data to the _tmp subdirectory of the --dbpath directory. The default is False. - `maxTimeMS` (int): The maximum amount of time to allow the operation to run in milliseconds. - `batchSize` (int): The maximum number of documents to return per batch. Ignored if the connected mongod or mongos does not support returning aggregate results using a cursor. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. - `bypassDocumentValidation` (bool): If ``True``, allows the write to opt-out of document level validation. :return: A :class:`~pymongo.command_cursor.CommandCursor` over the result set. .. versionchanged:: 4.1 Added ``comment`` parameter. Added ``let`` parameter. Support $merge and $out executing on secondaries according to the collection's :attr:`read_preference`. .. versionchanged:: 4.0 Removed the ``useCursor`` option. .. versionchanged:: 3.9 Apply this collection's read concern to pipelines containing the `$out` stage when connected to MongoDB >= 4.2. Added support for the ``$merge`` pipeline stage. Aggregations that write always use read preference :attr:`~pymongo.read_preferences.ReadPreference.PRIMARY`. .. versionchanged:: 3.6 Added the `session` parameter. Added the `maxAwaitTimeMS` option. Deprecated the `useCursor` option. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. Support the `collation` option. .. versionchanged:: 3.0 The :meth:`aggregate` method always returns a CommandCursor. The pipeline argument must be a list. .. seealso:: :doc:`/examples/aggregation` .. _aggregate command: https://mongodb.com/docs/manual/reference/command/aggregate FcloseN)rrrr)rrrrr=rA)rrrrrrrs rYrzCollection.aggregateN srh^^ " " / /u / E "4??- !(!4     s $AAc N|jjjr td|||d<|jjj |d5}t t t|jt|tf||dud|cdddS#1swYyxYw)aDPerform 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 auto encryption. .. versionchanged:: 3.12 Added session support. .. versionadded:: 3.6 z6aggregate_raw_batches does not support auto encryptionNrFr)rr) rrrvr&rrrDrFrr>rB)rrrrrrs rYaggregate_raw_batchesz Collection.aggregate_raw_batches s> >> + +"#[\ \   'F9  ^^ " " / /u / E }-4)%,D%8       s 7BB$c t|tstdt||rd|vr t d|ddk(s|ddk(r t dd|vr|j d s t d |j jd|}|j|d }|j||||d <|j||}|j|tj5}|j jj|5}|j!d||d||j jcd d d cd d d S#1swYnxYw d d d y #1swYy xYw)a\Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`str`. Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :param new_name: new name for this collection :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param kwargs: additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. ``dropTarget=True``) .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. z)new_name must be an instance of str, not rirjrrmrnz/collection names must not start or end with '.'rkrlz%collection names must not contain '$')renameCollectiontoNrradminT)ryrrr)r{r|r}r~r%rrrrrrrr4RENAMErrr) rnew_namerrrrryrrs rYrenamezCollection.rename stH(C(GXGWXY Y48+@A A A;# "!4OP P (?8#6#6}#EEF Fnn))*!H:6#'??(C 6  $C N33CA  " "7cjj " A T&&33G< ||"/.2>>00 $          s$)&E#+E : E# E E##E,c  t|tstdt|j|d|d|vr t d||d<t |jdd j|||d<|*t|tstj|}|d< d  fd }j||tj 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:`str`. All optional distinct parameters should be passed as keyword arguments to this method. Valid options include: - `maxTimeMS` (int): The maximum amount of time to allow the count command to run, in milliseconds. - `collation` (optional): An instance of :class:`~pymongo.collation.Collation`. The :meth:`distinct` method obeys the :attr:`read_preference` of this :class:`Collection`. :param key: name of the field for which we want to get the distinct values :param filter: A query document that specifies the documents from which to retrieve the distinct values. :param session: a :class:`~pymongo.client_session.ClientSession`. :param comment: A user-provided comment to attach to this command. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). :param kwargs: See list of options above. .. versionchanged:: 4.12 Added ``hint`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Support the `collation` option. z$key must be an instance of str, not )distinctrNqueryz can't pass both filter and queryrrr8c Rj||j|ddidS)NvaluesrN)rxrzrrr)rrz)rrrrxrrrs rYrz!Collection.distinct.._cmd` sD $3!%!2!2'#!)1   rXr) rrrrarr`rxrrr+)r{r|r}r~rr$r!rrrr?rr4DISTINCT) rrrJrrr8rrrrs ` @@rYrzCollection.distinct sd#s#B49+NO O::c2  & ()KLL$F7O.vzz+t/LM  6  $C N  dC(%55d;CK ,   3     $..tW .UUrXc   tjd|t|tst dt |t | jdd j||d | tjd| | d< j| |tj|d d<|tj| d <|td || d <%ttstjj | d  fd } j j"j%j&| |t(j* S)zInternal findAndModify helper.rJzKreturn_document must be ReturnDocument.BEFORE or ReturnDocument.AFTER, not rN) findAndModifyrnewr projectionfieldsr:r0c ^ j}|s tdtd<;|jdkr td|s|jdkr tdd< j |t j ||t}t||jd S) Nr5r6r7zJMust be connected to MongoDB 4.2+ to use hint on find and modify commands.r^zYMust be connected to MongoDB 4.4+ to use hint on unacknowledged find and modify commands.r8)rxryrrrrrM) rr$r+rrr6r_FIND_AND_MODIFY_DOC_FIELDSr(r) rrrroutrBrrr8rrys rY_find_and_modify_helperz._find_and_modify_helper s)55L(#,P'+=&9N#((1,,d&$*?*?!*C,s#F -- . 6 6+# /7 C *# .777# #rXr)rrrr`rrrr)rrr{rrr~r!rrrr_fields_list_to_dictr?rKr|rrrrrr4FIND_AND_MODIFY)rrJrr:r0return_documentrBr8rrrrrrrys` `` @@@rY_find_and_modifyzCollection._find_and_modifyt sw ""8V4/40]^bcr^s]tu /vzz+t/LM $ VOT ?  & &uc 2CJ 6  !*?? LYCM  (88>CK   Xv ."CM  dC(%55d;33CA  $, $4> $QU $  $ $D~~$$55  & & # )) 6  rXc Ld|d<|||d<|j|||f|||d|S)af 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}) {'x': 1, '_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) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} >>> db.test.find_one_and_delete( ... {'x': 1}, sort=[('_id', pymongo.DESCENDING)]) {'x': 1, '_id': 2} The *projection* option can be used to limit the fields returned. >>> db.test.find_one_and_delete({'x': 1}, projection={'_id': False}) {'x': 1} :param filter: A query that matches the document to delete. :param projection: a list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If `projection` is a list "_id" will always be returned. Use a mapping to exclude fields from the result (e.g. projection={'_id': False}). :param sort: a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is deleted. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.4 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :param kwargs: additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions). .. versionchanged:: 4.1 Added ``let`` parameter. .. versionchanged:: 3.11 Added ``hint`` parameter. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.2 Respects write concern. .. warning:: Starting in PyMongo 3.2, this command uses the :class:`~pymongo.write_concern.WriteConcern` of this :class:`~pymongo.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 Tremoverrr8r)r ) rrJrr:r8rrrrs rYfind_one_and_deletezCollection.find_one_and_delete sOd x   'F9 $t$$ J *-D' MS  rXc  ztj||| d<| | | 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) ... {'x': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} >>> db.test.find_one_and_replace({'x': 1}, {'y': 1}) {'x': 1, '_id': 0} >>> for doc in db.test.find({}): ... print(doc) ... {'y': 1, '_id': 0} {'x': 1, '_id': 1} {'x': 1, '_id': 2} :param filter: A query that matches the document to replace. :param replacement: The replacement document. :param projection: A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If `projection` is a list "_id" will always be returned. Use a mapping to exclude fields from the result (e.g. projection={'_id': False}). :param sort: a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is replaced. :param upsert: When ``True``, inserts a new document if no document matches the query. Defaults to ``False``. :param return_document: If :attr:`ReturnDocument.BEFORE` (the default), returns the original document before it was replaced, or ``None`` if no document matches. If :attr:`ReturnDocument.AFTER`, returns the replaced or inserted document. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.4 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :param kwargs: additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions). .. versionchanged:: 4.1 Added ``let`` parameter. .. versionchanged:: 3.11 Added the ``hint`` option. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the ``collation`` option. .. versionchanged:: 3.2 Respects write concern. .. warning:: Starting in PyMongo 3.2, this command uses the :class:`~pymongo.write_concern.WriteConcern` of this :class:`~pymongo.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 rrr)rrKr ) rrJrMrr:r0r r8rrrrs rYfind_one_and_replacezCollection.find_one_and_replace skv &&{3&x   'F9 $t$$           rXc  tj|tjd||| d<| | | d<|j||||||f|| | d| S)aFinds 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}}) {'_id': 665, 'done': False, '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) {'_id': 'userid', '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) {'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) {'seq': 1} If multiple documents match *filter*, a *sort* can be applied. >>> for doc in db.test.find({'done': True}): ... print(doc) ... {'_id': 665, 'done': True, 'result': {'count': 26}} {'_id': 701, 'done': True, 'result': {'count': 17}} >>> db.test.find_one_and_update( ... {'done': True}, ... {'$set': {'final': True}}, ... sort=[('_id', pymongo.DESCENDING)]) {'_id': 701, 'done': True, 'result': {'count': 17}} :param filter: A query that matches the document to update. :param update: The update operations to apply. :param projection: A list of field names that should be returned in the result document or a mapping specifying the fields to include or exclude. If `projection` is a list "_id" will always be returned. Use a dict to exclude fields from the result (e.g. projection={'_id': False}). :param sort: a list of (key, direction) pairs specifying the sort order for the query. If multiple documents match the query, they are sorted and the first is updated. :param upsert: When ``True``, inserts a new document if no document matches the query. Defaults to ``False``. :param return_document: If :attr:`ReturnDocument.BEFORE` (the default), returns the original document before it was updated. If :attr:`ReturnDocument.AFTER`, returns the updated or inserted document. :param array_filters: A list of filters specifying which array elements an update should apply. :param hint: An index to use to support the query predicate specified either by its string name, or in the same format as passed to :meth:`~pymongo.collection.Collection.create_index` (e.g. ``[('field', ASCENDING)]``). This option is only supported on MongoDB 4.4 and above. :param session: a :class:`~pymongo.client_session.ClientSession`. :param let: Map of parameter names and values. Values must be constant or closed expressions that do not reference document fields. Parameters can then be accessed as variables in an aggregate expression context (e.g. "$$var"). :param comment: A user-provided comment to attach to this command. :param kwargs: additional command arguments can be passed as keyword arguments (for example maxTimeMS can be used with recent server versions). .. versionchanged:: 3.11 Added the ``hint`` option. .. versionchanged:: 3.9 Added the ability to accept a pipeline as the ``update``. .. versionchanged:: 3.6 Added the ``array_filters`` and ``session`` options. .. versionchanged:: 3.4 Added the ``collation`` option. .. versionchanged:: 3.2 Respects write concern. .. warning:: Starting in PyMongo 3.2, this command uses the :class:`~pymongo.write_concern.WriteConcern` of this :class:`~pymongo.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 rBrr)r8rr)rrQrRr ) rrJrrr:r0r rBr8rrrrs rYfind_one_and_updatezCollection.find_one_and_update s~F %%f-$$_mD!x   'F9 $t$$            rX)FNNNNN)rDatabase[_DocumentType]rr|rOptional[bool]rwz(Optional[CodecOptions[_DocumentTypeArg]]rxrryOptional[WriteConcern]rzOptional[ReadConcern]rrrrrr)rr|rCollection[_DocumentType])rr|)rrrr)rra)rr)rr)N...) rwrrxrryrrzrrr)...) rwz#bson.CodecOptions[_DocumentTypeArg]rxrryrrzrrzCollection[_DocumentTypeArg])NNNN) rwz-Optional[bson.CodecOptions[_DocumentTypeArg]]rxrryrrzrrz8Collection[_DocumentType] | Collection[_DocumentTypeArg])rrfrrrrJ)rrrrrr) NNNNNNNNNNNN)rzOptional[_Pipeline]r Optional[str]rrGr Optional[int]rrrOptional[_CollationIn]rzOptional[Timestamp]rrrrGr Optional[Any]rrrrrz%CollectionChangeStream[_DocumentType])rrrr|rzContextManager[Connection]) NNTNNNNNFN)rr`rMutableMapping[str, Any]rxrrwzOptional[CodecOptions]rrrz#Optional[Sequence[Union[str, int]]]rzrryrrrrrrrrrrrf)NF)rr|rrrrrrrrGrrrr)rrrrrr)TNNNN)rz!Sequence[_WriteOp[_DocumentType]]r rr rrrrrrOptional[Mapping]rr8r)rrfr rryrJrrrrrrrrrr)NNN) r"z%Union[_DocumentType, RawBSONDocument]r rrrrrrr;)TNNN) rz/Iterable[Union[_DocumentType, RawBSONDocument]]r rr rrrrrrr:)FFNNTNNNNNFNNN)$rr`rArfr"#Union[Mapping[str, Any], _Pipeline]r0rr3rryrrrr rrrrrrB%Optional[Sequence[Mapping[str, Any]]]r8Optional[_IndexKeyHint]rrrrrrGr:rGrrrrG) FFNNTNNNNNNNN)"rArfr"rrr|r0rr3rryrrrr rrrrrrBr r8r!rrrrGr:rGrrrrG)FNNNNNNN)rJrfrMrfr0rr rrrr8r!rrrrGr:rGrrrr<) FNNNNNNNN)rJrfrrr0rr rrrrBr r8r!rrrrGr:rGrrrr<)rJrfrrr0rrBr r rrrr8r!rrrrGrrrr<)rrrrrrGrr) NNTNNNFNN)rr`rArfr3rryrrrr rrrr8r!rrrrrrGrrrrf)NNTNNNNN)rArfr3rryrrrr rrrr8r!rrrrGrrrrf)NNNNN)rJrfrrr8r!rrrrGrrrr9)rJrrrrrrzOptional[_DocumentType])rrrrrzCursor[_DocumentType])rrrrrRawBatchCursor[_DocumentType]) rrrr`rxrrdict[str, Any]rzOptional[Collation]rra) rr`rxrrr#rrrrrrG)rrrrrra)NN) rJrfrrrrrrrra)rzQCallable[[Optional[ClientSession], Server, Connection, Optional[_ServerMode]], T]rrrr|rrL) rSequence[IndexModel]rrrrrrr list[str])rr$rrrrrr%) rr2rrrrrrrr|)rrrrrrrr) rr2rrrrrrrr)rrrrrr)rrrrrr) rrrrrrrrrz CommandCursor[Mapping[str, Any]]) rz*Union[Mapping[str, Any], SearchIndexModel]rrrrrrrr|) rzlist[SearchIndexModel]rrrrrrrr%) rr|rrrrrrrr) rr|rrfrrrrrrrr)rzType[_AggregationCommand]rrHrzType[CommandCursor]rrrrrrGrrrrrCommandCursor[_DocumentType]) rrHrrrrGrrrrrr&) rrHrrrrrrrr") rr|rrrrrrrr)rr|rJrGrrrrr8r!rrrr+)rJrfr1Optional[Union[Mapping[str, Any], Iterable[str]]]r:Optional[_IndexList]r0rr rrBr r8r!rrrrrrrr)NNNNNN)rJrfrr'r:r(r8r!rrrrGrrrrrrF)rJrfrMrfrr'r:r(r0rr rr8r!rrrrGrrrrrrF)rJrfrrrr'r:r(r0rr rrBr r8r!rrrrGrrrrrrF)PrQrRrSrTrvrrrrrrrpropertyrrrrrr__iter__rnextrrrrrrrapplyrr r$r-rDrHrNrSrUrZrcrhrmrorsrqrwrzrrrrrrrrrrrrrrrrrrrrrrrrrrPrUr rrr __classcell__)rs@rYrcrcs "'BF1504.2+/@d)@d@d @d @ @d / @d.@d,@d)@d@d @dD &  L !2  #1403.1   / .  ,  #   2503.1  : / .  ,  &   HL1504.2 + D+ /+ . + , + B + Z4$4/F4 4H? D  ")-'+48+/$(,07;+/37!%59/3K%K%K2 K ) K " K*K"5K)K1KK&3K-K /KZJ.J;>J #J2604@D.204,0+/ %%)88*8/ 8 . 8  8>8,8.8*8)88#8 8@9=#!!*!* ! ) ! 6 !! !FI)I)I  I2 [[59+/!%!%_*3_*_*%3 _* ) _*  _*_* _*_*R"&) ))$ )  ) ' )))) )\6:+/!% > 7> %3> ) >  >  > @ [[59+/!% HJBHJHJ%3 HJ ) HJ  HJ HJHJ^04#)-,0?C(,+/ %+/,0!%%^^$^6 ^  ^  ^.^^^'^*^=^&^)^^ )!^"*#^$%^& %'^J04#)-,0?C(,+/+/,0!%#1 #1 61  1  1  1 .1 1 1 '1 *1 =1 &1 )1 )1 *!1 "#1 $ %%1 n59,0(,+/+/,0!%k !k 'k  k %3 k * k &k )k )k *k k  k b59,0?C(,+/+/,0!%v !v 4v  v %3 v * v =v &v )v )v *v v  v x?C59,0(,+/+/!%c !c 4c  c = c %3 c *c &c )c )c c  c N,0!%8< ) () ) 6 )  ) `15#,0(,+/ %+/!%66$6 6 . 6  66*6&6)66)66 6x15#,0(,+/+/!%& #& & . &  &  & *& && )& )& &  & V-1(,+/+/!%? !? *? & ? ) ? ) ? ?  ? H-1(,+/+/!%? !? *? & ? ) ? ) ? ?  ? D'+!#!36!BE! !Fz-x5>(/    '  (++/+ + * + ) + %+2*P^,0!% WI!WI)WI WI  WI WIr \  \ ) \ \  \",0!% -@%-@)-@ -@  -@  -@^ [[*+*6M*Y\* **^,0!% tJtJ)tJ tJ  tJ tJp,0!%9(99 9  9B [[,0!% .D$.D).D .D  .D  .D.D` [[,0!% $)     <,0!%4(44 1 4>,0!%/(// 1 /f,0!%(((( " (X#+/!% 3 3 )3  3  3 * 3 p,0 U9U)U U  U UB,0!% O&O)O O  O  O6,0!% G&G)G G  G  GB,0!%  )      L,0!% ""&") "  "  " "L,0!%*(** " *X [[,0!% 6  *  )    )    &  D,0+/!% ^^)^) ^  ^  ^ &^F,0!% ..). .  . ' .` [[,0!% ==)= =  = " ==D/3+/!%(, TV TV,TV) TV  TV & TVTV TVv"& . 5 5?C(,+/!%M !M FM # M  M  M =M &M )M M M  M dIM%)(,+/+/!%W !W FW # W & W ) W )W W W  W zIM%) . 5 5(,+/+/!%i !i 'i F i # i  i i &i )i )i i i  i ^IM%) . 5 5?C(,+/+/!%S !S 4S F S # S  S S =S &S )S )S S S  S rXrc)wrT __future__rr collectionsrtypingrrrrr r r r r rrrrrrrrbson.codec_optionsrr bson.objectidr bson.raw_bsonrbson.sonrbson.timestamprpymongorrrrr pymongo.collationr!pymongo.commonr"r#pymongo.errorsr$r%r&r'pymongo.helpers_sharedr(pymongo.messager)pymongo.operationsr*r+r,r-r.r/r0r1r2r3r4pymongo.read_concernr5pymongo.read_preferencesr6r7pymongo.resultsr8r9r:r;r<pymongo.synchronous.aggregationr=r>pymongo.synchronous.bulkr?!pymongo.synchronous.change_streamr@"pymongo.synchronous.command_cursorrArBpymongo.synchronous.cursorrCrDpymongo.typingsrErFrGrHpymongo.write_concernrIrJrKrrLr_WriteOprPbsonrZr[r\"pymongo.synchronous.client_sessionr]rr_pymongo.synchronous.poolr`pymongo.synchronous.serverra BaseObjectrcrWrXrYrMs0,"(C")$EE8: A:    6@+DUTWW  CL&l  m }    < <+0C@531Q6 ""GM$:Q6 rX