f`ddlmZddlZddlmZddlmZmZmZddlZddl Z ddl Z ddl Z ddl Z ddl mZddlZddlZ ddlmZmZmZddlmZ ddlZ ddlmZdd lmZdd lmZej>Z ddl#m$Z$ddl%Z%ddl%m&Z&ddl%m'Z(ddl%m)Z)m*Z*m+Z+ddl%m,Z,ddl-m.Z.ddl%m/Z/ddl%m0Z0ddl1m2Z3ddl%m4Z4ddl%m5Z5ddl6m7Z7ddl6m8Z8ddl6m9Z9ddl6m:Z:ddl6m;Z;dd lZ> dd"l?m@Z@ejd#gd$ZCeCd%e d&eCd'e=d(d)ZDd*ZEd+ZFd,ZGd-ZHd.ZIGd/d0e!ZJd1ZKd2ZLd3ZMd4ZNd5ZOGd6d7e!ZPGd8d9e!ZQGd:d;e!ZRd<ZSd=ZTd>ZUd?ZVd@ZWdAZXdBZYdCZZeSeTeUeVeWeXdDZ[y#e$r dxZxZZYHwxYw#e$rdZYQwxYw#e$r Gd d e!ZGd de!Zddl"mZ YZwxYw#e$r dd"lAm@Z@YwxYw)E)divisionN) OrderedDict)IterableMappingMutableMapping)version) json_utilSONBSON)InvalidDocument) IndexModel)ReadPreference)ReturnDocumentc eZdZy)r N)__name__ __module__ __qualname__]/var/lib/jenkins/workspace/mettalog/venv/lib/python3.12/site-packages/mongomock/collection.pyr r s rr ceZdZdZdZy)rFTN)rrrBEFOREAFTERrrrrr!s rr)PRIMARY)NOTHING) aggregate) codec_options)ConfigurationErrorDuplicateKeyErrorBulkWriteError) filteringfilter_applies)helpers)InvalidOperation)raise_for_feature)ObjectId)OperationFailure)BulkWriteResult) DeleteResult)InsertManyResult)InsertOneResult) UpdateResult WriteConcern WriteError) ReadConcern KwargOption)typenamedefaultattrsz&pymongo.read_preference.ReadPreference)documentmode mongos_mode max_stalenessz"pymongo.write_concern.WriteConcern) acknowledgedr7)read_preference write_concernc@t|tst|dy)Nz` must be an instance of dict, bson.son.SON, or other type that inherits from collections.Mapping) isinstancer TypeErroroptionvalues rvalidate_is_mappingrDNs& eW %17:; ; &rc@t|tst|dy)Nzg must be an instance of dict, bson.son.SON, or other type that inherits from collections.MutableMapping)r?rr@rAs rvalidate_is_mutable_mappingrFUs) e^ ,8>AB B -rctd||r1tt|}|jdr t dyy)N replacement$z'replacement can not include $ operators)rDnextiter startswith ValueError)rHfirsts rvalidate_ok_for_replacerO\sB {3T+&'   C FG G !rctd||s tdtt|}|j ds tdy)Nupdatez"update only works with $ operatorsrI)rDrMrJrKrL)rQrNs rvalidate_ok_for_updaterRdsH&) =>> f E   C =>> !rc |r tdi|yy)Nrr.)paramss rvalidate_write_concern_paramsrUms vrcLeZdZd dZdZd dZdZdZdZd dZ d d Z d d Z y) BulkWriteOperationc.||_||_||_yN)builderselector is_upsert)selfrZr[r\s r__init__zBulkWriteOperation.__init__ss   "rcb|jrJt|j|jdS)NTr\)r\rWrZr[r]s rupsertzBulkWriteOperation.upsertxs&>>!!!$,, NNrNc|jj|jfd}|jjj |y)Ncrjj}njj}|jdrd|jdiS|jd}|rd|giSiS)NhintoknRemovednerr writeErrors) delete_many raw_result delete_oneget) op_resultrj collectionrfmultir[s r exec_removez:BulkWriteOperation.register_remove_op..exec_removes&228$2GRR &11(1FQQ }}T""IMM#$677--&C%u--Ir)rZrqr[ executorsappend)r]rrrfrsrqr[s `` @@rregister_remove_opz%BulkWriteOperation.register_remove_op|s:\\,, ==  %%k2rcD|jrJ|jdy)NTrrr\rvras rremovezBulkWriteOperation.removes >>!! d+rcD|jrJ|jdy)NFrxryras r remove_onezBulkWriteOperation.remove_ones >>!! e,rc jds tjjjfd}jj j |y)Nrzcljd jd}i}|jdr)|jd|d<|jd|d<n|jd}|||d<|jd}|||d<|jdr|jd|d<|S) N)specr7rrrbupsertedri nUpsertednMatched nModifiedrjr)_updater\ro) resultret_valmatchedmodifiedrqr7 extra_argsrrr[r]s r exec_updatez:BulkWriteOperation.register_update_op..exec_updates'Z''6X.3DNN6*46FGzz*%&,jj&< #'-zz# $ **S/&*1GJ'zz+.H#'/ $zz% !'E!2Nr)rorRrZrqr[rtru)r]r7rrrrrqr[s```` @@rregister_update_opz%BulkWriteOperation.register_update_opsS~~h' "8 ,\\,, ==  $ %%k2rc,|j|d|y)NTrrrfrr]r7rfs rrQzBulkWriteOperation.updates 4@rc,|j|d|y)NFrrrs r update_onezBulkWriteOperation.update_ones DArc.|j|dd|y)NFT)rrrzrfrrs r replace_onezBulkWriteOperation.replace_ones dNrFrY) rrrr^rbrvrzr|rrQrrrrrrWrWrs3# O3",-36ABOrrWc6t}|jD]\}}d|vrCt|j|tr|st d|zt d|z|||<M|jdd}t|\}}t|j|ts"||vrt d|d|t||<||||<t}|jD])\}}t|trt|||<%|||<+|S)zRe-format a projection fields spec into a nested dictionary. e.g: {'a': 1, 'b.c': 1, 'b.d': 1} => {'a': 1, 'b': {'c': 1, 'd': 1}} .z>Mongomock does not support overriding excluding projection: %szPath collision at %szPath collision at z remaining portion ) ritemsr?rodictNotImplementedErrorr(splittuple_combine_projection_spec)projection_fields_spectmp_specfv split_field base_field new_field combined_specs rrrs& }H&,,.1 a<(,,q/40-X./00''='ABBHQK''#q/K$)+$6 !J hll:6=)*GH)TVV'2}$./HZ  +#/& MM 1 a 7:M!  M!  ! rc d|vr|r tdtd|}|jD]\}}|j|t}t |t rYt |ttfr |Dcgc]}t||||c}||<bt |t sst||||||<|r|tus |r|tust||||<|Scc}w)NrIz5Positional projection is not implemented in mongomockz:Cannot exclude array elements with the positional operator) rr(rrorr?rlistr_project_by_spec _copy_field) doccombined_projection_spec is_include containerdoc_copykeyvalrsub_docs rrrs && %&]^ ^[\\{HIIKS'++C9 dD !#e}-03!5%,"2'4Y!W!5 C& 0dJ R T0*QX'Y7HSM  O!5s:C"ct|tr&g}|D]}|jt|||St|tr0|}|j D]\}}t||||<|St j |SrY)r?rrurrrcopy)objrnewitemrrCs rrrs{#tD JJ{43 4 #tk))+JC"5)4CH& 99S>rc|jD]4\}}d|vrtd|dt|ts*t |6y)Nz6Field names cannot contain the null character (found: ))rr r?r#_recursive_key_check_null_character)datarrCs rrrsGjjl U 3;!$Z[^Z__`"ab b eW % / 6 #rct||jD]"}|jdstd|dy)NrIz=Top-level field names cannot start with the "$" sign (found: r)rkeysrLr )rrs r_validate_data_fieldsr sD'-yy{ >># !%--0E#45 5rcVeZdZd dZdZdZdZdZd dZdZ dd Z dd Z dd Z y)BulkOperationBuilderct||_||_i|_g|_d|_d|_d|_||_y)NFT)rqorderedresultsrtdone_insert_returns_nModified_update_returns_nModified_bypass_document_validation)r]rqrbypass_document_validations rr^zBulkOperationBuilder.__init__s=$   )-&)-&+E(rct||SrY)rW)r]r[s rfindzBulkOperationBuilder.finds!$11rcJfd}jj|y)NcZjjjddiS)N)r nInsertedr)rq insert_oner)rr]sr exec_insertz0BulkOperationBuilder.insert..exec_insert!s1 OO & &0P0P ' R# #r)rtru)r]rrs`` rinsertzBulkOperationBuilder.insert s $ k*rcB|j|}|Jd|d|dt|tr||xx|z cc<yt|tr7|dk(r t ||d}|j |y|j |yJdt |d|d|d) NzUnknow operation result =z (unrecognized key)r)index_idz(Fixme: missed aggreation rule for type: z for key {})ror?intrlenrutype)r] total_resultrrCagg_val new_elements r__aggregate_operation_resultz1BulkOperationBuilder.__aggregate_operation_result's""3'" I=@%%I I" gs #   &   &j (+G UC {+u% I,0M3I I5rc ||_||_yrY)rr)r]rrQs r_set_nModified_policyz*BulkOperationBuilder._set_nModified_policy7s)/&)/&rNc  |js td|jr tdd|_dddgggddd}d}d}d}t|jD]Y\}}|j} |} | jD]\} } |j|| | |d k(rd}d | vrd}||d k(z}[|r|jd nH|r |jrn9|r |jrn*|jr |jrn|jd |jdr t!||S#t $rH} |dj || jt| d|jrYd} ~ Yd} ~ "d} ~ wwxYw) NzBulk operation empty!z Bulk operation already executed!Tr)rrrrkrwriteConcernErrorsrhrFrk)rcodeerrmsgrrr)rtr%r enumeraterr1rurstrrr1_BulkOperationBuilder__aggregate_operation_resultpoprrror ) r]r=r has_update has_insertbroken_nModified_infor execute_func exec_namerperrorrrCs rexecutezBulkOperationBuilder.execute;s~~"#:; ; 99"#EF F  qa!#2a1  %#,T^^#< E<$--I (N !* 1 e11&#uE!2M)! i/,0) )}4 4J'$=* ! JJ{ # D::  D::   + +0N0N  JJ{ # ::m $ ( ( ? }%,,"!JJ!%j. << s/D22 F;7E>>Fc&|j|yrY)r)r]rs r add_insertzBulkOperationBuilder.add_insertms Crcd|r tddt|||}|j|||y)N array_filters3Array filters are not implemented in mongomock yet.r`re)raise_not_implementedrWr) r]r[rrrrb collationrrfwrite_operations r add_updatezBulkOperationBuilder.add_updateps7  !!V X,T8vN**3D*ArcFt|||}|j||y)Nr`re)rWr)r]r[rrbrrfrs r add_replacez BulkOperationBuilder.add_replacexs#,T8vN##Cd#3rcHt||d}|j| |y)NFr`re)rWrv)r]r[just_onerrfrs r add_deletezBulkOperationBuilder.add_delete|s%,T8uM**xd:Z?d;Z@d\d<ZAe je jdkrdad=ZBdbd>ZCd\d?ZDd\d@ZEd\dAZFe je jdkrd\dBZGdCZHd\dDZId\dEZJe je jdkr dcdFZK dcdGZLd]dHZMe je jdkrd\dIZNd\dJZO dPdKZPd\dLZQdTdMZR dddNZSdOZTy)e CollectionNc ||_||_||_|xs t|_|rt |t s td|xs t |_|xst|_ |xstj|_ y)NzDread_concern must be an instance of pymongo.read_concern.ReadConcern)database_name _db_storer/_write_concernr?r2r@ _read_concern_READ_PREFERENCE_PRIMARY_read_preferencemongomock_codec_options CodecOptions_codec_options)r]rnamerr= read_concernr<rs rr^zCollection.__init__st!  "+=|~  < Ebc c):[] / K3K+U/F/S/S/UrcNdj|j|jS)NzCollection({0}, '{1}'))formatrr ras r__repr__zCollection.__repr__s'..t}}diiHHrc@|j|jdz|zS)Nr)rr )r]r s r __getitem__zCollection.__getitem__s}}TYY_t344rc|jdrEt|jjd|d|jd|d|jd|d |j |S)N_z has no attribute 'z'. To access the rz collection, use database['z'].)rLAttributeError __class__rr r)r]attrs r __getattr__zCollection.__getattr__sU ??3  (($ 4DRS S%%rcd|jvr |jn|jjdd}td|z)Nrz'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.)rrr@)r]argskwargsr s r__call__zCollection.__call__sJ  2tzz 8H8H8Mb8Q OQU VW Wrct||jr4|j|jk(xr|j|jk(StSrY)r?rrr NotImplemented)r]others r__eq__zCollection.__eq__s; eT^^ ,==ENN2NtyyEJJ7N Nrz3.12cDt|j|jfSrY)hashrr ras r__hash__zCollection.__hash__s 23 3rcbdj|jj|jS)Nz{0}.{1})r rr rras r full_namezCollection.full_names# 2 2DJJ??rc|jSrY)rras rr zCollection.names zzrc|jSrY)rras rr=zCollection.write_concern"""rc|jSrY)rras rr zCollection.read_concerns!!!rc|jSrY)rras rr<zCollection.read_preferences$$$rc|jSrY)r ras rrzCollection.codec_optionsr'rFct|d|S)NFrrrr]rs rinitialize_unordered_bulk_opz'Collection.initialize_unordered_bulk_ops# %TRRrct|tr|s tdt|}|s|D]}t d|t |j |||dS)Nz"documents must be a non-empty listr7rTr?)r?rr@rrFr+r:)r] documentsrrr@r7s r insert_manyzCollection.insert_manys\)X.i@A AO )%+JA& LLGWL = rc4|j|jSrY)rrras r_storezCollection._stores~~djj))rc |r tddt|tsQg}g}d}t|D]+\}} |j |j ||dz }-|rt||d|Std|Ds tdtrJtjtj d k} | s t#|tj$|| d |vr t'|d <|d } t| t(rtj*| } | |j,vr t/d d tj0|}||j,| < |j3||d S#t $r=} |j || jt| |d|rYd} ~ JYd} ~ ~d} ~ wwxYw#t.$r|j,| =wxYw)Nr@&Mongomock does not handle sessions yetr)rrropr)rkrc3<K|]}t|tywrY)r?r).0ks r z%Collection._insert..s4!:a%4szDocument keys must be strings3.6r<rE11000 Duplicate Key Error*)rr?rrrur:r1rrr allrMr r$PYMONGO_VERSIONrparserencoder'rhashdictrFr$patch_datetime_awareness_in_document_ensure_uniques) r]rr@rr write_errors num_insertedrrrr< object_ids rr:zCollection._inserts  !)-U V$(GLL( t !NN4<<#56!  /$#/!-&N4t44<= =  007==3GGJ%d+ KK 4  "*DKK i &((3I  ##$@%H H;;DA!% I    & E{e" ! ''!& % "%e*" )   !\!  I&  s# E-F6- F36+F..F36Gc |jjjD]}|jds|jd}|jd}|jd}i}|D]\}} t j ||||<!|rt|jdhk(r|d||gi}tt|j|} | dkDstddy#t $rd||<YwxYw) NuniquersparsepartialFilterExpressionz$andrrPrQ) rFindexesvaluesror$get_value_by_dotKeyErrorsetrr_iter_documentsr) r]new_datarr] is_sparsepartial_filter_expression find_kwargsrr answer_counts rrXzCollection._ensure_uniques&s [[((//1E99X&YYu%F (+I(- 2K(L %K Q,'.'?'?#'NK$! S!3!3!564&@(4%(A;'OP tD$8$8$EFGLa'(DeLL%2 ,'+K$,s8C22DDc||jDcic]\}}|tj|c}}Scc}}wrY)rrdeepcopy)r]drLrs r_internalize_dictzCollection._internalize_dict<s.01 :14==##:::s 8cN|jd}|}|D] }||vry||}y)NrFT)r)r]rr key_partsrparts r_has_keyzCollection._has_key?s7IIcN D7"dmGrc d|s t|t|j|||||||| dS)N)rbrfr@rrletTr?rRr-r) r]filterrQrbrrrrfr@rts rrzCollection.update_oneHsE* "6 * LLvD'U^+  6  rc f|s t|t|j|||d|||||  dS)NT)rbrrrfr@rrrtr?ru) r]rvrQrbrrrrfr@rts r update_manyzCollection.update_manySsG* "6 * LLvTg#=c  K  rc ^|s t|t|j|||||dS)N)rbrfr@Tr?)rOr-r)r]rvrHrbrr@rfs rrzCollection.replace_one_s6* #K 0 LLV$PWL X rc jtjdtd|j||||||fi|S)NzIupdate is deprecated. Use replace_one, update_one or update_many instead.r4r5)r7r8r9r)r]rr7rbr;rrr<rs rrQzCollection.updateisB MM12DQR T4<<h E *6.46 6rc /|r tdd|r td| r tdd| r tdd| r tdd tj|}tj|}t d |t d ||j j jd d gkr/tD]&} |j| drtd| d| dd}d}d}d}tj|j|dgD]}d}|t|r|r |jd|d}n!|jd|d}n t}t||}|j!|}|j#|\}}|}d}nt%j&|}d}|dz }d}d}|j)D]\}}|tvr t|}|j+|||||}n|dk(rT|j)D]?\}}d|vsd|vr td|j-||s,|j/|||<An||dk(r|s|j+|||t0|}nY|dk(r|j+|||t2|}n9|dk(r@|j)D]*\}} |j5d}!t7|!dk(rh||vrg||<t9| tr3d| vr/||xxt;| dD"cgc] }"|"||vr|" c}"z cc<r| ||vr||j=| |}|!ddD]}#|#dk(rn|#|vri||#<||#}|j?|||!\}}g}$|!d|vr||!d}$t9| tr(d| vr$|$t;| dD"cgc]}"|"|$vr|" c}"z }$n| |$vr|$j=| |$||!d<-n|d k(ro|j)D]Y\}} |j5d}!d|!vr|s|j?|||!\}}g}%||!dD]\}"t9|"tr3| j)D]\}&}'|"|&|'k7s|%j=|"!F|"| k7sL|%j=|"^|%||!d<|}(|!D] }#|#|(vrn|(|#}(t9|(t:st%j&|(})t9| trL|)D]E}" tA| |"}*|*r|(jE|"$tAd!| id!|"is5|(jE|"G<|)D]}"| |"k(s |(jE|"\n~|d"k(r|j)D]\}} |j5d}!t7|!dk(r"||vr||}(|(D"cgc] }"|"| vs|" c}"||<G|j?|||!\}}|!d|vse||!d}(|(D"cgc] }"|"| vs|" c}"||!d<n|d#k(r|j)D]\}} |j5d}!|j?|||!\}}t9|tr ||vrg||<||}$t9| tr"d| vrd$| vr!|$d| d$t;| dz|$| d$dz}$n|$t;| dz }$d%| vr| d%}+t9|+tratG|+jIj//tK|$/fd&tG|+jMj/dk'}$ntK|$|+dk(}$d)| vr| d)},|,dkr|$|,d}$n |,dk(rg}$n|$d|,}$tG| jIhd*z }-|-r-td+|-j/z|$j=| |$||<n-|r|jID]-}.|.jOdstQd,jS||jd|jd}|jU|||d<tVrJtjXt[j\d-k}|s t_|tWj`||.|jc|je||d|k7rtCd/jS|d|ntQd0jS|d}|s8|jd|jd}|jU|r||d<|r|jg|}|dz }nz|k7ru|jd|jdk7r;||jh|d<td1jS|jd |jk||dz }|rn|j j jnd||r|ndd||d2Scc}"wcc}"w#tB$rd}*YwxYwcc}"wcc}"w#tl$r||jh|d<wxYw)3Nr@rHzRThe hint argument of update is valid but has not been implemented in mongomock yetrzWThe collation argument of update is valid but has not been implemented in mongomock yetrrrtzQThe let argument of update is valid but has not been implemented in mongomock yetrr7 versionArrayT'z/' is empty. You must specify a field like so: {z: {: ...}}Frr)rrz$renamerzkUsing the $rename operator with dots is a valid MongoDB operation, but it is not yet supported by mongomockz $setOnInsertz $currentDatez $addToSet$eachrrIz$pullfieldz$pullAllz$push $position$sortc0tj|SrY)r$rb)rmsort_keys rz$Collection._update..Ysg6N6NqRZ6[rrreverse)r$slice>rrrrzUnrecognized clause in $push: z$field names cannot start with $ [{}]rNrOz/The _id field cannot be changed from {0} to {1}zInvalid modifier specified: {}z`After applying the update, the (immutable) field '_id' was found to have been altered to _id: {}) connectionIdrjrirrgrupdatedExisting)8rrr$rWrDrclient server_info _updatersror1 itertoolschainrer'r _expand_dots_discard_operatorsrrlr1_update_document_fields_with_positional_awarenessrrr _set_updater_current_date_updaterrsplitrr?rru_get_subdocumentr#r(rzrdrsortedrarLrMr clearr rSrrTrrUrQrnr:rFrXrr)0r]rr7rbr;rrr<rfr@rrtrroperatorupdated_existing upserted_id num_updated num_matchedexisting_document was_insertr to_insertroriginal_document_snapshotrN subdocumentrLrupdatersrcdstrrCnested_field_listr field_part push_results pull_resultspull_key pull_valuearrarr_copy is_matching sort_spec slice_valueunused_modifiersrrs0 @rrzCollection._updateps   !)-U V % ! !  !  !  !!V X  ! ;;DA??IFD)J1 ==   + + -n = C%||Hd3$#X/&!   !*1E1Ed1KdV!T J (88E?.u+C\\%(4"5/C"*C 3/  --i8 #66yA 1$-!! -1]];L-M*#' 1 KEK (1 >'lG"&"X"X)1dG[#JK)^$%GGIS#:"5!V# ==):C@5F5J5J35O-c2%..(% "&"X"X)1dL+#OK.("&"X"X)1d4I;#XK+%() u,1LL,=)01Q6$,==;= 1% 8)%6#*e#3$5e$<7;E'N7KAP03+.6G6N+N),AP%P$<%-$,=e,DD 1% 8 ? ? F$+@K $;.9*.E /E.2-B-B 149J.LNK,.L04 C/:$5b$90;  *%67e;K ,37g3G1@,/'*,'>%(1@!@ "'l!: , 3 3E :AMK(9"(=>])2^'\() u,1LL,=)"33#.151F1F$5t=N2P Q,.L'23DR3H'I#-c4#8@E (<*+.x=J+F,8,?,?,DAN%-#&%<$0$7$7$<(JBNK(9"(=>"3C.? #-S#8$)&)*o/@$.c4#8 ('+}}S'9H)%6+3C%<6DUC6P (3(+ 3(0'5w6FRU'W(+ 3,4,4C',|(+ 3,4_)2d*_() u,1LL,=)01Q6$(99&7&>36/29>>3C/D/H/H/JH39(4,[03I4D4D4F0G0K0K0MPQ0Q4SL 4:,PY\]P]3^L'50.3Ho #.?3? 3ML%0A%535L3? 3ML!$EJJL 14] ]-/&0$DGWG[G[G]$]'_!_)//6-9 E*])2`#+==?C"~~c2'11W1^1^_`1a&b b $3 #hhu.?.C.CE.JK)//1?7:-e4)0)@)@7==QVCW)WJ#- 5h ? KKZH)001G1G1QR,U3s:"2 Q!'(9%(@#!F#HH)<CCAFHHu)xhhu&7&;&;E&BC!'')/2%e,"ll+<= q "&@@.11%81@\,<%<6; %<$._raise_incompatibles %-)**rrrr)rrrjoinr?r) r]rexpandedrrrp sub_expandedikey_partrrLrs @@rrzCollection._expand_dotssIIKDAq * Ez#A& I#LE!H(3B8 8</-/L*+H5 hhy!a%01!,5',c  9+,L2 '- .rc|rt|ts|dfSt}|jD]>\}}|dk(r|dfcS|j dr#|j |\}}|r:|||<@|t | fS)NFz$eqrI)r?rrrrLrbool)r]rnew_docrLrnew_v discardeds rrzCollection._discard_operators s*S$/: -IIKDAqEz%x||C #66q9 E9"  DM)))rc |}|i}td||jD]\}}|s td|zt||||||| j |j |S)NrvzUnrecognized field '%s')r)rDrr(Cursor max_time_msallow_disk_use)r]rv projectionskiplimitno_cursor_timeout cursor_typesortallow_partial_results oplog_replay modifiers batch_sizer;rr@rrrrkwargrCs rrzCollection.findsx  <DHd+"LLNLE5&'@5'HII+dD$ D% )++6;{+CNNSaDb crc #rK|j|}|rt|D]u\}dk(r#|dkrttt|}.j drt dj tt|fd|dk}w|D]}|j|||yw)Nz$naturalrrIz1Sorting by {} is not implemented in mongomock yetc0tj|SrY)r!resolve_sort_key)xrs rrz)Collection._get_dataset..2s9+E+EhPQ+Rrr) rereversedrKrrLrr r_copy_only_fields) r]rrfieldsas_classdatasetsort_directionr7rs @r _get_datasetzCollection._get_dataset&s&&t, ,4TN(.z)%)"&xW '>"?&&s+-KRRS[\^^v!R*Q. 01-; H((68D D sB4B7ci}ddh}|jD]@\}}t|ts|D] }||vstdj ||||<B|D]}||=|S)z5Removes and returns fields with projection operators.rrz!Unsupported projection option: {})rr?rrMr )r]rrallowed_projection_operatorsrrCrIs r_extract_projection_operatorsz(Collection._extract_projection_operators7s(4h'?$ ,,.JC%&B!==()L)S)STV)WXX $s )Cs  rc |jD]\}}||vr||vr ||||<nd|vrMt||ts'tdj t ||||d}d}t|trlt |dk7rtdj |||\}} |dkrt |||z}t|| zt ||} t|| }ngt|trW|} d} t ||} | dkrtdt ||| z} nt| t ||} t| | }|r |||||<ntdj ||d|vsqt||tr.d }||D]}t|d|sd }|g||<n|r||=||=y) z0Applies projection operators to copied document.rz-Unsupported type {} for slicing operation: {}Nr4z5Unsupported slice format {} for slicing operation: {}rz4Unsupported slice value {} for slicing operation: {}rFT) rr?rr(r rrminslicermaxr#)r]opsrrrrIop_valueslice_rrlastcountstartendrrs r_apply_projection_operatorsz&Collection._apply_projection_operatorsGsIE2H$C<&)%jHUO2~!(5/48*GNN %12788h<h-8}).SZZ (".//#+KD%ax"8E?3d:te|S%-ABD"4.F#.$EEhuo.Cqy #As8E?';e'C D!%Xe_)=>"5#.F&.uof&=HUO*NUU$b*++r!huot4#G ()"\*:DA&*G/3fHUO! !0#$UO!w%rc|(|s2tjtjdk\r t ||S|sddi}t |t stj|}|jdd}|j|}ttt|jdkDr td|s|dk(r|}n?t ||}n2t|t!|t|jd|}|dk(r|jddn d|vr|d|d<||d<|j#||||j%D] \}}|||< |S)zCopy only the specified fields.Nr2rrz8You cannot currently mix including and excluding fields.r)rr)r$rSrrTrr?rfields_list_to_dictrrrrdrrarMrrrr) r]rrrid_valueprojection_operatorsrrrIs rrzCollection._copy_only_fieldssc >G,C,Cw}}UZG[,[sI. .QZF&$'008F::eQ' $AA&I s4 () *Q .JL L 1}$;&sI6'-f5 03#%H q= LL %|"%e* u  (()=sHM-335IE2F5M6rc\|jD]\}}|j||||y)4Implements the $set behavior on an existing documentN)r_update_document_single_field)r]rrrrLrs r_update_document_fieldsz"Collection._update_document_fieldss*LLNDAq  . .sAq' B#rc |jD]@\}}d|vr!|jd}|s|} |} |ddD]} | dk(r*| jd| } | D]} t| | s| } n2i}| D]`}|j | st |jddkDr*| ||dj |jddd<\| |}b|} | | } | }|ddk(rJt|tr:t|D]*\}}| jd| } t| |s%|||<n|||d|-|j||||C|S)rrIrNrrr) rrror#rLrrr?rrr)r]rrrrrrLrfield_name_parts current_docrrqsubspec_dollarrnew_specelrs r"_update_document_fields_positionalz-Collection._update_document_fields_positionalsLLNDAqax#$773< ""%K"G 0" 53;-4[[w-ON(3#1.$#G26K$))4%#%")B!}}T2#&rxx}#5#9>Ebk%-SXX(* ab(9.;%<07r{H #*#+&1$&7 %!6(#.K'+s2z+t7T&/ &.s88s)anyrrr)r]rrrrr positionals rrz.s"5X!&(35s)rFis_emptyr#rrC)r]rvs `rrezCollection._iter_documentss: ;;   62 &5dkk.C.C)D5 5rc|i}t|tsd|i} t|j|g|i|S#t$rYywxYwNr)r?rrJr StopIteration)r]rvrrs rfind_onezCollection.find_onesX >F&'*V_F   &:4:6:; ;  s9 AAc Pd|d<td||j||fd|i|S)NTrzrvr)rD_find_and_modify)r]rvrrrs rfind_one_and_deletezCollection.find_one_and_delete#s5xHf-$t$$VZMdMfMMrc `td|t||j||||||fi|SNrv)rDrOr)r]rvrHrrrbreturn_documentrs rfind_one_and_replacezCollection.find_one_and_replace(sC Hf- ,$t$$VZf%)?F>DF Frc `td|t||j||||||fi|Sr)rDrRr)r]rvrQrrrbrrs rfind_one_and_updatezCollection.find_one_and_update0sC Hf-v&$t$$VZ%)?F>DF Frc tjdtdd|vr td|j|f||||d|S)Nzlfind_and_modify is deprecated, use find_one_and_delete, find_one_and_replace, or find_one_and_update insteadr4r5rzAfind_and_modify() got an unexpected keyword argument 'projection')rQrbrr)r7r8r9r@r) r]queryrQrbr full_responser;rrs rfind_and_modifyzCollection.find_and_modify9s` MMS, <v% cdd(4((Qvf.2vQIOQ Qrc |r tdd|jdd} |jddr | r td| s |s td| r |r td|j ||| } | s|sy| r d | vrd | d i}| r|j |n|j |||} | d rd | d i}|tjus|jdr|j ||S| S) Nr@rHrzFrz#remove and returnNew can't co-existzMust either update or removezCan't do both update and remove)rrrr) rror(rMrrnrrr) r]rrrQrbrrr@rrzoldupdateds rrzCollection._find_and_modifyCs  !)-U VHe, ::eU #"#HI I&;< < f>? ?mmEjtmD6  5C<CJ'E  OOE "ll5&&9Gz" 34 n22 2fjj6G== 3 3 rc tjdtdtd|t di|d|vr|j |S|j d|di|d|fddi||jddS) Nz9save is deprecated. Use insert_one or replace_one insteadr4r5to_saverTr<r)r7r8r9rFrUrrro)r]r!r;r<rs rsavezCollection.savefs MM$%7A G ' 7 ; ) 3F 3G#{{7++ DLL'$  _OS _W] _;;ud+ +rcXtd|t|j||||dS)Nrv)rrfr@TrDr*_deleter]rvrrfr@s rrnzCollection.delete_oners2Hf- LL94L QSWY Yrc Ztd|t|j|||d|dS)NrvT)rrfrrr@r$r&s rrlzCollection.delete_manyws5Hf- LL94tU\L ]_ce erc|r td|r tdd|r tddtj|}|i}t |t sd|i}t |j|}d}|D]B}|d} t | trtj| } |j| =|dz }|rBn|jjj|d dd S) NzRThe hint argument of delete is valid but has not been implemented in mongomock yetrzWThe collation argument of delete is valid but has not been implemented in mongomock yetr@rHrrr?)rrirgrj)rrr$rWr?rrrrrVrFrrr) r]rvrrfrrr@ to_delete deleted_countrdoc_ids rr%zCollection._delete|s % ! !  !/ 0  !)-U V==fE >F&'*V_F6*+  CZF&$' ))&1 F# Q M!MM0044   rc vtjdtdtdi||j ||S)Nzrfrr1r|r}rz4.2z*BSON field 'count.%s' is an unknown field.r) rrrdrrrr$rSrrTr(rr7)r]rr5s restimated_document_countz#Collection.estimated_document_counts ::i &$%YZ ZV'EE ==   + + -n = C vh &N  " "gmmE&: : vh &N "(>z(JK Z( #'Jx #'Jx 6 )f5I.J.V/5zz:N/OJ+ , $ .6:S3T3`4:JJ?X4YJ0 1,,00< jN:"KjXZ Z eGL KK11M$)3%C+ W%=%=c3%GH*4Ue  /'%++-.JERTXZ^`KK&#%2   Z8-$+$$ T*+!/ ,%++-.JERTXZ]_ ''.. /s0'%F12G1 G>GG H2HHc |D] }t|trtd|z|Dcgc]}|j|jdj ||jj d|jj dd|jj dd|jj dc}Scc}w) Nz6%s is not an instance of pymongo.operations.IndexModelrrEr]Fr^r )r@rEr]r^r )r?r r@r@r7rro)r]r`r@rs rcreate_indexeszCollection.create_indexes!sEeZ0LuTVV!     u%++-#(>>#5#56J#K~~))(E:~~))(E:^^''/  1   sBC c|r tddt|trtj|}n|} |j j |y#t$r}td|z|d}~wwxYw)Nr@rHzindex not found with name [%s]) rr?rr$rGrF drop_indexrcr()r] index_or_namer@r rjs rrVzCollection.drop_index2sm  !)-U V mT *))-8D D U KK " "4 ( U"#Cd#JKQT T UsA A1A,,A1cB|r tddi|j_yr;)rrFr`r=s r drop_indexeszCollection.drop_indexes>s  !)-U V  rc"|r tddyyr;)rr=s rreindexzCollection.reindexDs%i1YZrc#K|jjsydddgif|jjjD] \}}||f yw)N_id_r)rr)rF is_createdr`r)r]r  informations r_list_all_indexeszCollection._list_all_indexesHsU{{%% uzl+++!%!4!4!:!:!< D+ # #"=sAAc#K|r tdd|jD]"\}}t|t|d|d$yw)Nr@rHrr4)rr rrr`r)r]r@r r_s r list_indexeszCollection.list_indexesOsO  !)-U V!%!7!7!9 D+U+,  ":sAAc |r tdd|jDcic]\}}|t|dc}}Scc}}w)Nr@rHr4)rrb)r]r@r rs rindex_informationzCollection.index_informationYsK  !)-U V $557 e $u" "   s>ct td|r tdd|dk(rd}tj}d} d} ddddddddd} tj d} tj d } |j |Dcgc]'}tj|tj )}}| jd ||}| jd ||d|} | D]+}|d jdst|d dd|d <-t| d} |rkt|| dd<|j!D]6}t||}| ddxx|z cc<|dkDs'| ddxxdz cc<8t| | dd<t#|t$t&fr?t)|j*|} | j-| j/| | }|| d<nt#|t0rv|j3dre|j3drTt)|j*j4|d}t)||d} | j/| | }|d|dd| d<n4t#|t6r|j3dr| }| | d<n t9dtj|z dz}t;t=|| d<|r| }|Scc}w) NzoPyExecJS is required in order to run Map-Reduce. Use 'pip install pyexecjs pymongo' to support Map-Reduce mock.r@rHr)inputreduceemitoutputr))counts timeMillisrgra function doMap(fnc, docList) { var mappedDict = {}; function emit(key, val) { if (key['$oid']) { mapped_key = '$oid' + key['$oid']; } else { mapped_key = key; } if(!mappedDict[mapped_key]) { mappedDict[mapped_key] = []; } mappedDict[mapped_key].push(val); } mapper = eval('('+fnc+')'); var mappedList = new Array(); for(var i=0; i.sahrrrkrgrirrhrjrreplacedb)rsrqinlinez5'out' must be an instance of string, dict or bson.SONirl)execjsrrtime perf_countercompilerjsondumpsr r5callrLr'rrrr?rbytesgetattrrr>rr ro_clientrr@rround)r]map_func reduce_funcoutrrrr@ start_timeout_collection reduced_rows full_dictmap_ctx reduce_ctxrdoc_list mapped_rows reduced_rowr emit_countrout_db time_milliss r map_reducezCollection.map_reducebs~)U%i1YZz**,J!NL !   Inn&G0  ) J$(99U#35 3 0A0AB5H5!,,w(CK%??:{KPQWRWXL+ u%008)1+e2DQR2H)IK& ,",4FGL/28} (#G,&++-C!$[%5!6Jh'/:=/!A~!(+H5:5 . 14L0A (#H-#U|,!(!<##%%%l3(&) (#C%#'')*< !6!6D B!(Y!@%%l3(-0Yc)n&U (#C&3778+<&&2 (# WXX,,.;tCK&)% *<&=Il ##NM5s,Kc 6|j||ddi||||S)Nrtr)r@)r)r]rrrrrr@s rinline_map_reducezCollection.inline_map_reduces.??+!}mUE[b#d drc^|r tdd|j|j|Sr;)rrdistinct)r]rrvr@s rrzCollection.distincts*  !)-U Vyy ))#..rctjtjdk\r t dt t dt jd}g}g}g} i} |j|D cgc]} | } } | D]} tj| } | D]3}t| |trt| || |<||vs,||vs1| |=5|D]}|| jvr||| |<|j| |} |D]t!| fd} |D]qtts t#dt%j&| fdD]8\}}|Dcgc]}|}}|j)d ||} |j| :s|D]J} tj| } | D]}||vs||jvs| |=| j| L| }|Scc} wcc}w) NrNzno such command: 'group'zePyExecJS is required in order to use group. Use 'pip install pyexecjs pymongo' to support group mock.a function doReduce(fnc, docList) { reducer = eval('('+fnc+')'); for(var i=0, l=docList.length; i.s):O:OPRTU:Vrrqz9Keys must be a list of key names, each an instance of strc|SrYr)rk2s rrz"Collection.group..s brrn)r$rSrrTr(rurrxrrrlr?r'rrrurr@rgroupbyr{)r]r conditioninitialrhfinalizer ret_array doc_list_copyret_array_copy reduced_valrrrdoc_key initial_keyrgroupr group_listrLrrs @@rrzCollection.groups&&'--*>>&'ABB~)P  ) JIMNK'+yy';<4+>+>$.. Z Zrc n|r tdd|jj|j|fi|Sr;)rrrename_collectionr )r]new_namer@rs rrenamezCollection.rename*s2  !)-U V.t}}..tyy(MfMMrc|r td|r tddt||}|D]}|j|t |j dS)NzeSkipping document validation is a valid MongoDB operation; however Mongomock does not support it yet.r@zYSessions are valid in MongoDB 3.6 and newer; however Mongomock does not support them yet.rBT)rrr _add_to_bulkr)r)r]requestsrrr@bulk operations r bulk_writezCollection.bulk_write/se %%>? ?  !. /$D':!I  " "4 ("t||~t44rctd)Nz;find_raw_batches method is not implemented in mongomock yetr)r]rvrrrrrrrrrrr;rrfmax_scanrrr return_key how_record_idsnapshotcommentrs rfind_raw_batcheszCollection.find_raw_batches>s ""_``rc td)Nz@aggregate_raw_batches method is not implemented in mongomock yetr)r]rrs raggregate_raw_batchesz Collection.aggregate_raw_batchesFs! NP Pr)NNNNr)TTF)FN)TFN)NT)FFNNNNN)FNFNNNN)FFNN)FFFF) FFFFNNNNN)NNrrFNNFFNrTNNNFrYr)TT)NNN)NNFN),)rN)FNrN)NNrrFNNFFNrTNNNNNNFFFNF)Urrrr^rrrrrr$rSrrTr"propertyr$r r=r r<rr/r1rrrDrFr:rXrnrrrrxrrQrrrrrrrrrrrrrrerrrrrrrrr"rnrlr%rzrr7r9r>rCr@rTrVrYr[r`rcrerrrrrrrrrrrrrrrsOS04 VI5&W  -'--"77 4@@##""%%##XWu!55;?%* &S **<|M,;]a=A ?CCG" QV#u!55BG+0 6@EBF8<F P 3,j8 *@A=AHLDH.3 cE" =(~3jC 8<,\.,5 N )-4-;-B-BF(,$u,:,A,AFu!55(*4D*/E$ Q26d %D)7)>)> Du!55 ,Y e ! Fu!55 9 9=62 1 u!55 G7r " U! u!55 [$ u!55GL48a FJO;? d / u!55: x[ ^bZ4N 5 TY?DY]W\NS aPrrceZdZ dfd ZddZdZdZdZeZdZ ddZ e je jdkrdd Zd Zd Zd Zd ZdZddZdZdZdZedZedZdZddZxZS)rc ftt| ||_t j |}||_||_||_||_ d|_ d|_ tj|j|||t|_|dk7r|nd|_||_| |_|j)yNr)superrr^rqr$rW_spec_sort _projection_skip_factory_last_generated_results_results functoolspartialrr_factory_limit _collationr@rewind) r]rqrrrrrrrrr@rs rr^zCursor.__init__Ms fd$&$;;DA  % /3, !))  # #T4TC  %zet #  rc|jr|j|jk7r|jjj r1|jDcgc]}t j|}}nt|j}|j|_||_|r?|j|jd}|jr|dt|j}|S|j}|Scc}wrY) rrrrqrtz_awarer$(make_datetime_timezone_aware_in_documentrrrabs)r]with_limit_and_skiprrs r_compute_resultszCursor._compute_results`s}} D D U,,55$(MMO5 #KKAN55t}}/37==D 0#DM mmDJJK0G{{!"33t{{#34mmG5sC7c|SrYrras r__iter__zCursor.__iter__r rct|j|j|j|j|j |j }|j|_|SrY)rrqrrrrrr)r]cursors rclonez Cursor.cloneusD DJJ0@0@$**dkk[-- rc |jd|j}|xjdz c_|S#t$r}t|d}~wwxYw)NTrr)r_emitted IndexErrorr)r]rrjs r__next__zCursor.__next__{sP +''D'A$--PC MMQ MJ +/s * +s58 A A  Acd|_yr)rras rrz Cursor.rewinds  rctj||}|s td||_t j |j j|j|j|jt|_ |S)Nz&key_or_list must not be the empty list) r$rFrMrrrrqrrrrr)r]rA directionrs rrz Cursor.sortsf((i@EF F !)) OO ( ($**djj$BRBRTXZ  rr2crtjdtd|j|}t |S)NzuEErc|SrYrras r __enter__zCursor.__enter__rrc$|jyrY)r)r]exc_typeexc_valexc_tbs r__exit__zCursor.__exit__s  rcR|jt|jdk7S)NFr)rrrras ralivez Cursor.alives$}}D$9$9e$9$T UUUrc|jSrY)rras rrzCursor.collations rc@|t|ts td|S)Nz&max_time_ms must be an integer or None)r?rr@)r]rs rrzCursor.max_time_mss"  ":k3+GDE E rc@|t|ts td|S)Nzallow_disk_use must be a bool)r?rr@)r]rs rrzCursor.allow_disk_uses"  %j.N;< < r) NNNrrNFrNrrY)rrrr^rrrrrJrrr$rSrrTrrrrrrfrrrrrrrrr __classcell__)rs@rrrKsXYPT&$ + Du!55  S&F>VV rrct|ttfrtj|}t ret jtjdk}|s$d|vs|jdrtd|dt j||i|t|tr|||<t|tr@t|}|dkr td|t!|d z z }|dkDr |dg|zz }|||<yy) NrNrrIzdField name cannot contain the null character and top-level field name cannot start with "$" (found: rrOrNegative index providedr)r?rrrrlr r$rSrrTrLr rUrrr1r)rrrCr< field_indexlen_diffs rrrs%%' e$ ,,w}}U/CC z!Z%:%:3%?%55?LC Z'J?#tJ#t*o ?67 7#c(Q,/ a< D6H$ $C KrcJt|tr|j|dyyrY)r?rrrrrCs rrrs#t  D!rc$t|tr|j|d|z||<t|tr*t |}|dkr t d ||xx|z cc<yy#t $r"|t|dz z }|dg|zz }|||<YywxYw)Nrr r)r?rrorrr1rr)rrrCr r s r _inc_updaterrs#t''*a058J#t*o ?67 7 %   %    %"c#hl3H D6H$ $C$C  %s A$$(BBcdt|tr t|j|||||<yyrY)r?rrrors r _max_updaterr),#tcggj%8%@Jrcdt|tr t|j|||||<yyrY)r?rrrors r _min_updaterr.rrcx|dvrtdt|zt|trEt||tt fr!t ||||<t |||ytdt|t r:t|}|dkr td|t|k\ryt |||yy)N>rrz$pop expects 1 or -1, found: z'Path contains element of non-array typerr ) r1rr?rrr_pop_from_listrr)rrrCr s r _pop_updaterr3s G83u:EFF#t c*ot} 5"3z?3C O 3z?E 2 BCC#t*o ?67 7 #c( " s;'/ rcd|sy|dk(r|jy|dk(r|jdyy)Nrrr)r) list_instancemongo_pop_values rrrGs7 ! B ! rct|tr7|ddik(rtj||<yt j ||<yy)Nz$type timestamp)r?rr$get_current_timestamp mongomockutcnowrs rrrQsD#t Wk* *&;;=C O'..0C O r)z$setz$unsetz$incz$maxz$minz$pop)\ __future__r collectionsrcollections.abcrrrrrrryr3 packagingrrvr7bsonr r r bson.errorsr ImportError json_utilsrupymongo.operationsr pymongorrrrobjectmongomock.read_preferences sentinelsrrrrrrrr r!mongomock.filteringr#r$r%mongomock.not_implementedr&rr'r(mongomock.resultsr)r*r+r,r-mongomock.write_concernr/r1pymongo.read_concernr2mongomock.read_concern namedtuple _KwargOptionrrDrFrOrRrUrWrrrrrrrrrrrrrrrrrrrrr6s%#==   #))+ O-&&-55>KK.&P&-*.-*0 30&{%%m5UV $02J<>",ln$& ;BH? EOEOP!H, 75lD6lD^GPGPT.mVm`!2" % A A 0(1        UB#""J"t# FO V ONOD323sGFFF('G FFF%$F%(!G  G  GG