f$dZddlmZddlmZddlmZmZmZm Z m Z m Z m Z m Z mZmZmZmZmZmZmZmZddlmZmZddlmZddlmZddlmZdd lm Z dd l!m"Z"m#Z#m$Z$m%Z%m&Z&dd l'm(Z(m)Z)dd l*m+Z+dd l,m-Z-ddl.m/Z/ddl0m1Z1m2Z2ddl3m4Z4m5Z5ddl6m7Z7m8Z8ddl9m:Z:m;Z;mm?Z?ddl@mAZAddlBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMddlNmOZOmPZPddlQmRZRmSZSddlTmUZUmVZVmWZWmXZXmYZYddlZm[Z[m\Z\m]Z]m^Z^ddl_m`Z`maZambZbedZcddiZdeeFe\eDeCeGe\eJeIfZeGddZfer$dd l'mgZgdd!lhmiZidd"l.mjZjdd#lkmlZldd$lmmnZndd%lompZpGd&d'e$je e\Zry())z%Collection level utilities for Mongo.) annotations)abc) TYPE_CHECKINGAnyCallableContextManagerGenericIterableIteratorMappingMutableMappingNoReturnOptionalSequenceTypeTypeVarUnioncast)DEFAULT_CODEC_OPTIONS CodecOptions)ObjectId)RawBSONDocument)SON) Timestamp) ASCENDING_csotcommonhelpersmessage)_CollectionAggregationCommand _CollectionRawAggregationCommand)_BulkCollectionChangeStream)validate_collation_or_none) CommandCursorRawBatchCommandCursor)_ecoc_coll_name_esc_coll_name)CursorRawBatchCursor)ConfigurationError InvalidNameInvalidOperationOperationFailure)_check_write_command_response)_UNICODE_REPLACE_CODEC_OPTIONS) DeleteMany DeleteOne IndexModel InsertOne ReplaceOneSearchIndexModel UpdateMany UpdateOne _IndexKeyHint _IndexList_Op)DEFAULT_READ_CONCERN ReadConcern)ReadPreference _ServerMode)BulkWriteResult DeleteResultInsertManyResultInsertOneResult UpdateResult) _CollationIn _DocumentType_DocumentTypeArg _Pipeline)DEFAULT_WRITE_CONCERN WriteConcernvalidate_booleanTvalueceZdZdZdZ 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__BEFOREAFTER[/var/lib/jenkins/workspace/mettalog/venv/lib/python3.12/site-packages/pymongo/collection.pyrQrQfs F E;rYrQ)_AggregationCommand) ClientSession) Collation)Database) Connection)Serverc  eZdZdZ dC dDfd Z dEdZ dF dGdZ dH dIdZdJdZdJd Z dKd Z dLd Z dLd Z dMd Z dNdZedKdZedKdZedOdZ dP dQdZej* dR dSdZ dT dUdZ dV dWdZej* dX dYdZ dZ d[dZ d\ d]dZ d^ d_dZ d` dadZ db dcdZ dd dedZ df dgdZ dh didZ! dj dkdZ" dj dkd Z# dT dld!Z$dmd"Z%dnd#Z& dod$Z' dpd%Z(dTdqd&Z) dr dsd'Z* dtd(Z+ dr dud)Z,ej* dvd*Z- dr dwd+Z. dr dxd,Z/ej* dr dyd-Z0 dr dzd.Z1 dr d{d/Z2 dd d|d0Z3 dr d}d1Z4 dr d~d2Z5 dr dd3Z6 dr dd4Z7 dr d{d5Z8ej* dr dd6Z9 dd dd7Z: dr dd8Z; d dd9Z dd<Z?de@jddddf dd=ZB d dd>ZCddde@jddddf dd?ZDddde@jdddddf dd@ZEdZFdNdAZGeGZHddBZIxZJS) CollectionzA Mongo collection.FNc  Ft ||xs |j|xs |j|xs |j|xs |j t |ts td|rd|vr tdd|vr|jdstd|z|ddk(s|d dk(rtd |zd |vr td t| jd d} ||_ ||_|jjd|j|_|jj#dt$|_|j(j*j,|_| jdd} |s| s| r| rt1j2d| dddiddi} |j5t7| || d|d|j5t9| || d||j5|| | || |j;dt<fg|y|j5|| | |yy)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 `_. zname must be an instance of str.. collection names cannot be empty$) oplog.$mainz$cmdz)collection names must not contain '$': %rr.z3collection names must not start or end with '.': %rz4collection names must not contain the null character collationNreplace)unicode_decode_error_handlerdocument_classencryptedFieldsencrypted_fieldsclusteredIndex_idrOT)keyunique) qev2_required)rp__safeContent__)super__init__ codec_optionsread_preference write_concern read_concern isinstancestr TypeErrorr- startswithr%pop_Collection__database_Collection__namename_Collection__full_name_replacedict)_Collection__write_response_codec_optionsclientoptionstimeout_timeoutrvalidate_is_mapping_Collection__creater)r( create_indexr)selfdatabasercreateryrzr{r|sessionkwargsrkrpopts __class__s rZrxzCollection.__init__s"n   3X33  7x77  3X33  1H11  $$=> >tt|@A A $;0G HIDPQ Q 7c>T"X_SVZZ[ [ T>TU U.vzz+t/LM 3; "oo2231T[[MB.2.@.@.I.I)24/J/ +!//77 !::&7> Vy**+=?OP(5!**MN "#3T:D$_c o.>EtTSZ[ dFIwQa b!!$5y#A"BGL dFIw? )rYcN|jjj||SN)rr_conn_for_writes)rr operations rZrzCollection._conn_for_writess!%%66w JJrYc 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)r|r{parse_write_concern_errorrkrrretryable_write user_fieldsN)rr _tmp_sessioncommandr_read_preference_forry)rconnrrzrycheckallowable_errorsr|r{rkrrrss rZ_commandzCollection._commandsP__ # # 0 0 9 Q<<$$E4#<#= 21 (MongoDB >=7.0))rzr{rkrN) floatupdaterr<CREATEmax_wire_versionr,rr?PRIMARY_write_concern_for) rrrrkrrprucmdrs rZ__createzCollection.__create>s (. %5C! "  "'"8 JJw   " "7cjj " A T!6!6!;(**.*?*?)@@np MM . 6 6"55g>#     s AB==Cc |jdr&|jd|}td|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 _rhzCollection has no attribute z. To access the z collection, use database['z'].)rrAttributeError __getitem__)rr full_names rZ __getattr__zCollection.__getattr__as` ??3 ;;-q/I .th6Fyk-i[= %%rYc t|j|jd|d|j|j|j |j S)NrhFrbrrryrzr{r|)rrs rZrzCollection.__getitem__psO OO{{m1TF #             rYc<d|jd|jdS)Nz Collection(z, ))rrrs rZ__repr__zCollection.__repr__{s T__/r$++BBrYct|tr4|j|jk(xr|j|j k(St Sr)r}rbrrrrNotImplementedrothers rZ__eq__zCollection.__eq__~s7 eZ (??enn4R 9R RrYc||k( SrrXrs rZ__ne__zCollection.__ne__s5=  rYcDt|j|jfSr)hashrrrs rZ__hash__zCollection.__hash__sT__dkk233rYctd)Nz{Collection objects do not implement truth value testing or bool(). Please compare with None instead: collection is not None)NotImplementedErrorrs rZ__bool__zCollection.__bool__s! 8  rYc|jS)zzThe full name of this :class:`Collection`. The full name is of the form `database_name.collection_name`. )rrs rZrzCollection.full_names rYc|jS)z%The name of this :class:`Collection`.)rrs rZrzCollection.names{{rYc|jS)zdThe :class:`~pymongo.database.Database` that this :class:`Collection` is a part of. )rrs rZrzCollection.databases rYc 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. Fr)rryrzr{r|s rZ with_optionszCollection.with_optionss[F OO KK   /T//  3t33  /T//  -D--  rYcPtjd|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)commentletz is not a valid requestNTF) r validate_listr" _add_to_bulkrrrexecuter<INSERTrA) rrorderedbypass_document_validationrrrblkrequestr{bulk_api_results rZ bulk_writezCollection.bulk_writesf Z2D'#=wTWXG Q$$S) //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 rdd<|jjjj|jj|}t |y)NTbypassDocumentValidationr{ryrrr)rrrrrr0)rrrresultbypass_doc_valrrr{s rZ_insert_commandz/Collection._insert_one.._insert_commandDs_6:23\\$$+"AA-- /"F *& 1rYrrr)rOptional[ClientSession]rr_rboolreturnNone) r{ acknowledgedrrr_retryable_writer<rr}rget) rdocrr{op_idrrrrrrs ` ` ` @rZ _insert_onezCollection._insert_one3s&;);); $11 !YY7#O  !(GI  2, 24> 2QU 2  2 2$ // /7cjj 0 #/775> !rYc 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 documentrrTN)rr{rrrr) rvalidate_is_document_typer}rrrrDrr)rrrrrr{s rZ insert_onezCollection.insert_one^s\ ((X>8_5(9J&jHUO//8    +9    & &  rYcr 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.rrrN)rrr}rrappendr_INSERT)rr inserted_idss rZgenz#Collection.insert_many..gens_%00XF!(O<H,*2* ''811 &sA(A+)r)rz'Iterator[tuple[int, Mapping[str, Any]]])r}rr r rrr"listopsrr<rrCr) rrrrrrrr{rrs ` @rZ insert_manyzCollection.insert_manysh9cll3)S[[1@A A')  2//8 D'#=wOsu+ M7CJJ7 m.H.HIIrYc td|t| } |xs |j}|j}||||d}| |s t d| |d<| |s t d| |d<| F|s|j dkr t d t | tstj| } | |d <|j||gd }|tjd |||d <|||d <| rd|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)qumultirN3Collation is unsupported for unacknowledged writes.rk6arrayFilters is unsupported for unacknowledged writes. arrayFilterszPMust be connected to MongoDB 4.2+ to use hint on unacknowledged update commands.hint)rrupdatesrrTrrnupsertedupdatedExistingFrrr)rLr%r{rr,rr}r~r_index_documentrrrrrrrcopyr0r)rrcriteriarrrr{rrrrk array_filtersr rrrrr update_docrrs rZ_updatezCollection._updates( 6*.y9 %;);); $11  &  ()^__*3 ;'  $()abb-: >*  D$9$9A$=(fdC(..t4!%Jv !YY7 |T ?  & &uc 2 GEN  !(GI  26G. / OO '==??))+  $&  &f- ::c?z7(,F$ %(-F$ %V#%+J%7%:5%Az" rYc  d  fd }jjjxs jjxr || |S)rcFj|   || S)N) rrr{rrrrkrr rrrr)r)rrrrrrkrrrr rrrrrrr{s rZrz-Collection._update_retryable.._updateRsK<<+-#+ /!  rY)rrrr_rrrOptional[Mapping[str, Any]])rrrr{r)rrrrrrr{rrrrkrr rrrrs``` ````````` `` rZ_update_retryablezCollection._update_retryable>sv( , 4> QU  (   ,%%66  0d00 > > Lu9      rYc &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. :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.6 Added ``session`` parameter. .. versionchanged:: 3.4 Added the `collation` option. .. versionchanged:: 3.2 Added bypass_document_validation support. .. versionadded:: 3.0 filterr)r{rrkr rrr) rrvalidate_ok_for_replacerrErr<UPDATEr) rr replacementrrrkr rrrr{s rZ replace_onezCollection.replace_oneos` ""8V4&&{3 ?  & &uc 2//8   " " +9# #   & &  rYc $tjd|tj|tjd||j |} t |j ||tj|| |||||| |  | jS)a5 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 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 the ``array_filters`` and ``session`` parameters. .. versionchanged:: 3.4 Added the ``collation`` option. .. versionchanged:: 3.2 Added ``bypass_document_validation`` support. .. versionadded:: 3.0 rr)r{rrkrr rrr rrvalidate_ok_for_updatevalidate_list_or_nonerrErr<rr) rrrrrrkrr rrrr{s rZ update_onezCollection.update_onest ""8V4%%f-$$_mD//8   " " +9#+ #   & &  rYc &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 rrT) rr{rrkrr rrrr) rrrrrrrkr rrrr{s rZ update_manyzCollection.update_manyFsZ ""8V4%%f-$$_mD//8   " " +9#+ #   & &!  rYc |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. )rrrpN) rr get_databaserryrzr{r|drop_collectionr)rrrrpdbos rZdropzCollection.dropss@oo$$11 OO              KK'L\  rYc 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.r)rlimitrrk zPMust be connected to MongoDB 4.4+ to use hint on unacknowledged delete commands.r )deleterdeletesrrr)rrr{rintr%r,rr}r~rrrrrrrrr0)rrrrr{rrrkr rrrrr delete_docrrs rZ_deletezCollection._deletesG ""8X6%;);); $11 #ce)n= .y9  ()^__*3 ;'  D$9$9A$=(fdC(..t4!%Jv !YY7 |T ?  , ,UC 8 GEN  !(GI  OO '==??))+  &f- rYc  d  f d } jjjxs jjxr | |t j S)r+c> j| || S)N) r{rrrkr rrrr)r2) rrrrkrrr rrrrrr{s rZr2z-Collection._delete_retryable.._deletes?<<+# /  rYr)rrrr_rrrMapping[str, Any])rrrr{rr<DELETE) rrrr{rrrkr rrrr2s ```````` `` rZ_delete_retryablezCollection._delete_retryablesz , 4> QU    $%%66  0d00 > > Lu9  jj 7  rYc ~|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 Fr{rkr rrrrrBr7rrrrkr rrrr{s rZ delete_onezCollection.delete_one6sXd//8   " "+# #   & &  rYc ~|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 Tr9r:r;s rZ delete_manyzCollection.delete_manywsXd//8   " "+# #   & &  rYc|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) Nrrri)r}rr findr,)rrargsrcursorrs rZfind_onezCollection.find_onesU8  j&EV_F63D3F3ll2&FM'rYc 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 `_. )r*rrArs rZr@zCollection.findstd,T,V,,rYcv|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.r+rEs rZfind_raw_batcheszCollection.find_raw_batchess86 ?? ! ! , ,"#VW Wd4T4V44rYc |j|||dg|j|j||}|jdddk(ryt |dS)zInternal count command helper.z ns missing)rzrryr|rkrerrmsgrr )rrr|rr0)rrrrzrrkress rZ _count_cmdzCollection._count_cmdscmm  +*^==**   778R L 03s8}rYc |j|||dg|j|j||}d|vry|dd}|r|dSdS)zAInternal helper to run an aggregate that returns a single result.)rryr|rkrrBN firstBatchr)rrr|)rrrzrrkrrbatchs rZ_aggregate_one_resultz Collection._aggregate_one_resultsj    T==**   6 !x . uQx*d*rYc 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)rk)rrrM)r_serverrrzrrrs rZ_cmdz1Collection.estimated_document_count.._cmds9 $+DKK"8C JJv ??7D/3RV?W WrYr rrrVr`rr_rzOptional[_ServerMode]rr0)r,_retryable_non_cursor_readr<COUNT)rrrrWs` ` rZestimated_document_countz#Collection.estimated_document_counts6  $%YZ Z   'F9  X, X X X3  X   X..tTSYY.OOrYc *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$grouprOz$sum)rrr ) aggregatepipelinerBr rkc>j|||}|sy|dS)Nrr )rR)rrVrrzrrrkrs rZrWz(Collection.count_documents.._cmd`s. //osIW^_F#; rYrX) rrrr}r~rrr%rrZr<r[) rrrrrr`rWrrks ` @@rZcount_documentszCollection.count_documentss-|v&' V  OOWfjj&89 : f  OOXvzz'':; <   'F9 1FA;#?@A KKXL V Jvf~s$C$44VF^DF6N.vzz+t/LM  6 ,   3   ..tWciiHHrYc|jj}|j|5}|j||j |||cdddS#1swYyxYw)z;Non-cursor read helper to handle implicit session creation.N)rrr_retryable_readr)rfuncrrrrs rZrZz%Collection._retryable_non_cursor_readms\''   ) \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_Collection__create_indexes)rrgrrrs rZcreate_indexeszCollection.create_indexesxs?T Y0   'F9 $t$$Wg@@@rYc 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}r4rrr)indexrrgnamess rZ gen_indexesz0Collection.__create_indexes..gen_indexessT$E%eZ8'$i'[\ %~~HLL&!12"N%sA A) createIndexesrg commitQuorumzRMust be connected to MongoDB 4.4+ to use the commitQuorum option for createIndexes)rzryr{rNrzIterator[Mapping[str, Any]]) rr<CREATE_INDEXESrrrrr,rr?rr1r) rrgrrrsupports_quorumrnrrms ` @rZ__create_indexeszCollection.__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)rr4rh)rkeysrrr cmd_optionsrls rZrzCollection.create_indexse\ & '-zz+'>K $  %,K "4*6*$t$$eWgEEaHHrYc :|||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 rZ drop_indexeszCollection.drop_indexesJs*:   'F9 7W77rYc |}t|trtj|}t|ts t d|j |d}|j||||d<|j|tj5}|j||tjddg|j||dddy#1swYyxYw) 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. z0index_or_name must be an instance of str or list) dropIndexesrlNrr ns not foundrO)rzrr{r)r}rr_gen_index_namer~rrrrr< DROP_INDEXESrr?rr)r index_or_namerrrrrrs rZr{zCollection.drop_indexks^ mT ***=9D$$NO O"kkD9 6  $C N  " "7c6F6F " G 4 MM . 6 6"0"!5"55g>     s 7C  Cctttttt t fjtj|xr|jxstj}|du dfd }jjj|d5}jjj|||tj cdddS#1swYyxYw)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 )ryrzNc 4 jid}  |d< j||||d}t ||j | |j d}|j||S#t$r}|jdk7rdgd}Yd}~`d}~wwxYw) N) listIndexesrBr)rrBrOr)idrP)rexplicit_sessionr)rrr/coder&addressr_maybe_pin_connection) rrVrrzrrBexc cmd_cursorrycollrrrs rZrWz%Collection.list_indexes.._cmds #'++ !4  5sA// B8BBFr) rrrVr`rr_rzr@r'CommandCursor[MutableMapping[str, Any]])rrrrbr r~rrr?r_txn_read_preferencerrrrdr< LIST_INDEXES) rrr read_prefrWrryrrs ` ` @@@rZ list_indexeszCollection.list_indexess6'33&7  ~c3h/ 0   M>KaKa  b ?!=!=!?ZNDZDZ "$. ,   )   5   >__ # # 0 0% @ A??))99ic.>.>:   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. )rrrsr)rritemsrr)rrrrBinforls rZindex_informationzCollection.index_informationsgD""7G"DEe 2 2 45E%LKE&+D6" # rYc 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)ryrzr{r|rBrPrO)rrr retryabler)rrr?rrJr=r r&rrrd get_cursorget_read_preference_performs_writer<LIST_SEARCH_INDEX)rrrrrr`rrs rZlist_search_indexeszCollection.list_search_indexes s0 <$8"#=">H-~>?H  /*22/- !  ,    $D0!L!#45 %%55 NN  # #G , ---++ 6  rYc 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 rrX)r}r7create_search_indexes)rmodelrrrs rZcreate_search_indexzCollection.create_search_indexU s?4%!12$-u-E)t))5'7GNvNqQQrYc l|||d<d fd }|jt|d}|j||j|tj 5}|j ||tjt}|dD cgc]} | d c} cdddScc} w#1swYyxYw) 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 Nrc3tKD].}t|tst|d|j0yw)Nz: is not an instance of pymongo.operations.SearchIndexModel)r}r7rr)rlmodelss rZrnz5Collection.create_search_indexes..gen_indexes s@!%)9:# )#]^nn$  s58)createSearchIndexesrgr)rzryindexesCreatedrrq) rrrrr<CREATE_SEARCH_INDEXESrr?rr1) rrrrrrnrrresprls ` rZrz Collection.create_search_indexess 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)rrrNrr) rrr&rryrzr{r|list_collectionsrr)rrrr(rBrrrs rZrzCollection.options s(oo$$11 OO            %%VT[[$97& CF I**Y+""" w !rYc |||d<|||||||dddii} |jjj| j| j ||| j t jS)NrrBrPrO)rr)rrrdrrrr< AGGREGATE) raggregation_commandr` cursor_classrrrrrrs rZ _aggregatezCollection._aggregate s   'F9 !      !L!#45 %%55 NN  # #G , ---mm 6  rYc |jjj|d5}|jt|t f||du||d|cdddS#1swYyxYw)a=Perform 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`. :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 r&)rr`rrrrrs rZr_zCollection.aggregate4 srf__ # # 0 0 0 F !"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) rrrGr.rrr+rGrr!r')rr`rrrrs rZaggregate_raw_batchesz Collection.aggregate_raw_batches s> ?? ! ! , ,"#[\ \   'F9  __ # # 0 0 0 F !}-4)%,D%8       s 7BB$c 0t|||||||||| | | | 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.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. :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#) rr` full_document resume_aftermax_await_time_ms batch_sizerkstart_at_operation_timer start_afterrfull_document_before_changeshow_expanded_eventss rZwatchzCollection.watch s9t&        #    '   rYc t|ts td|rd|vr td|ddk(s|ddk(r tdd|vr|j d s td |j j d|}|j|d }|j||||d <|j||}|j|tj5}|j jj|5}|jd||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 strrdrerrhriz/collection names must not start or end with '.'rfrgz%collection names must not contain '$')renameCollectiontoNrradminT)r{rrr)r}r~rr-rrrrr_write_concern_for_cmdrr<RENAMErrr) rnew_namerrrrr{rrs rZrenamezCollection.renameM sjH(C(AB B48+@A A A;# "!4OP P (?8#6#6}#EEF Foo**+1XJ7#'#3#38D 6  $C N33CA  " "7cjj " A T''44W= ||"/.2??11 $          s$&E+E. EE EE c Vt|ts tdj|d|d|vr t d||d<t |j ddj|||d< d fd }j||tj S) aGet 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 kwargs: See list of options above. .. versionchanged:: 3.6 Added ``session`` parameter. .. versionchanged:: 3.4 Support the `collation` option. zkey must be an instance of str)distinctrsNqueryz can't pass both filter and queryrkrc Rj||j|ddidS)NvaluesrO)rzr|rkrr)rr|)rrVrrzrrkrs rZrWz!Collection.distinct.._cmd sD == /!..#%qM! rYr) rrrVr`rr_rzrYrr) r}r~rrr,r%rrrZr<DISTINCT) rrsrrrrrWrrks ` @@rZrzCollection.distinct sT#s#<= =;;s3  & ()KLL$F7O.vzz+t/LM  6  $C N ,   3      ..tW .UUrYc`|jd}| tdi|S|j|S)N writeConcernrX)rrKr)rrrraw_wcs rZrz!Collection._write_concern_for_cmd s7(  )&) )**73 3rYc   tjd|t|ts t dt | j dd j||d | tjd| | d< j| |tj|d d<|tj| d <|td || d <%ttstjj | d  fd } jj j#j$| |t&j( S)zInternal findAndModify helper.rzEreturn_document must be ReturnDocument.BEFORE or ReturnDocument.AFTERrkN) findAndModifyrnewr projectionfieldssortrc ^ j}|s tdtd<;|jdkr td|s|jdkr tdd< j |t j ||t}t||jd S) NrrrzJMust 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.r )rzr{rkrrrrN) rr,rrrr?r_FIND_AND_MODIFY_DOC_FIELDSr0r) rrrroutrrrkr rr{s rZ_find_and_modifyz6Collection.__find_and_modify.._find_and_modify s)55L(#,P'+=&9N#((1,,d&$*?*?!*C,s#F -- . 6 6+# /7 C *# .777# #rYr)rrrr_rrrr)rrr}r ValueErrorr%rrrr_fields_list_to_dictrrLr~rrrrrr<FIND_AND_MODIFY)rrrrrreturn_documentrr rrrrrrkr{s` `` @@@rZ__find_and_modifyzCollection.__find_and_modify sh ""8V4/40W /vzz+t/LM $ f_U ?  & &uc 2CJ 6  !#88\RCM  !11$7CK   Xv ."CM  dC(..t433CA  $, $4> $QU $  $ $D%%66  & &  )) 7  rYc 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 Tremoverrr r)_Collection__find_and_modify) rrrrr rrrrs rZfind_one_and_deletezCollection.find_one_and_delete- sOd x   'F9 %t%% J *-D' MS  rYc  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)rrr) rrrrrrrr rrrrs rZfind_one_and_replacezCollection.find_one_and_replace skv &&{3&x   'F9 %t%%           rYc  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 rrr)r rr)rr r!r) rrrrrrrrr rrrrs rZfind_one_and_updatezCollection.find_one_and_update s~F %%f-$$_mD!x   'F9 %t%%            rYctd)Nz#'Collection' object is not iterable)rrs rZ__next__zCollection.__next__ s=>>rYcd|jvrtd|jztd|jjddz)zAThis is only here so that some API misusages are easier to debug.rhz'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.ri)rrsplitrEs rZ__call__zCollection.__call__ s_ dkk !!KK(   57;{{7H7H7Mb7Q R  rY)FNNNNN)rDatabase[_DocumentType]rr~rOptional[bool]ry(Optional[CodecOptions[_DocumentTypeArg]]rzrYr{Optional[WriteConcern]r|Optional[ReadConcern]rrrrrr)rrrr~rzContextManager[Connection]) NNTNNNNNFN)rr_rMutableMapping[str, Any]rzrYryzOptional[CodecOptions]rrrz#Optional[Sequence[Union[str, int]]]r|rr{rrkOptional[_CollationIn]rrrrr Optional[Any]rr5)NF)rr~rrrkrrrrprrurrr)rr~rCollection[_DocumentType])rr~)rrrr)rr0)rr)rr)NNNN) ryrrzrYr{rr|rrr)TFNNN)rz!Sequence[_WriteOp[_DocumentType]]rrrrrrrrrOptional[Mapping]rrAr)rr5rrr{rKr Optional[int]rrrrrrrr)FNN) rz%Union[_DocumentType, RawBSONDocument]rrrrrrrrD)TFNN) rz/Iterable[Union[_DocumentType, RawBSONDocument]]rrrrrrrrrrC) FFNNTFNNNNFNN)"rr_rr5r#Union[Mapping[str, Any], _Pipeline]rrrrr{rrrrrrrrkrr%Optional[Sequence[Mapping[str, Any]]]r Optional[_IndexKeyHint]rrrrrrrrrr) FFNNTFNNNNNN) rr5rrrr~rrrrr{rrrrrrrrkrrrr rrrrrrrrr)FFNNNNN)rr5rr5rrrrrkrr rrrrrrrrrE)FFNNNNNN)rr5rrrrrrrkrrrr rrrrrrrrrE)FNNNNNNN)rr5rrrrrrrrrkrr rrrrrrrrrE)NNN)rrrrrprrr) NNTNNNFNN)rr_rr5rrr{rrrrrrkrr rrrrrrrrrrr5)NNTNNNNN)rr5rrr{rrrrrrkrr rrrrrrrrr5)NNNNN)rr5rkrr rrrrrrrrrB)rrrArrrrzOptional[_DocumentType])rArrrrzCursor[_DocumentType])rArrrrRawBatchCursor[_DocumentType]) rrrr_rzrYrdict[str, Any]rkzOptional[Collation]rr0) rr_rzrYrrrkrrrrr)rrrrrr0)NN) rr5rrrrrrrr0)rezQCallable[[Optional[ClientSession], Server, Connection, Optional[_ServerMode]], T]rrrr~rrM) rgSequence[IndexModel]rrrrrrr list[str])rgrrrrrrr ) rwr:rrrrrrrr~)rrrrrrrr) rr:rrrrrrrr)rrrrrr)rrrrrr) r Optional[str]rrrrrrrz CommandCursor[Mapping[str, Any]]) rz*Union[Mapping[str, Any], SearchIndexModel]rrrrrrrr~) rzlist[SearchIndexModel]rrrrrrrr ) rr~rrrrrrrr) rr~rr5rrrrrrrr)rzType[_AggregationCommand]r`rIrzType[CommandCursor]rrrrrrrrrrrCommandCursor[_DocumentType]) r`rIrrrrrrrrrr ) r`rIrrrrrrrr) NNNNNNNNNNNN)r`zOptional[_Pipeline]rr rrrrrrrkrrzOptional[Timestamp]rrrrrrrr rrrz%CollectionChangeStream[_DocumentType]) rr~rrrrrrrr) rsr~rrrrrrrrrr)rr5rrrrK)rr5r1Optional[Union[Mapping[str, Any], Iterable[str]]]rOptional[_IndexList]rrrrrrr rrrrrrrrr)NNNNNN)rr5rr rr r rrrrrrrrrrrG)rr5rr5rr rr rrrrr rrrrrrrrrrrG)rr5rrrr rr rrrrrrr rrrrrrrrrrrG)rArrrrr)KrRrSrTrUrxrrrrrrrrrrpropertyrrrrrapplyrrrrrrrr"r$r)r2r7r<r>rCr@rHrMrRr\rbrZrirhrr|r{rrrrrrrrrr_rrrrrrQrVrrrr__iter__rnextr __classcell__)rs@rZrbrb}s "'BF1504.2+/}@)}@}@ }@ @ }@ / }@.}@,}@)}@}@ }@~K.K;>K #K2604@D.204,0+/ %%)88*8/ 8 . 8  8>8,8.8*8)88#8 8@9=#!!*!* ! ) ! 6 !! !F &  C !4   CG1504.2 + ?+ /+ . + , + # + Z [[+0+/!%!%_*3_*_*%) _* ) _*  _*_* _*_*R"&) ))$ )  )  )))) )\,1+/!% > 7> %)> ) >  >  > @ [[+0+/!% HJBHJHJ%) HJ ) HJ  HJ HJHJ^04#).,0?C(,+/ %+/!%#SS$S6 S  S  S.SSS'S*S=S&S)SS )!S"#S$ %%St04#).,0?C(,+/+/!%!/ #/ 6/  /  /  / ./ / / '/ */ =/ &/ )/ )/ !/ " %#/ j+0,0(,+/+/!%d !d 'd  d %) d * d &d )d )d d  d T+0,0?C(,+/+/!%o !o 4o  o %) o * o =o &o )o )o o  o j?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++/+ + * + ) + %+2*P^,0!% WI!WI)WI WI  WI WIr \_ \) \ \ \,0!% -A%-A)-A -A  -A  -A^ [[*+*6M*Y\* **^,0!% tItI)tI tI  tI tIp,0!%8(88 8  8B [[,0!% A$A)A A  A  AAJ,0!%E(EE 1 ER,0!%(((( " (X#+/!% 3 3 )3  3  3 * 3 p,0 R9R)R R  R RB,0!% +G&+G)+G +G  +G  +G`,0!%  )      L,0!% ""&") "  "  " "L,0!%,(,, " ,\ [[,0!% 6  *  )    )    &  D,0+/!% ]])]) ]  ]  ] &]D,0!% ..). .  . ' .d)-'+48+/$(,07;+/37!%59/3H %H %H 2 H ) H " H *H "5H )H 1H H &3H -H  /H T [[,0!% ==)= =  = " ==D/3+/!% FV FV,FV) FV  FV  FV FVP4$4/F4 4"& . 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 lH? D  rYrbN)srU __future__r collectionsrtypingrrrrr r r r r rrrrrrrbson.codec_optionsrr bson.objectidr bson.raw_bsonrbson.sonrbson.timestamprpymongorrrrrpymongo.aggregationr r! pymongo.bulkr"pymongo.change_streamr$pymongo.collationr%pymongo.command_cursorr&r'pymongo.commonr(r)pymongo.cursorr*r+pymongo.errorsr,r-r.r/pymongo.helpersr0pymongo.messager1pymongo.operationsr2r3r4r5r6r7r8r9r:r;r<pymongo.read_concernr=r>pymongo.read_preferencesr?r@pymongo.resultsrArBrCrDrEpymongo.typingsrFrGrHrIpymongo.write_concernrJrKrLrMr_WriteOprQr[pymongo.client_sessionr\r]pymongo.databaser^ pymongo.poolr_pymongo.serverr` BaseObjectrbrXrYrZr2s,"&C")$>>88G:1 ::    C@UTWW CL&l  m }    < <74+)'%^4 ""GM$:^4 rY