mongodb.d.ts 257 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753
  1. /// <reference types="node" />
  2. import { Binary } from 'bson';
  3. import { BSON } from 'bson';
  4. import { BSONRegExp } from 'bson';
  5. import { BSONSymbol } from 'bson';
  6. import { BSONType } from 'bson';
  7. import { Code } from 'bson';
  8. import type { ConnectionOptions as ConnectionOptions_2 } from 'tls';
  9. import { DBRef } from 'bson';
  10. import { Decimal128 } from 'bson';
  11. import { deserialize } from 'bson';
  12. import type { DeserializeOptions } from 'bson';
  13. import * as dns from 'dns';
  14. import { Document } from 'bson';
  15. import { Double } from 'bson';
  16. import { Duplex } from 'stream';
  17. import { DuplexOptions } from 'stream';
  18. import { EventEmitter } from 'events';
  19. import { Int32 } from 'bson';
  20. import { Long } from 'bson';
  21. import { MaxKey } from 'bson';
  22. import { MinKey } from 'bson';
  23. import { ObjectId } from 'bson';
  24. import type { ObjectIdLike } from 'bson';
  25. import { Readable } from 'stream';
  26. import { serialize } from 'bson';
  27. import type { SerializeOptions } from 'bson';
  28. import type { Socket } from 'net';
  29. import type { SrvRecord } from 'dns';
  30. import type { TcpNetConnectOpts } from 'net';
  31. import { Timestamp } from 'bson';
  32. import type { TLSSocket } from 'tls';
  33. import type { TLSSocketOptions } from 'tls';
  34. import { Writable } from 'stream';
  35. /* Excluded from this release type: AbstractCallbackOperation */
  36. /** @public */
  37. export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> {
  38. /* Excluded from this release type: [kId] */
  39. /* Excluded from this release type: [kSession] */
  40. /* Excluded from this release type: [kServer] */
  41. /* Excluded from this release type: [kNamespace] */
  42. /* Excluded from this release type: [kDocuments] */
  43. /* Excluded from this release type: [kClient] */
  44. /* Excluded from this release type: [kTransform] */
  45. /* Excluded from this release type: [kInitialized] */
  46. /* Excluded from this release type: [kClosed] */
  47. /* Excluded from this release type: [kKilled] */
  48. /* Excluded from this release type: [kOptions] */
  49. /** @event */
  50. static readonly CLOSE: "close";
  51. /* Excluded from this release type: __constructor */
  52. get id(): Long | undefined;
  53. /* Excluded from this release type: isDead */
  54. /* Excluded from this release type: client */
  55. /* Excluded from this release type: server */
  56. get namespace(): MongoDBNamespace;
  57. get readPreference(): ReadPreference;
  58. get readConcern(): ReadConcern | undefined;
  59. /* Excluded from this release type: session */
  60. /* Excluded from this release type: session */
  61. /* Excluded from this release type: cursorOptions */
  62. get closed(): boolean;
  63. get killed(): boolean;
  64. get loadBalanced(): boolean;
  65. /** Returns current buffered documents length */
  66. bufferedCount(): number;
  67. /** Returns current buffered documents */
  68. readBufferedDocuments(number?: number): TSchema[];
  69. [Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void>;
  70. stream(options?: CursorStreamOptions): Readable & AsyncIterable<TSchema>;
  71. hasNext(): Promise<boolean>;
  72. /** Get the next available document from the cursor, returns null if no more documents are available. */
  73. next(): Promise<TSchema | null>;
  74. /**
  75. * Try to get the next available document from the cursor or `null` if an empty batch is returned
  76. */
  77. tryNext(): Promise<TSchema | null>;
  78. /**
  79. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  80. *
  81. * If the iterator returns `false`, iteration will stop.
  82. *
  83. * @param iterator - The iteration callback.
  84. * @deprecated - Will be removed in a future release. Use for await...of instead.
  85. */
  86. forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>;
  87. close(): Promise<void>;
  88. /**
  89. * Returns an array of documents. The caller is responsible for making sure that there
  90. * is enough memory to store the results. Note that the array only contains partial
  91. * results when this cursor had been previously accessed. In that case,
  92. * cursor.rewind() can be used to reset the cursor.
  93. */
  94. toArray(): Promise<TSchema[]>;
  95. /**
  96. * Add a cursor flag to the cursor
  97. *
  98. * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
  99. * @param value - The flag boolean value.
  100. */
  101. addCursorFlag(flag: CursorFlag, value: boolean): this;
  102. /**
  103. * Map all documents using the provided function
  104. * If there is a transform set on the cursor, that will be called first and the result passed to
  105. * this function's transform.
  106. *
  107. * @remarks
  108. *
  109. * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
  110. * function that maps values to `null` will result in the cursor closing itself before it has finished iterating
  111. * all documents. This will **not** result in a memory leak, just surprising behavior. For example:
  112. *
  113. * ```typescript
  114. * const cursor = collection.find({});
  115. * cursor.map(() => null);
  116. *
  117. * const documents = await cursor.toArray();
  118. * // documents is always [], regardless of how many documents are in the collection.
  119. * ```
  120. *
  121. * Other falsey values are allowed:
  122. *
  123. * ```typescript
  124. * const cursor = collection.find({});
  125. * cursor.map(() => '');
  126. *
  127. * const documents = await cursor.toArray();
  128. * // documents is now an array of empty strings
  129. * ```
  130. *
  131. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  132. * it **does not** return a new instance of a cursor. This means when calling map,
  133. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  134. * Take note of the following example:
  135. *
  136. * @example
  137. * ```typescript
  138. * const cursor: FindCursor<Document> = coll.find();
  139. * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
  140. * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
  141. * ```
  142. * @param transform - The mapping transformation method.
  143. */
  144. map<T = any>(transform: (doc: TSchema) => T): AbstractCursor<T>;
  145. /**
  146. * Set the ReadPreference for the cursor.
  147. *
  148. * @param readPreference - The new read preference for the cursor.
  149. */
  150. withReadPreference(readPreference: ReadPreferenceLike): this;
  151. /**
  152. * Set the ReadPreference for the cursor.
  153. *
  154. * @param readPreference - The new read preference for the cursor.
  155. */
  156. withReadConcern(readConcern: ReadConcernLike): this;
  157. /**
  158. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  159. *
  160. * @param value - Number of milliseconds to wait before aborting the query.
  161. */
  162. maxTimeMS(value: number): this;
  163. /**
  164. * Set the batch size for the cursor.
  165. *
  166. * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
  167. */
  168. batchSize(value: number): this;
  169. /**
  170. * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
  171. * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
  172. * if the resultant data has already been retrieved by this cursor.
  173. */
  174. rewind(): void;
  175. /**
  176. * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
  177. */
  178. abstract clone(): AbstractCursor<TSchema>;
  179. /* Excluded from this release type: _initialize */
  180. /* Excluded from this release type: _getMore */
  181. /* Excluded from this release type: [kInit] */
  182. }
  183. /** @public */
  184. export declare type AbstractCursorEvents = {
  185. [AbstractCursor.CLOSE](): void;
  186. };
  187. /** @public */
  188. export declare interface AbstractCursorOptions extends BSONSerializeOptions {
  189. session?: ClientSession;
  190. readPreference?: ReadPreferenceLike;
  191. readConcern?: ReadConcernLike;
  192. /**
  193. * Specifies the number of documents to return in each response from MongoDB
  194. */
  195. batchSize?: number;
  196. /**
  197. * When applicable `maxTimeMS` controls the amount of time the initial command
  198. * that constructs a cursor should take. (ex. find, aggregate, listCollections)
  199. */
  200. maxTimeMS?: number;
  201. /**
  202. * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores
  203. * that a cursor uses to fetch more data should take. (ex. cursor.next())
  204. */
  205. maxAwaitTimeMS?: number;
  206. /**
  207. * Comment to apply to the operation.
  208. *
  209. * In server versions pre-4.4, 'comment' must be string. A server
  210. * error will be thrown if any other type is provided.
  211. *
  212. * In server versions 4.4 and above, 'comment' can be any valid BSON type.
  213. */
  214. comment?: unknown;
  215. /**
  216. * By default, MongoDB will automatically close a cursor when the
  217. * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections)
  218. * you may use a Tailable Cursor that remains open after the client exhausts
  219. * the results in the initial cursor.
  220. */
  221. tailable?: boolean;
  222. /**
  223. * If awaitData is set to true, when the cursor reaches the end of the capped collection,
  224. * MongoDB blocks the query thread for a period of time waiting for new data to arrive.
  225. * When new data is inserted into the capped collection, the blocked thread is signaled
  226. * to wake up and return the next batch to the client.
  227. */
  228. awaitData?: boolean;
  229. noCursorTimeout?: boolean;
  230. }
  231. /* Excluded from this release type: AbstractOperation */
  232. /** @public */
  233. export declare type AcceptedFields<TSchema, FieldType, AssignableType> = {
  234. readonly [key in KeysOfAType<TSchema, FieldType>]?: AssignableType;
  235. };
  236. /** @public */
  237. export declare type AddToSetOperators<Type> = {
  238. $each?: Array<Flatten<Type>>;
  239. };
  240. /**
  241. * @public
  242. * @deprecated Use the createUser command directly instead.
  243. */
  244. export declare interface AddUserOptions extends CommandOperationOptions {
  245. /** Roles associated with the created user */
  246. roles?: string | string[] | RoleSpecification | RoleSpecification[];
  247. /** Custom data associated with the user (only Mongodb 2.6 or higher) */
  248. customData?: Document;
  249. }
  250. /**
  251. * The **Admin** class is an internal class that allows convenient access to
  252. * the admin functionality and commands for MongoDB.
  253. *
  254. * **ADMIN Cannot directly be instantiated**
  255. * @public
  256. *
  257. * @example
  258. * ```ts
  259. * import { MongoClient } from 'mongodb';
  260. *
  261. * const client = new MongoClient('mongodb://localhost:27017');
  262. * const admin = client.db().admin();
  263. * const dbInfo = await admin.listDatabases();
  264. * for (const db of dbInfo.databases) {
  265. * console.log(db.name);
  266. * }
  267. * ```
  268. */
  269. export declare class Admin {
  270. /* Excluded from this release type: s */
  271. /* Excluded from this release type: __constructor */
  272. /**
  273. * Execute a command
  274. *
  275. * The driver will ensure the following fields are attached to the command sent to the server:
  276. * - `lsid` - sourced from an implicit session or options.session
  277. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  278. * - `$db` - sourced from the name of this database
  279. *
  280. * If the client has a serverApi setting:
  281. * - `apiVersion`
  282. * - `apiStrict`
  283. * - `apiDeprecationErrors`
  284. *
  285. * When in a transaction:
  286. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  287. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  288. *
  289. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  290. *
  291. * @param command - The command to execute
  292. * @param options - Optional settings for the command
  293. */
  294. command(command: Document, options?: RunCommandOptions): Promise<Document>;
  295. /**
  296. * Retrieve the server build information
  297. *
  298. * @param options - Optional settings for the command
  299. */
  300. buildInfo(options?: CommandOperationOptions): Promise<Document>;
  301. /**
  302. * Retrieve the server build information
  303. *
  304. * @param options - Optional settings for the command
  305. */
  306. serverInfo(options?: CommandOperationOptions): Promise<Document>;
  307. /**
  308. * Retrieve this db's server status.
  309. *
  310. * @param options - Optional settings for the command
  311. */
  312. serverStatus(options?: CommandOperationOptions): Promise<Document>;
  313. /**
  314. * Ping the MongoDB server and retrieve results
  315. *
  316. * @param options - Optional settings for the command
  317. */
  318. ping(options?: CommandOperationOptions): Promise<Document>;
  319. /**
  320. * Add a user to the database
  321. *
  322. * @param username - The username for the new user
  323. * @param passwordOrOptions - An optional password for the new user, or the options for the command
  324. * @param options - Optional settings for the command
  325. * @deprecated Use the createUser command in `db.command()` instead.
  326. * @see https://www.mongodb.com/docs/manual/reference/command/createUser/
  327. */
  328. addUser(username: string, passwordOrOptions?: string | AddUserOptions, options?: AddUserOptions): Promise<Document>;
  329. /**
  330. * Remove a user from a database
  331. *
  332. * @param username - The username to remove
  333. * @param options - Optional settings for the command
  334. */
  335. removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
  336. /**
  337. * Validate an existing collection
  338. *
  339. * @param collectionName - The name of the collection to validate.
  340. * @param options - Optional settings for the command
  341. */
  342. validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise<Document>;
  343. /**
  344. * List the available databases
  345. *
  346. * @param options - Optional settings for the command
  347. */
  348. listDatabases(options?: ListDatabasesOptions): Promise<ListDatabasesResult>;
  349. /**
  350. * Get ReplicaSet status
  351. *
  352. * @param options - Optional settings for the command
  353. */
  354. replSetGetStatus(options?: CommandOperationOptions): Promise<Document>;
  355. }
  356. /* Excluded from this release type: AdminPrivate */
  357. /* Excluded from this release type: AggregateOperation */
  358. /** @public */
  359. export declare interface AggregateOptions extends CommandOperationOptions {
  360. /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */
  361. allowDiskUse?: boolean;
  362. /** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */
  363. batchSize?: number;
  364. /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
  365. bypassDocumentValidation?: boolean;
  366. /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */
  367. cursor?: Document;
  368. /** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */
  369. maxTimeMS?: number;
  370. /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */
  371. maxAwaitTimeMS?: number;
  372. /** Specify collation. */
  373. collation?: CollationOptions;
  374. /** Add an index selection hint to an aggregation command */
  375. hint?: Hint;
  376. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  377. let?: Document;
  378. out?: string;
  379. }
  380. /**
  381. * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
  382. * allowing for iteration over the results returned from the underlying query. It supports
  383. * one by one document iteration, conversion to an array or can be iterated as a Node 4.X
  384. * or higher stream
  385. * @public
  386. */
  387. export declare class AggregationCursor<TSchema = any> extends AbstractCursor<TSchema> {
  388. /* Excluded from this release type: [kPipeline] */
  389. /* Excluded from this release type: [kOptions] */
  390. /* Excluded from this release type: __constructor */
  391. get pipeline(): Document[];
  392. clone(): AggregationCursor<TSchema>;
  393. map<T>(transform: (doc: TSchema) => T): AggregationCursor<T>;
  394. /* Excluded from this release type: _initialize */
  395. /** Execute the explain for the cursor */
  396. explain(verbosity?: ExplainVerbosityLike): Promise<Document>;
  397. /** Add a group stage to the aggregation pipeline */
  398. group<T = TSchema>($group: Document): AggregationCursor<T>;
  399. /** Add a limit stage to the aggregation pipeline */
  400. limit($limit: number): this;
  401. /** Add a match stage to the aggregation pipeline */
  402. match($match: Document): this;
  403. /** Add an out stage to the aggregation pipeline */
  404. out($out: {
  405. db: string;
  406. coll: string;
  407. } | string): this;
  408. /**
  409. * Add a project stage to the aggregation pipeline
  410. *
  411. * @remarks
  412. * In order to strictly type this function you must provide an interface
  413. * that represents the effect of your projection on the result documents.
  414. *
  415. * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
  416. * You should specify a parameterized type to have assertions on your final results.
  417. *
  418. * @example
  419. * ```typescript
  420. * // Best way
  421. * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
  422. * // Flexible way
  423. * const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
  424. * ```
  425. *
  426. * @remarks
  427. * In order to strictly type this function you must provide an interface
  428. * that represents the effect of your projection on the result documents.
  429. *
  430. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  431. * it **does not** return a new instance of a cursor. This means when calling project,
  432. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  433. * Take note of the following example:
  434. *
  435. * @example
  436. * ```typescript
  437. * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
  438. * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
  439. * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
  440. *
  441. * // or always use chaining and save the final cursor
  442. *
  443. * const cursor = coll.aggregate().project<{ a: string }>({
  444. * _id: 0,
  445. * a: { $convert: { input: '$a', to: 'string' }
  446. * }});
  447. * ```
  448. */
  449. project<T extends Document = Document>($project: Document): AggregationCursor<T>;
  450. /** Add a lookup stage to the aggregation pipeline */
  451. lookup($lookup: Document): this;
  452. /** Add a redact stage to the aggregation pipeline */
  453. redact($redact: Document): this;
  454. /** Add a skip stage to the aggregation pipeline */
  455. skip($skip: number): this;
  456. /** Add a sort stage to the aggregation pipeline */
  457. sort($sort: Sort): this;
  458. /** Add a unwind stage to the aggregation pipeline */
  459. unwind($unwind: Document | string): this;
  460. /** Add a geoNear stage to the aggregation pipeline */
  461. geoNear($geoNear: Document): this;
  462. }
  463. /** @public */
  464. export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {
  465. }
  466. /**
  467. * It is possible to search using alternative types in mongodb e.g.
  468. * string types can be searched using a regex in mongo
  469. * array types can be searched using their element type
  470. * @public
  471. */
  472. export declare type AlternativeType<T> = T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;
  473. /** @public */
  474. export declare type AnyBulkWriteOperation<TSchema extends Document = Document> = {
  475. insertOne: InsertOneModel<TSchema>;
  476. } | {
  477. replaceOne: ReplaceOneModel<TSchema>;
  478. } | {
  479. updateOne: UpdateOneModel<TSchema>;
  480. } | {
  481. updateMany: UpdateManyModel<TSchema>;
  482. } | {
  483. deleteOne: DeleteOneModel<TSchema>;
  484. } | {
  485. deleteMany: DeleteManyModel<TSchema>;
  486. };
  487. /** @public */
  488. export declare type AnyError = MongoError | Error;
  489. /** @public */
  490. export declare type ArrayElement<Type> = Type extends ReadonlyArray<infer Item> ? Item : never;
  491. /** @public */
  492. export declare type ArrayOperator<Type> = {
  493. $each?: Array<Flatten<Type>>;
  494. $slice?: number;
  495. $position?: number;
  496. $sort?: Sort;
  497. };
  498. /** @public */
  499. export declare interface Auth {
  500. /** The username for auth */
  501. username?: string;
  502. /** The password for auth */
  503. password?: string;
  504. }
  505. /* Excluded from this release type: AuthContext */
  506. /** @public */
  507. export declare const AuthMechanism: Readonly<{
  508. readonly MONGODB_AWS: "MONGODB-AWS";
  509. readonly MONGODB_CR: "MONGODB-CR";
  510. readonly MONGODB_DEFAULT: "DEFAULT";
  511. readonly MONGODB_GSSAPI: "GSSAPI";
  512. readonly MONGODB_PLAIN: "PLAIN";
  513. readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1";
  514. readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256";
  515. readonly MONGODB_X509: "MONGODB-X509";
  516. /** @experimental */
  517. readonly MONGODB_OIDC: "MONGODB-OIDC";
  518. }>;
  519. /** @public */
  520. export declare type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism];
  521. /** @public */
  522. export declare interface AuthMechanismProperties extends Document {
  523. SERVICE_HOST?: string;
  524. SERVICE_NAME?: string;
  525. SERVICE_REALM?: string;
  526. CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue;
  527. AWS_SESSION_TOKEN?: string;
  528. /** @experimental */
  529. REQUEST_TOKEN_CALLBACK?: OIDCRequestFunction;
  530. /** @experimental */
  531. REFRESH_TOKEN_CALLBACK?: OIDCRefreshFunction;
  532. /** @experimental */
  533. PROVIDER_NAME?: 'aws' | 'azure';
  534. /** @experimental */
  535. ALLOWED_HOSTS?: string[];
  536. /** @experimental */
  537. TOKEN_AUDIENCE?: string;
  538. }
  539. /**
  540. * @public
  541. * @deprecated This interface will be removed in the next major version.
  542. */
  543. export declare interface AutoEncrypter {
  544. new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter;
  545. init(cb: Callback): void;
  546. teardown(force: boolean, callback: Callback): void;
  547. encrypt(ns: string, cmd: Document, options: any, callback: Callback<Document>): void;
  548. decrypt(cmd: Document, options: any, callback: Callback<Document>): void;
  549. /** @experimental */
  550. readonly cryptSharedLibVersionInfo: {
  551. version: bigint;
  552. versionStr: string;
  553. } | null;
  554. }
  555. /** @public */
  556. export declare const AutoEncryptionLoggerLevel: Readonly<{
  557. readonly FatalError: 0;
  558. readonly Error: 1;
  559. readonly Warning: 2;
  560. readonly Info: 3;
  561. readonly Trace: 4;
  562. }>;
  563. /** @public */
  564. export declare type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel];
  565. /** @public */
  566. export declare interface AutoEncryptionOptions {
  567. /* Excluded from this release type: metadataClient */
  568. /** A `MongoClient` used to fetch keys from a key vault */
  569. keyVaultClient?: MongoClient;
  570. /** The namespace where keys are stored in the key vault */
  571. keyVaultNamespace?: string;
  572. /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */
  573. kmsProviders?: {
  574. /** Configuration options for using 'aws' as your KMS provider */
  575. aws?: {
  576. /** The access key used for the AWS KMS provider */
  577. accessKeyId: string;
  578. /** The secret access key used for the AWS KMS provider */
  579. secretAccessKey: string;
  580. /**
  581. * An optional AWS session token that will be used as the
  582. * X-Amz-Security-Token header for AWS requests.
  583. */
  584. sessionToken?: string;
  585. } | Record<string, never>;
  586. /** Configuration options for using 'local' as your KMS provider */
  587. local?: {
  588. /**
  589. * The master key used to encrypt/decrypt data keys.
  590. * A 96-byte long Buffer or base64 encoded string.
  591. */
  592. key: Buffer | string;
  593. };
  594. /** Configuration options for using 'azure' as your KMS provider */
  595. azure?: {
  596. /** The tenant ID identifies the organization for the account */
  597. tenantId: string;
  598. /** The client ID to authenticate a registered application */
  599. clientId: string;
  600. /** The client secret to authenticate a registered application */
  601. clientSecret: string;
  602. /**
  603. * If present, a host with optional port. E.g. "example.com" or "example.com:443".
  604. * This is optional, and only needed if customer is using a non-commercial Azure instance
  605. * (e.g. a government or China account, which use different URLs).
  606. * Defaults to "login.microsoftonline.com"
  607. */
  608. identityPlatformEndpoint?: string | undefined;
  609. } | {
  610. /**
  611. * If present, an access token to authenticate with Azure.
  612. */
  613. accessToken: string;
  614. } | Record<string, never>;
  615. /** Configuration options for using 'gcp' as your KMS provider */
  616. gcp?: {
  617. /** The service account email to authenticate */
  618. email: string;
  619. /** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */
  620. privateKey: string | Buffer;
  621. /**
  622. * If present, a host with optional port. E.g. "example.com" or "example.com:443".
  623. * Defaults to "oauth2.googleapis.com"
  624. */
  625. endpoint?: string | undefined;
  626. } | {
  627. /**
  628. * If present, an access token to authenticate with GCP.
  629. */
  630. accessToken: string;
  631. } | Record<string, never>;
  632. /**
  633. * Configuration options for using 'kmip' as your KMS provider
  634. */
  635. kmip?: {
  636. /**
  637. * The output endpoint string.
  638. * The endpoint consists of a hostname and port separated by a colon.
  639. * E.g. "example.com:123". A port is always present.
  640. */
  641. endpoint?: string;
  642. };
  643. };
  644. /**
  645. * A map of namespaces to a local JSON schema for encryption
  646. *
  647. * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.
  648. * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.
  649. * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.
  650. * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
  651. */
  652. schemaMap?: Document;
  653. /** Supply a schema for the encrypted fields in the document */
  654. encryptedFieldsMap?: Document;
  655. /** Allows the user to bypass auto encryption, maintaining implicit decryption */
  656. bypassAutoEncryption?: boolean;
  657. /** Allows users to bypass query analysis */
  658. bypassQueryAnalysis?: boolean;
  659. options?: {
  660. /** An optional hook to catch logging messages from the underlying encryption engine */
  661. logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
  662. };
  663. extraOptions?: {
  664. /**
  665. * A local process the driver communicates with to determine how to encrypt values in a command.
  666. * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise
  667. */
  668. mongocryptdURI?: string;
  669. /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */
  670. mongocryptdBypassSpawn?: boolean;
  671. /** The path to the mongocryptd executable on the system */
  672. mongocryptdSpawnPath?: string;
  673. /** Command line arguments to use when auto-spawning a mongocryptd */
  674. mongocryptdSpawnArgs?: string[];
  675. /**
  676. * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd).
  677. *
  678. * This needs to be the path to the file itself, not a directory.
  679. * It can be an absolute or relative path. If the path is relative and
  680. * its first component is `$ORIGIN`, it will be replaced by the directory
  681. * containing the mongodb-client-encryption native addon file. Otherwise,
  682. * the path will be interpreted relative to the current working directory.
  683. *
  684. * Currently, loading different MongoDB Crypt shared library files from different
  685. * MongoClients in the same process is not supported.
  686. *
  687. * If this option is provided and no MongoDB Crypt shared library could be loaded
  688. * from the specified location, creating the MongoClient will fail.
  689. *
  690. * If this option is not provided and `cryptSharedLibRequired` is not specified,
  691. * the AutoEncrypter will attempt to spawn and/or use mongocryptd according
  692. * to the mongocryptd-specific `extraOptions` options.
  693. *
  694. * Specifying a path prevents mongocryptd from being used as a fallback.
  695. *
  696. * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
  697. */
  698. cryptSharedLibPath?: string;
  699. /**
  700. * If specified, never use mongocryptd and instead fail when the MongoDB Crypt
  701. * shared library could not be loaded.
  702. *
  703. * This is always true when `cryptSharedLibPath` is specified.
  704. *
  705. * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
  706. */
  707. cryptSharedLibRequired?: boolean;
  708. /* Excluded from this release type: cryptSharedLibSearchPaths */
  709. };
  710. proxyOptions?: ProxyOptions;
  711. /** The TLS options to use connecting to the KMS provider */
  712. tlsOptions?: {
  713. aws?: AutoEncryptionTlsOptions;
  714. local?: AutoEncryptionTlsOptions;
  715. azure?: AutoEncryptionTlsOptions;
  716. gcp?: AutoEncryptionTlsOptions;
  717. kmip?: AutoEncryptionTlsOptions;
  718. };
  719. }
  720. /** @public */
  721. export declare interface AutoEncryptionTlsOptions {
  722. /**
  723. * Specifies the location of a local .pem file that contains
  724. * either the client's TLS/SSL certificate and key or only the
  725. * client's TLS/SSL key when tlsCertificateFile is used to
  726. * provide the certificate.
  727. */
  728. tlsCertificateKeyFile?: string;
  729. /**
  730. * Specifies the password to de-crypt the tlsCertificateKeyFile.
  731. */
  732. tlsCertificateKeyFilePassword?: string;
  733. /**
  734. * Specifies the location of a local .pem file that contains the
  735. * root certificate chain from the Certificate Authority.
  736. * This file is used to validate the certificate presented by the
  737. * KMS provider.
  738. */
  739. tlsCAFile?: string;
  740. }
  741. /**
  742. * Keeps the state of a unordered batch so we can rewrite the results
  743. * correctly after command execution
  744. *
  745. * @public
  746. */
  747. export declare class Batch<T = Document> {
  748. originalZeroIndex: number;
  749. currentIndex: number;
  750. originalIndexes: number[];
  751. batchType: BatchType;
  752. operations: T[];
  753. size: number;
  754. sizeBytes: number;
  755. constructor(batchType: BatchType, originalZeroIndex: number);
  756. }
  757. /** @public */
  758. export declare const BatchType: Readonly<{
  759. readonly INSERT: 1;
  760. readonly UPDATE: 2;
  761. readonly DELETE: 3;
  762. }>;
  763. /** @public */
  764. export declare type BatchType = (typeof BatchType)[keyof typeof BatchType];
  765. export { Binary }
  766. /* Excluded from this release type: BinMsg */
  767. /** @public */
  768. export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray<number>;
  769. export { BSON }
  770. export { BSONRegExp }
  771. /**
  772. * BSON Serialization options.
  773. * @public
  774. */
  775. export declare interface BSONSerializeOptions extends Omit<SerializeOptions, 'index'>, Omit<DeserializeOptions, 'evalFunctions' | 'cacheFunctions' | 'cacheFunctionsCrc32' | 'allowObjectSmallerThanBufferSize' | 'index' | 'validation'> {
  776. /**
  777. * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html)
  778. * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize).
  779. * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe)
  780. * for more detail about what "unsafe" refers to in this context.
  781. * If you need to maintain your own editable clone of the bytes returned for an extended life time of the process, it is recommended you allocate
  782. * your own buffer and clone the contents:
  783. *
  784. * @example
  785. * ```ts
  786. * const raw = await collection.findOne({}, { raw: true });
  787. * const myBuffer = Buffer.alloc(raw.byteLength);
  788. * myBuffer.set(raw, 0);
  789. * // Only save and use `myBuffer` beyond this point
  790. * ```
  791. *
  792. * @remarks
  793. * Please note there is a known limitation where this option cannot be used at the MongoClient level (see [NODE-3946](https://jira.mongodb.org/browse/NODE-3946)).
  794. * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work.
  795. */
  796. raw?: boolean;
  797. /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */
  798. enableUtf8Validation?: boolean;
  799. }
  800. export { BSONSymbol }
  801. export { BSONType }
  802. /** @public */
  803. export declare type BSONTypeAlias = keyof typeof BSONType;
  804. /* Excluded from this release type: BufferPool */
  805. /** @public */
  806. export declare abstract class BulkOperationBase {
  807. isOrdered: boolean;
  808. /* Excluded from this release type: s */
  809. operationId?: number;
  810. /* Excluded from this release type: __constructor */
  811. /**
  812. * Add a single insert document to the bulk operation
  813. *
  814. * @example
  815. * ```ts
  816. * const bulkOp = collection.initializeOrderedBulkOp();
  817. *
  818. * // Adds three inserts to the bulkOp.
  819. * bulkOp
  820. * .insert({ a: 1 })
  821. * .insert({ b: 2 })
  822. * .insert({ c: 3 });
  823. * await bulkOp.execute();
  824. * ```
  825. */
  826. insert(document: Document): BulkOperationBase;
  827. /**
  828. * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
  829. * Returns a builder object used to complete the definition of the operation.
  830. *
  831. * @example
  832. * ```ts
  833. * const bulkOp = collection.initializeOrderedBulkOp();
  834. *
  835. * // Add an updateOne to the bulkOp
  836. * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
  837. *
  838. * // Add an updateMany to the bulkOp
  839. * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
  840. *
  841. * // Add an upsert
  842. * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
  843. *
  844. * // Add a deletion
  845. * bulkOp.find({ g: 7 }).deleteOne();
  846. *
  847. * // Add a multi deletion
  848. * bulkOp.find({ h: 8 }).delete();
  849. *
  850. * // Add a replaceOne
  851. * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
  852. *
  853. * // Update using a pipeline (requires Mongodb 4.2 or higher)
  854. * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
  855. * { $set: { total: { $sum: [ '$y', '$z' ] } } }
  856. * ]);
  857. *
  858. * // All of the ops will now be executed
  859. * await bulkOp.execute();
  860. * ```
  861. */
  862. find(selector: Document): FindOperators;
  863. /** Specifies a raw operation to perform in the bulk write. */
  864. raw(op: AnyBulkWriteOperation): this;
  865. get bsonOptions(): BSONSerializeOptions;
  866. get writeConcern(): WriteConcern | undefined;
  867. get batches(): Batch[];
  868. execute(options?: BulkWriteOptions): Promise<BulkWriteResult>;
  869. /* Excluded from this release type: handleWriteError */
  870. abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
  871. }
  872. /* Excluded from this release type: BulkOperationPrivate */
  873. /* Excluded from this release type: BulkResult */
  874. /** @public */
  875. export declare interface BulkWriteOperationError {
  876. index: number;
  877. code: number;
  878. errmsg: string;
  879. errInfo: Document;
  880. op: Document | UpdateStatement | DeleteStatement;
  881. }
  882. /** @public */
  883. export declare interface BulkWriteOptions extends CommandOperationOptions {
  884. /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
  885. bypassDocumentValidation?: boolean;
  886. /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */
  887. ordered?: boolean;
  888. /** Force server to assign _id values instead of driver. */
  889. forceServerObjectId?: boolean;
  890. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  891. let?: Document;
  892. }
  893. /**
  894. * @public
  895. * The result of a bulk write.
  896. */
  897. export declare class BulkWriteResult {
  898. private readonly result;
  899. /** Number of documents inserted. */
  900. readonly insertedCount: number;
  901. /** Number of documents matched for update. */
  902. readonly matchedCount: number;
  903. /** Number of documents modified. */
  904. readonly modifiedCount: number;
  905. /** Number of documents deleted. */
  906. readonly deletedCount: number;
  907. /** Number of documents upserted. */
  908. readonly upsertedCount: number;
  909. /** Upserted document generated Id's, hash key is the index of the originating operation */
  910. readonly upsertedIds: {
  911. [key: number]: any;
  912. };
  913. /** Inserted document generated Id's, hash key is the index of the originating operation */
  914. readonly insertedIds: {
  915. [key: number]: any;
  916. };
  917. private static generateIdMap;
  918. /* Excluded from this release type: __constructor */
  919. /** Evaluates to true if the bulk operation correctly executes */
  920. get ok(): number;
  921. /**
  922. * The number of inserted documents
  923. * @deprecated Use insertedCount instead.
  924. */
  925. get nInserted(): number;
  926. /**
  927. * Number of upserted documents
  928. * @deprecated User upsertedCount instead.
  929. */
  930. get nUpserted(): number;
  931. /**
  932. * Number of matched documents
  933. * @deprecated Use matchedCount instead.
  934. */
  935. get nMatched(): number;
  936. /**
  937. * Number of documents updated physically on disk
  938. * @deprecated Use modifiedCount instead.
  939. */
  940. get nModified(): number;
  941. /**
  942. * Number of removed documents
  943. * @deprecated Use deletedCount instead.
  944. */
  945. get nRemoved(): number;
  946. /**
  947. * Returns an array of all inserted ids
  948. * @deprecated Use insertedIds instead.
  949. */
  950. getInsertedIds(): Document[];
  951. /**
  952. * Returns an array of all upserted ids
  953. * @deprecated Use upsertedIds instead.
  954. */
  955. getUpsertedIds(): Document[];
  956. /** Returns the upserted id at the given index */
  957. getUpsertedIdAt(index: number): Document | undefined;
  958. /** Returns raw internal result */
  959. getRawResponse(): Document;
  960. /** Returns true if the bulk operation contains a write error */
  961. hasWriteErrors(): boolean;
  962. /** Returns the number of write errors off the bulk operation */
  963. getWriteErrorCount(): number;
  964. /** Returns a specific write error object */
  965. getWriteErrorAt(index: number): WriteError | undefined;
  966. /** Retrieve all write errors */
  967. getWriteErrors(): WriteError[];
  968. /** Retrieve the write concern error if one exists */
  969. getWriteConcernError(): WriteConcernError | undefined;
  970. toString(): string;
  971. isOk(): boolean;
  972. }
  973. /**
  974. * MongoDB Driver style callback
  975. * @public
  976. */
  977. export declare type Callback<T = any> = (error?: AnyError, result?: T) => void;
  978. /** @public */
  979. export declare class CancellationToken extends TypedEventEmitter<{
  980. cancel(): void;
  981. }> {
  982. }
  983. /**
  984. * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
  985. * @public
  986. */
  987. export declare class ChangeStream<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> {
  988. pipeline: Document[];
  989. /**
  990. * @remarks WriteConcern can still be present on the options because
  991. * we inherit options from the client/db/collection. The
  992. * key must be present on the options in order to delete it.
  993. * This allows typescript to delete the key but will
  994. * not allow a writeConcern to be assigned as a property on options.
  995. */
  996. options: ChangeStreamOptions & {
  997. writeConcern?: never;
  998. };
  999. parent: MongoClient | Db | Collection;
  1000. namespace: MongoDBNamespace;
  1001. type: symbol;
  1002. /* Excluded from this release type: cursor */
  1003. streamOptions?: CursorStreamOptions;
  1004. /* Excluded from this release type: [kCursorStream] */
  1005. /* Excluded from this release type: [kClosed] */
  1006. /* Excluded from this release type: [kMode] */
  1007. /** @event */
  1008. static readonly RESPONSE: "response";
  1009. /** @event */
  1010. static readonly MORE: "more";
  1011. /** @event */
  1012. static readonly INIT: "init";
  1013. /** @event */
  1014. static readonly CLOSE: "close";
  1015. /**
  1016. * Fired for each new matching change in the specified namespace. Attaching a `change`
  1017. * event listener to a Change Stream will switch the stream into flowing mode. Data will
  1018. * then be passed as soon as it is available.
  1019. * @event
  1020. */
  1021. static readonly CHANGE: "change";
  1022. /** @event */
  1023. static readonly END: "end";
  1024. /** @event */
  1025. static readonly ERROR: "error";
  1026. /**
  1027. * Emitted each time the change stream stores a new resume token.
  1028. * @event
  1029. */
  1030. static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged";
  1031. /* Excluded from this release type: __constructor */
  1032. /* Excluded from this release type: cursorStream */
  1033. /** The cached resume token that is used to resume after the most recently returned change. */
  1034. get resumeToken(): ResumeToken;
  1035. /** Check if there is any document still available in the Change Stream */
  1036. hasNext(): Promise<boolean>;
  1037. /** Get the next available document from the Change Stream. */
  1038. next(): Promise<TChange>;
  1039. /**
  1040. * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned
  1041. */
  1042. tryNext(): Promise<TChange | null>;
  1043. [Symbol.asyncIterator](): AsyncGenerator<TChange, void, void>;
  1044. /** Is the cursor closed */
  1045. get closed(): boolean;
  1046. /** Close the Change Stream */
  1047. close(): Promise<void>;
  1048. /**
  1049. * Return a modified Readable stream including a possible transform method.
  1050. *
  1051. * NOTE: When using a Stream to process change stream events, the stream will
  1052. * NOT automatically resume in the case a resumable error is encountered.
  1053. *
  1054. * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed
  1055. */
  1056. stream(options?: CursorStreamOptions): Readable & AsyncIterable<TChange>;
  1057. /* Excluded from this release type: _setIsEmitter */
  1058. /* Excluded from this release type: _setIsIterator */
  1059. /* Excluded from this release type: _createChangeStreamCursor */
  1060. /* Excluded from this release type: _closeEmitterModeWithError */
  1061. /* Excluded from this release type: _streamEvents */
  1062. /* Excluded from this release type: _endStream */
  1063. /* Excluded from this release type: _processChange */
  1064. /* Excluded from this release type: _processErrorStreamMode */
  1065. /* Excluded from this release type: _processErrorIteratorMode */
  1066. }
  1067. /* Excluded from this release type: ChangeStreamAggregateRawResult */
  1068. /**
  1069. * Only present when the `showExpandedEvents` flag is enabled.
  1070. * @public
  1071. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1072. */
  1073. export declare interface ChangeStreamCollModDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
  1074. /** Describes the type of operation represented in this change notification */
  1075. operationType: 'modify';
  1076. }
  1077. /**
  1078. * @public
  1079. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1080. */
  1081. export declare interface ChangeStreamCreateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
  1082. /** Describes the type of operation represented in this change notification */
  1083. operationType: 'create';
  1084. }
  1085. /**
  1086. * Only present when the `showExpandedEvents` flag is enabled.
  1087. * @public
  1088. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1089. */
  1090. export declare interface ChangeStreamCreateIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1091. /** Describes the type of operation represented in this change notification */
  1092. operationType: 'createIndexes';
  1093. }
  1094. /* Excluded from this release type: ChangeStreamCursor */
  1095. /* Excluded from this release type: ChangeStreamCursorOptions */
  1096. /**
  1097. * @public
  1098. * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event
  1099. */
  1100. export declare interface ChangeStreamDeleteDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID {
  1101. /** Describes the type of operation represented in this change notification */
  1102. operationType: 'delete';
  1103. /** Namespace the delete event occurred on */
  1104. ns: ChangeStreamNameSpace;
  1105. /**
  1106. * Contains the pre-image of the modified or deleted document if the
  1107. * pre-image is available for the change event and either 'required' or
  1108. * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
  1109. * when creating the change stream. If 'whenAvailable' was specified but the
  1110. * pre-image is unavailable, this will be explicitly set to null.
  1111. */
  1112. fullDocumentBeforeChange?: TSchema;
  1113. }
  1114. /** @public */
  1115. export declare type ChangeStreamDocument<TSchema extends Document = Document> = ChangeStreamInsertDocument<TSchema> | ChangeStreamUpdateDocument<TSchema> | ChangeStreamReplaceDocument<TSchema> | ChangeStreamDeleteDocument<TSchema> | ChangeStreamDropDocument | ChangeStreamRenameDocument | ChangeStreamDropDatabaseDocument | ChangeStreamInvalidateDocument | ChangeStreamCreateIndexDocument | ChangeStreamCreateDocument | ChangeStreamCollModDocument | ChangeStreamDropIndexDocument | ChangeStreamShardCollectionDocument | ChangeStreamReshardCollectionDocument | ChangeStreamRefineCollectionShardKeyDocument;
  1116. /** @public */
  1117. export declare interface ChangeStreamDocumentCollectionUUID {
  1118. /**
  1119. * The UUID (Binary subtype 4) of the collection that the operation was performed on.
  1120. *
  1121. * Only present when the `showExpandedEvents` flag is enabled.
  1122. *
  1123. * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers
  1124. * flag is enabled.
  1125. *
  1126. * @sinceServerVersion 6.1.0
  1127. */
  1128. collectionUUID: Binary;
  1129. }
  1130. /** @public */
  1131. export declare interface ChangeStreamDocumentCommon {
  1132. /**
  1133. * The id functions as an opaque token for use when resuming an interrupted
  1134. * change stream.
  1135. */
  1136. _id: ResumeToken;
  1137. /**
  1138. * The timestamp from the oplog entry associated with the event.
  1139. * For events that happened as part of a multi-document transaction, the associated change stream
  1140. * notifications will have the same clusterTime value, namely the time when the transaction was committed.
  1141. * On a sharded cluster, events that occur on different shards can have the same clusterTime but be
  1142. * associated with different transactions or even not be associated with any transaction.
  1143. * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
  1144. */
  1145. clusterTime?: Timestamp;
  1146. /**
  1147. * The transaction number.
  1148. * Only present if the operation is part of a multi-document transaction.
  1149. *
  1150. * **NOTE:** txnNumber can be a Long if promoteLongs is set to false
  1151. */
  1152. txnNumber?: number;
  1153. /**
  1154. * The identifier for the session associated with the transaction.
  1155. * Only present if the operation is part of a multi-document transaction.
  1156. */
  1157. lsid?: ServerSessionId;
  1158. /**
  1159. * When the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent
  1160. * stage, events larger than 16MB will be split into multiple events and contain the
  1161. * following information about which fragment the current event is.
  1162. */
  1163. splitEvent?: ChangeStreamSplitEvent;
  1164. }
  1165. /** @public */
  1166. export declare interface ChangeStreamDocumentKey<TSchema extends Document = Document> {
  1167. /**
  1168. * For unsharded collections this contains a single field `_id`.
  1169. * For sharded collections, this will contain all the components of the shard key
  1170. */
  1171. documentKey: {
  1172. _id: InferIdType<TSchema>;
  1173. [shardKey: string]: any;
  1174. };
  1175. }
  1176. /** @public */
  1177. export declare interface ChangeStreamDocumentOperationDescription {
  1178. /**
  1179. * An description of the operation.
  1180. *
  1181. * Only present when the `showExpandedEvents` flag is enabled.
  1182. *
  1183. * @sinceServerVersion 6.1.0
  1184. */
  1185. operationDescription?: Document;
  1186. }
  1187. /**
  1188. * @public
  1189. * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event
  1190. */
  1191. export declare interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon {
  1192. /** Describes the type of operation represented in this change notification */
  1193. operationType: 'dropDatabase';
  1194. /** The database dropped */
  1195. ns: {
  1196. db: string;
  1197. };
  1198. }
  1199. /**
  1200. * @public
  1201. * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event
  1202. */
  1203. export declare interface ChangeStreamDropDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
  1204. /** Describes the type of operation represented in this change notification */
  1205. operationType: 'drop';
  1206. /** Namespace the drop event occurred on */
  1207. ns: ChangeStreamNameSpace;
  1208. }
  1209. /**
  1210. * Only present when the `showExpandedEvents` flag is enabled.
  1211. * @public
  1212. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1213. */
  1214. export declare interface ChangeStreamDropIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1215. /** Describes the type of operation represented in this change notification */
  1216. operationType: 'dropIndexes';
  1217. }
  1218. /** @public */
  1219. export declare type ChangeStreamEvents<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> = {
  1220. resumeTokenChanged(token: ResumeToken): void;
  1221. init(response: any): void;
  1222. more(response?: any): void;
  1223. response(): void;
  1224. end(): void;
  1225. error(error: Error): void;
  1226. change(change: TChange): void;
  1227. } & AbstractCursorEvents;
  1228. /**
  1229. * @public
  1230. * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event
  1231. */
  1232. export declare interface ChangeStreamInsertDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID {
  1233. /** Describes the type of operation represented in this change notification */
  1234. operationType: 'insert';
  1235. /** This key will contain the document being inserted */
  1236. fullDocument: TSchema;
  1237. /** Namespace the insert event occurred on */
  1238. ns: ChangeStreamNameSpace;
  1239. }
  1240. /**
  1241. * @public
  1242. * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event
  1243. */
  1244. export declare interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon {
  1245. /** Describes the type of operation represented in this change notification */
  1246. operationType: 'invalidate';
  1247. }
  1248. /** @public */
  1249. export declare interface ChangeStreamNameSpace {
  1250. db: string;
  1251. coll: string;
  1252. }
  1253. /**
  1254. * Options that can be passed to a ChangeStream. Note that startAfter, resumeAfter, and startAtOperationTime are all mutually exclusive, and the server will error if more than one is specified.
  1255. * @public
  1256. */
  1257. export declare interface ChangeStreamOptions extends Omit<AggregateOptions, 'writeConcern'> {
  1258. /**
  1259. * Allowed values: 'updateLookup', 'whenAvailable', 'required'.
  1260. *
  1261. * When set to 'updateLookup', the change notification for partial updates
  1262. * will include both a delta describing the changes to the document as well
  1263. * as a copy of the entire document that was changed from some time after
  1264. * the change occurred.
  1265. *
  1266. * When set to 'whenAvailable', configures the change stream to return the
  1267. * post-image of the modified document for replace and update change events
  1268. * if the post-image for this event is available.
  1269. *
  1270. * When set to 'required', the same behavior as 'whenAvailable' except that
  1271. * an error is raised if the post-image is not available.
  1272. */
  1273. fullDocument?: string;
  1274. /**
  1275. * Allowed values: 'whenAvailable', 'required', 'off'.
  1276. *
  1277. * The default is to not send a value, which is equivalent to 'off'.
  1278. *
  1279. * When set to 'whenAvailable', configures the change stream to return the
  1280. * pre-image of the modified document for replace, update, and delete change
  1281. * events if it is available.
  1282. *
  1283. * When set to 'required', the same behavior as 'whenAvailable' except that
  1284. * an error is raised if the pre-image is not available.
  1285. */
  1286. fullDocumentBeforeChange?: string;
  1287. /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */
  1288. maxAwaitTimeMS?: number;
  1289. /**
  1290. * Allows you to start a changeStream after a specified event.
  1291. * @see https://www.mongodb.com/docs/manual/changeStreams/#resumeafter-for-change-streams
  1292. */
  1293. resumeAfter?: ResumeToken;
  1294. /**
  1295. * Similar to resumeAfter, but will allow you to start after an invalidated event.
  1296. * @see https://www.mongodb.com/docs/manual/changeStreams/#startafter-for-change-streams
  1297. */
  1298. startAfter?: ResumeToken;
  1299. /** Will start the changeStream after the specified operationTime. */
  1300. startAtOperationTime?: OperationTime;
  1301. /**
  1302. * The number of documents to return per batch.
  1303. * @see https://www.mongodb.com/docs/manual/reference/command/aggregate
  1304. */
  1305. batchSize?: number;
  1306. /**
  1307. * When enabled, configures the change stream to include extra change events.
  1308. *
  1309. * - createIndexes
  1310. * - dropIndexes
  1311. * - modify
  1312. * - create
  1313. * - shardCollection
  1314. * - reshardCollection
  1315. * - refineCollectionShardKey
  1316. */
  1317. showExpandedEvents?: boolean;
  1318. }
  1319. /**
  1320. * @public
  1321. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1322. */
  1323. export declare interface ChangeStreamRefineCollectionShardKeyDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1324. /** Describes the type of operation represented in this change notification */
  1325. operationType: 'refineCollectionShardKey';
  1326. }
  1327. /**
  1328. * @public
  1329. * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event
  1330. */
  1331. export declare interface ChangeStreamRenameDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
  1332. /** Describes the type of operation represented in this change notification */
  1333. operationType: 'rename';
  1334. /** The new name for the `ns.coll` collection */
  1335. to: {
  1336. db: string;
  1337. coll: string;
  1338. };
  1339. /** The "from" namespace that the rename occurred on */
  1340. ns: ChangeStreamNameSpace;
  1341. }
  1342. /**
  1343. * @public
  1344. * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event
  1345. */
  1346. export declare interface ChangeStreamReplaceDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema> {
  1347. /** Describes the type of operation represented in this change notification */
  1348. operationType: 'replace';
  1349. /** The fullDocument of a replace event represents the document after the insert of the replacement document */
  1350. fullDocument: TSchema;
  1351. /** Namespace the replace event occurred on */
  1352. ns: ChangeStreamNameSpace;
  1353. /**
  1354. * Contains the pre-image of the modified or deleted document if the
  1355. * pre-image is available for the change event and either 'required' or
  1356. * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
  1357. * when creating the change stream. If 'whenAvailable' was specified but the
  1358. * pre-image is unavailable, this will be explicitly set to null.
  1359. */
  1360. fullDocumentBeforeChange?: TSchema;
  1361. }
  1362. /**
  1363. * @public
  1364. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1365. */
  1366. export declare interface ChangeStreamReshardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1367. /** Describes the type of operation represented in this change notification */
  1368. operationType: 'reshardCollection';
  1369. }
  1370. /**
  1371. * @public
  1372. * @see https://www.mongodb.com/docs/manual/reference/change-events/
  1373. */
  1374. export declare interface ChangeStreamShardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1375. /** Describes the type of operation represented in this change notification */
  1376. operationType: 'shardCollection';
  1377. }
  1378. /** @public */
  1379. export declare interface ChangeStreamSplitEvent {
  1380. /** Which fragment of the change this is. */
  1381. fragment: number;
  1382. /** The total number of fragments. */
  1383. of: number;
  1384. }
  1385. /**
  1386. * @public
  1387. * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event
  1388. */
  1389. export declare interface ChangeStreamUpdateDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID {
  1390. /** Describes the type of operation represented in this change notification */
  1391. operationType: 'update';
  1392. /**
  1393. * This is only set if `fullDocument` is set to `'updateLookup'`
  1394. * Contains the point-in-time post-image of the modified document if the
  1395. * post-image is available and either 'required' or 'whenAvailable' was
  1396. * specified for the 'fullDocument' option when creating the change stream.
  1397. */
  1398. fullDocument?: TSchema;
  1399. /** Contains a description of updated and removed fields in this operation */
  1400. updateDescription: UpdateDescription<TSchema>;
  1401. /** Namespace the update event occurred on */
  1402. ns: ChangeStreamNameSpace;
  1403. /**
  1404. * Contains the pre-image of the modified or deleted document if the
  1405. * pre-image is available for the change event and either 'required' or
  1406. * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
  1407. * when creating the change stream. If 'whenAvailable' was specified but the
  1408. * pre-image is unavailable, this will be explicitly set to null.
  1409. */
  1410. fullDocumentBeforeChange?: TSchema;
  1411. }
  1412. /**
  1413. * @public
  1414. * @see https://github.com/mongodb/specifications/blob/master/source/mongodb-handshake/handshake.rst#hello-command
  1415. */
  1416. export declare interface ClientMetadata {
  1417. driver: {
  1418. name: string;
  1419. version: string;
  1420. };
  1421. os: {
  1422. type: string;
  1423. name?: NodeJS.Platform;
  1424. architecture?: string;
  1425. version?: string;
  1426. };
  1427. platform: string;
  1428. application?: {
  1429. name: string;
  1430. };
  1431. /** FaaS environment information */
  1432. env?: {
  1433. name: 'aws.lambda' | 'gcp.func' | 'azure.func' | 'vercel';
  1434. timeout_sec?: Int32;
  1435. memory_mb?: Int32;
  1436. region?: string;
  1437. url?: string;
  1438. };
  1439. }
  1440. /** @public */
  1441. export declare interface ClientMetadataOptions {
  1442. driverInfo?: {
  1443. name?: string;
  1444. version?: string;
  1445. platform?: string;
  1446. };
  1447. appName?: string;
  1448. }
  1449. /**
  1450. * A class representing a client session on the server
  1451. *
  1452. * NOTE: not meant to be instantiated directly.
  1453. * @public
  1454. */
  1455. export declare class ClientSession extends TypedEventEmitter<ClientSessionEvents> {
  1456. /* Excluded from this release type: client */
  1457. /* Excluded from this release type: sessionPool */
  1458. hasEnded: boolean;
  1459. clientOptions?: MongoOptions;
  1460. supports: {
  1461. causalConsistency: boolean;
  1462. };
  1463. clusterTime?: ClusterTime;
  1464. operationTime?: Timestamp;
  1465. explicit: boolean;
  1466. /* Excluded from this release type: owner */
  1467. defaultTransactionOptions: TransactionOptions;
  1468. transaction: Transaction;
  1469. /* Excluded from this release type: [kServerSession] */
  1470. /* Excluded from this release type: [kSnapshotTime] */
  1471. /* Excluded from this release type: [kSnapshotEnabled] */
  1472. /* Excluded from this release type: [kPinnedConnection] */
  1473. /* Excluded from this release type: [kTxnNumberIncrement] */
  1474. /* Excluded from this release type: __constructor */
  1475. /** The server id associated with this session */
  1476. get id(): ServerSessionId | undefined;
  1477. get serverSession(): ServerSession;
  1478. /** Whether or not this session is configured for snapshot reads */
  1479. get snapshotEnabled(): boolean;
  1480. get loadBalanced(): boolean;
  1481. /* Excluded from this release type: pinnedConnection */
  1482. /* Excluded from this release type: pin */
  1483. /* Excluded from this release type: unpin */
  1484. get isPinned(): boolean;
  1485. /**
  1486. * Ends this session on the server
  1487. *
  1488. * @param options - Optional settings. Currently reserved for future use
  1489. */
  1490. endSession(options?: EndSessionOptions): Promise<void>;
  1491. /**
  1492. * Advances the operationTime for a ClientSession.
  1493. *
  1494. * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
  1495. */
  1496. advanceOperationTime(operationTime: Timestamp): void;
  1497. /**
  1498. * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
  1499. *
  1500. * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature
  1501. */
  1502. advanceClusterTime(clusterTime: ClusterTime): void;
  1503. /**
  1504. * Used to determine if this session equals another
  1505. *
  1506. * @param session - The session to compare to
  1507. */
  1508. equals(session: ClientSession): boolean;
  1509. /**
  1510. * Increment the transaction number on the internal ServerSession
  1511. *
  1512. * @privateRemarks
  1513. * This helper increments a value stored on the client session that will be
  1514. * added to the serverSession's txnNumber upon applying it to a command.
  1515. * This is because the serverSession is lazily acquired after a connection is obtained
  1516. */
  1517. incrementTransactionNumber(): void;
  1518. /** @returns whether this session is currently in a transaction or not */
  1519. inTransaction(): boolean;
  1520. /**
  1521. * Starts a new transaction with the given options.
  1522. *
  1523. * @param options - Options for the transaction
  1524. */
  1525. startTransaction(options?: TransactionOptions): void;
  1526. /**
  1527. * Commits the currently active transaction in this session.
  1528. */
  1529. commitTransaction(): Promise<Document>;
  1530. /**
  1531. * Aborts the currently active transaction in this session.
  1532. */
  1533. abortTransaction(): Promise<Document>;
  1534. /**
  1535. * This is here to ensure that ClientSession is never serialized to BSON.
  1536. */
  1537. toBSON(): never;
  1538. /**
  1539. * Runs a provided callback within a transaction, retrying either the commitTransaction operation
  1540. * or entire transaction as needed (and when the error permits) to better ensure that
  1541. * the transaction can complete successfully.
  1542. *
  1543. * **IMPORTANT:** This method requires the user to return a Promise, and `await` all operations.
  1544. * Any callbacks that do not return a Promise will result in undefined behavior.
  1545. *
  1546. * @remarks
  1547. * This function:
  1548. * - Will return the command response from the final commitTransaction if every operation is successful (can be used as a truthy object)
  1549. * - Will return `undefined` if the transaction is explicitly aborted with `await session.abortTransaction()`
  1550. * - Will throw if one of the operations throws or `throw` statement is used inside the `withTransaction` callback
  1551. *
  1552. * Checkout a descriptive example here:
  1553. * @see https://www.mongodb.com/developer/quickstart/node-transactions/
  1554. *
  1555. * @param fn - callback to run within a transaction
  1556. * @param options - optional settings for the transaction
  1557. * @returns A raw command response or undefined
  1558. */
  1559. withTransaction<T = void>(fn: WithTransactionCallback<T>, options?: TransactionOptions): Promise<Document | undefined>;
  1560. }
  1561. /** @public */
  1562. export declare type ClientSessionEvents = {
  1563. ended(session: ClientSession): void;
  1564. };
  1565. /** @public */
  1566. export declare interface ClientSessionOptions {
  1567. /** Whether causal consistency should be enabled on this session */
  1568. causalConsistency?: boolean;
  1569. /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */
  1570. snapshot?: boolean;
  1571. /** The default TransactionOptions to use for transactions started on this session. */
  1572. defaultTransactionOptions?: TransactionOptions;
  1573. /* Excluded from this release type: owner */
  1574. /* Excluded from this release type: explicit */
  1575. /* Excluded from this release type: initialClusterTime */
  1576. }
  1577. /** @public */
  1578. export declare interface CloseOptions {
  1579. force?: boolean;
  1580. }
  1581. /** @public
  1582. * Configuration options for clustered collections
  1583. * @see https://www.mongodb.com/docs/manual/core/clustered-collections/
  1584. */
  1585. export declare interface ClusteredCollectionOptions extends Document {
  1586. name?: string;
  1587. key: Document;
  1588. unique: boolean;
  1589. }
  1590. /** @public */
  1591. export declare interface ClusterTime {
  1592. clusterTime: Timestamp;
  1593. signature: {
  1594. hash: Binary;
  1595. keyId: Long;
  1596. };
  1597. }
  1598. export { Code }
  1599. /** @public */
  1600. export declare interface CollationOptions {
  1601. locale: string;
  1602. caseLevel?: boolean;
  1603. caseFirst?: string;
  1604. strength?: number;
  1605. numericOrdering?: boolean;
  1606. alternate?: string;
  1607. maxVariable?: string;
  1608. backwards?: boolean;
  1609. normalization?: boolean;
  1610. }
  1611. /**
  1612. * The **Collection** class is an internal class that embodies a MongoDB collection
  1613. * allowing for insert/find/update/delete and other command operation on that MongoDB collection.
  1614. *
  1615. * **COLLECTION Cannot directly be instantiated**
  1616. * @public
  1617. *
  1618. * @example
  1619. * ```ts
  1620. * import { MongoClient } from 'mongodb';
  1621. *
  1622. * interface Pet {
  1623. * name: string;
  1624. * kind: 'dog' | 'cat' | 'fish';
  1625. * }
  1626. *
  1627. * const client = new MongoClient('mongodb://localhost:27017');
  1628. * const pets = client.db().collection<Pet>('pets');
  1629. *
  1630. * const petCursor = pets.find();
  1631. *
  1632. * for await (const pet of petCursor) {
  1633. * console.log(`${pet.name} is a ${pet.kind}!`);
  1634. * }
  1635. * ```
  1636. */
  1637. export declare class Collection<TSchema extends Document = Document> {
  1638. /* Excluded from this release type: s */
  1639. /* Excluded from this release type: client */
  1640. /* Excluded from this release type: __constructor */
  1641. /**
  1642. * The name of the database this collection belongs to
  1643. */
  1644. get dbName(): string;
  1645. /**
  1646. * The name of this collection
  1647. */
  1648. get collectionName(): string;
  1649. /**
  1650. * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
  1651. */
  1652. get namespace(): string;
  1653. /* Excluded from this release type: fullNamespace */
  1654. /**
  1655. * The current readConcern of the collection. If not explicitly defined for
  1656. * this collection, will be inherited from the parent DB
  1657. */
  1658. get readConcern(): ReadConcern | undefined;
  1659. /**
  1660. * The current readPreference of the collection. If not explicitly defined for
  1661. * this collection, will be inherited from the parent DB
  1662. */
  1663. get readPreference(): ReadPreference | undefined;
  1664. get bsonOptions(): BSONSerializeOptions;
  1665. /**
  1666. * The current writeConcern of the collection. If not explicitly defined for
  1667. * this collection, will be inherited from the parent DB
  1668. */
  1669. get writeConcern(): WriteConcern | undefined;
  1670. /** The current index hint for the collection */
  1671. get hint(): Hint | undefined;
  1672. set hint(v: Hint | undefined);
  1673. /**
  1674. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  1675. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  1676. * can be overridden by setting the **forceServerObjectId** flag.
  1677. *
  1678. * @param doc - The document to insert
  1679. * @param options - Optional settings for the command
  1680. */
  1681. insertOne(doc: OptionalUnlessRequiredId<TSchema>, options?: InsertOneOptions): Promise<InsertOneResult<TSchema>>;
  1682. /**
  1683. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  1684. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  1685. * can be overridden by setting the **forceServerObjectId** flag.
  1686. *
  1687. * @param docs - The documents to insert
  1688. * @param options - Optional settings for the command
  1689. */
  1690. insertMany(docs: OptionalUnlessRequiredId<TSchema>[], options?: BulkWriteOptions): Promise<InsertManyResult<TSchema>>;
  1691. /**
  1692. * Perform a bulkWrite operation without a fluent API
  1693. *
  1694. * Legal operation types are
  1695. * - `insertOne`
  1696. * - `replaceOne`
  1697. * - `updateOne`
  1698. * - `updateMany`
  1699. * - `deleteOne`
  1700. * - `deleteMany`
  1701. *
  1702. * If documents passed in do not contain the **_id** field,
  1703. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  1704. * can be overridden by setting the **forceServerObjectId** flag.
  1705. *
  1706. * @param operations - Bulk operations to perform
  1707. * @param options - Optional settings for the command
  1708. * @throws MongoDriverError if operations is not an array
  1709. */
  1710. bulkWrite(operations: AnyBulkWriteOperation<TSchema>[], options?: BulkWriteOptions): Promise<BulkWriteResult>;
  1711. /**
  1712. * Update a single document in a collection
  1713. *
  1714. * @param filter - The filter used to select the document to update
  1715. * @param update - The update operations to be applied to the document
  1716. * @param options - Optional settings for the command
  1717. */
  1718. updateOne(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Partial<TSchema>, options?: UpdateOptions): Promise<UpdateResult<TSchema>>;
  1719. /**
  1720. * Replace a document in a collection with another document
  1721. *
  1722. * @param filter - The filter used to select the document to replace
  1723. * @param replacement - The Document that replaces the matching document
  1724. * @param options - Optional settings for the command
  1725. */
  1726. replaceOne(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options?: ReplaceOptions): Promise<UpdateResult<TSchema> | Document>;
  1727. /**
  1728. * Update multiple documents in a collection
  1729. *
  1730. * @param filter - The filter used to select the documents to update
  1731. * @param update - The update operations to be applied to the documents
  1732. * @param options - Optional settings for the command
  1733. */
  1734. updateMany(filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options?: UpdateOptions): Promise<UpdateResult<TSchema>>;
  1735. /**
  1736. * Delete a document from a collection
  1737. *
  1738. * @param filter - The filter used to select the document to remove
  1739. * @param options - Optional settings for the command
  1740. */
  1741. deleteOne(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>;
  1742. /**
  1743. * Delete multiple documents from a collection
  1744. *
  1745. * @param filter - The filter used to select the documents to remove
  1746. * @param options - Optional settings for the command
  1747. */
  1748. deleteMany(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>;
  1749. /**
  1750. * Rename the collection.
  1751. *
  1752. * @remarks
  1753. * This operation does not inherit options from the Db or MongoClient.
  1754. *
  1755. * @param newName - New name of of the collection.
  1756. * @param options - Optional settings for the command
  1757. */
  1758. rename(newName: string, options?: RenameOptions): Promise<Collection>;
  1759. /**
  1760. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  1761. *
  1762. * @param options - Optional settings for the command
  1763. */
  1764. drop(options?: DropCollectionOptions): Promise<boolean>;
  1765. /**
  1766. * Fetches the first document that matches the filter
  1767. *
  1768. * @param filter - Query for find Operation
  1769. * @param options - Optional settings for the command
  1770. */
  1771. findOne(): Promise<WithId<TSchema> | null>;
  1772. findOne(filter: Filter<TSchema>): Promise<WithId<TSchema> | null>;
  1773. findOne(filter: Filter<TSchema>, options: FindOptions): Promise<WithId<TSchema> | null>;
  1774. findOne<T = TSchema>(): Promise<T | null>;
  1775. findOne<T = TSchema>(filter: Filter<TSchema>): Promise<T | null>;
  1776. findOne<T = TSchema>(filter: Filter<TSchema>, options?: FindOptions): Promise<T | null>;
  1777. /**
  1778. * Creates a cursor for a filter that can be used to iterate over results from MongoDB
  1779. *
  1780. * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate
  1781. */
  1782. find(): FindCursor<WithId<TSchema>>;
  1783. find(filter: Filter<TSchema>, options?: FindOptions): FindCursor<WithId<TSchema>>;
  1784. find<T extends Document>(filter: Filter<TSchema>, options?: FindOptions): FindCursor<T>;
  1785. /**
  1786. * Returns the options of the collection.
  1787. *
  1788. * @param options - Optional settings for the command
  1789. */
  1790. options(options?: OperationOptions): Promise<Document>;
  1791. /**
  1792. * Returns if the collection is a capped collection
  1793. *
  1794. * @param options - Optional settings for the command
  1795. */
  1796. isCapped(options?: OperationOptions): Promise<boolean>;
  1797. /**
  1798. * Creates an index on the db and collection collection.
  1799. *
  1800. * @param indexSpec - The field name or index specification to create an index for
  1801. * @param options - Optional settings for the command
  1802. *
  1803. * @example
  1804. * ```ts
  1805. * const collection = client.db('foo').collection('bar');
  1806. *
  1807. * await collection.createIndex({ a: 1, b: -1 });
  1808. *
  1809. * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
  1810. * await collection.createIndex([ [c, 1], [d, -1] ]);
  1811. *
  1812. * // Equivalent to { e: 1 }
  1813. * await collection.createIndex('e');
  1814. *
  1815. * // Equivalent to { f: 1, g: 1 }
  1816. * await collection.createIndex(['f', 'g'])
  1817. *
  1818. * // Equivalent to { h: 1, i: -1 }
  1819. * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
  1820. *
  1821. * // Equivalent to { j: 1, k: -1, l: 2d }
  1822. * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
  1823. * ```
  1824. */
  1825. createIndex(indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
  1826. /**
  1827. * Creates multiple indexes in the collection, this method is only supported for
  1828. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  1829. * error.
  1830. *
  1831. * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications.
  1832. * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}.
  1833. *
  1834. * @param indexSpecs - An array of index specifications to be created
  1835. * @param options - Optional settings for the command
  1836. *
  1837. * @example
  1838. * ```ts
  1839. * const collection = client.db('foo').collection('bar');
  1840. * await collection.createIndexes([
  1841. * // Simple index on field fizz
  1842. * {
  1843. * key: { fizz: 1 },
  1844. * }
  1845. * // wildcard index
  1846. * {
  1847. * key: { '$**': 1 }
  1848. * },
  1849. * // named index on darmok and jalad
  1850. * {
  1851. * key: { darmok: 1, jalad: -1 }
  1852. * name: 'tanagra'
  1853. * }
  1854. * ]);
  1855. * ```
  1856. */
  1857. createIndexes(indexSpecs: IndexDescription[], options?: CreateIndexesOptions): Promise<string[]>;
  1858. /**
  1859. * Drops an index from this collection.
  1860. *
  1861. * @param indexName - Name of the index to drop.
  1862. * @param options - Optional settings for the command
  1863. */
  1864. dropIndex(indexName: string, options?: DropIndexesOptions): Promise<Document>;
  1865. /**
  1866. * Drops all indexes from this collection.
  1867. *
  1868. * @param options - Optional settings for the command
  1869. */
  1870. dropIndexes(options?: DropIndexesOptions): Promise<Document>;
  1871. /**
  1872. * Get the list of all indexes information for the collection.
  1873. *
  1874. * @param options - Optional settings for the command
  1875. */
  1876. listIndexes(options?: ListIndexesOptions): ListIndexesCursor;
  1877. /**
  1878. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  1879. *
  1880. * @param indexes - One or more index names to check.
  1881. * @param options - Optional settings for the command
  1882. */
  1883. indexExists(indexes: string | string[], options?: IndexInformationOptions): Promise<boolean>;
  1884. /**
  1885. * Retrieves this collections index info.
  1886. *
  1887. * @param options - Optional settings for the command
  1888. */
  1889. indexInformation(options?: IndexInformationOptions): Promise<Document>;
  1890. /**
  1891. * Gets an estimate of the count of documents in a collection using collection metadata.
  1892. * This will always run a count command on all server versions.
  1893. *
  1894. * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command,
  1895. * which estimatedDocumentCount uses in its implementation, was not included in v1 of
  1896. * the Stable API, and so users of the Stable API with estimatedDocumentCount are
  1897. * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid
  1898. * encountering errors.
  1899. *
  1900. * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior}
  1901. * @param options - Optional settings for the command
  1902. */
  1903. estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise<number>;
  1904. /**
  1905. * Gets the number of documents matching the filter.
  1906. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  1907. * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments}
  1908. * the following query operators must be replaced:
  1909. *
  1910. * | Operator | Replacement |
  1911. * | -------- | ----------- |
  1912. * | `$where` | [`$expr`][1] |
  1913. * | `$near` | [`$geoWithin`][2] with [`$center`][3] |
  1914. * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
  1915. *
  1916. * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  1917. * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  1918. * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  1919. * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  1920. *
  1921. * @param filter - The filter for the count
  1922. * @param options - Optional settings for the command
  1923. *
  1924. * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  1925. * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  1926. * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  1927. * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  1928. */
  1929. countDocuments(filter?: Document, options?: CountDocumentsOptions): Promise<number>;
  1930. /**
  1931. * The distinct command returns a list of distinct values for the given key across a collection.
  1932. *
  1933. * @param key - Field of the document to find distinct values for
  1934. * @param filter - The filter for filtering the set of documents to which we apply the distinct filter.
  1935. * @param options - Optional settings for the command
  1936. */
  1937. distinct<Key extends keyof WithId<TSchema>>(key: Key): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
  1938. distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
  1939. distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>, options: DistinctOptions): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
  1940. distinct(key: string): Promise<any[]>;
  1941. distinct(key: string, filter: Filter<TSchema>): Promise<any[]>;
  1942. distinct(key: string, filter: Filter<TSchema>, options: DistinctOptions): Promise<any[]>;
  1943. /**
  1944. * Retrieve all the indexes on the collection.
  1945. *
  1946. * @param options - Optional settings for the command
  1947. */
  1948. indexes(options?: IndexInformationOptions): Promise<Document[]>;
  1949. /**
  1950. * Get all the collection statistics.
  1951. *
  1952. * @deprecated the `collStats` operation will be removed in the next major release. Please
  1953. * use an aggregation pipeline with the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) stage instead
  1954. *
  1955. * @param options - Optional settings for the command
  1956. */
  1957. stats(options?: CollStatsOptions): Promise<CollStats>;
  1958. /**
  1959. * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
  1960. *
  1961. * @param filter - The filter used to select the document to remove
  1962. * @param options - Optional settings for the command
  1963. */
  1964. findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions & {
  1965. includeResultMetadata: true;
  1966. }): Promise<ModifyResult<TSchema>>;
  1967. findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions & {
  1968. includeResultMetadata: false;
  1969. }): Promise<WithId<TSchema> | null>;
  1970. findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions): Promise<ModifyResult<TSchema>>;
  1971. findOneAndDelete(filter: Filter<TSchema>): Promise<ModifyResult<TSchema>>;
  1972. /**
  1973. * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
  1974. *
  1975. * @param filter - The filter used to select the document to replace
  1976. * @param replacement - The Document that replaces the matching document
  1977. * @param options - Optional settings for the command
  1978. */
  1979. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions & {
  1980. includeResultMetadata: true;
  1981. }): Promise<ModifyResult<TSchema>>;
  1982. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions & {
  1983. includeResultMetadata: false;
  1984. }): Promise<WithId<TSchema> | null>;
  1985. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions): Promise<ModifyResult<TSchema>>;
  1986. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>): Promise<ModifyResult<TSchema>>;
  1987. /**
  1988. * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
  1989. *
  1990. * @param filter - The filter used to select the document to update
  1991. * @param update - Update operations to be performed on the document
  1992. * @param options - Optional settings for the command
  1993. */
  1994. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options: FindOneAndUpdateOptions & {
  1995. includeResultMetadata: true;
  1996. }): Promise<ModifyResult<TSchema>>;
  1997. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options: FindOneAndUpdateOptions & {
  1998. includeResultMetadata: false;
  1999. }): Promise<WithId<TSchema> | null>;
  2000. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options: FindOneAndUpdateOptions): Promise<ModifyResult<TSchema>>;
  2001. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema>): Promise<ModifyResult<TSchema>>;
  2002. /**
  2003. * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2
  2004. *
  2005. * @param pipeline - An array of aggregation pipelines to execute
  2006. * @param options - Optional settings for the command
  2007. */
  2008. aggregate<T extends Document = Document>(pipeline?: Document[], options?: AggregateOptions): AggregationCursor<T>;
  2009. /**
  2010. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
  2011. *
  2012. * @remarks
  2013. * watch() accepts two generic arguments for distinct use cases:
  2014. * - The first is to override the schema that may be defined for this specific collection
  2015. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  2016. * @example
  2017. * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>`
  2018. * ```ts
  2019. * collection.watch<{ _id: number }>()
  2020. * .on('change', change => console.log(change._id.toFixed(4)));
  2021. * ```
  2022. *
  2023. * @example
  2024. * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline.
  2025. * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment.
  2026. * No need start from scratch on the ChangeStreamInsertDocument type!
  2027. * By using an intersection we can save time and ensure defaults remain the same type!
  2028. * ```ts
  2029. * collection
  2030. * .watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([
  2031. * { $addFields: { comment: 'big changes' } },
  2032. * { $match: { operationType: 'insert' } }
  2033. * ])
  2034. * .on('change', change => {
  2035. * change.comment.startsWith('big');
  2036. * change.operationType === 'insert';
  2037. * // No need to narrow in code because the generics did that for us!
  2038. * expectType<Schema>(change.fullDocument);
  2039. * });
  2040. * ```
  2041. *
  2042. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  2043. * @param options - Optional settings for the command
  2044. * @typeParam TLocal - Type of the data being detected by the change stream
  2045. * @typeParam TChange - Type of the whole change stream document emitted
  2046. */
  2047. watch<TLocal extends Document = TSchema, TChange extends Document = ChangeStreamDocument<TLocal>>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream<TLocal, TChange>;
  2048. /**
  2049. * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  2050. *
  2051. * @throws MongoNotConnectedError
  2052. * @remarks
  2053. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  2054. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  2055. */
  2056. initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation;
  2057. /**
  2058. * Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.
  2059. *
  2060. * @throws MongoNotConnectedError
  2061. * @remarks
  2062. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  2063. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  2064. */
  2065. initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation;
  2066. /**
  2067. * An estimated count of matching documents in the db to a filter.
  2068. *
  2069. * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
  2070. * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}.
  2071. * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  2072. *
  2073. * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead
  2074. *
  2075. * @param filter - The filter for the count.
  2076. * @param options - Optional settings for the command
  2077. */
  2078. count(filter?: Filter<TSchema>, options?: CountOptions): Promise<number>;
  2079. /**
  2080. * Returns all search indexes for the current collection.
  2081. *
  2082. * @param options - The options for the list indexes operation.
  2083. *
  2084. * @remarks Only available when used against a 7.0+ Atlas cluster.
  2085. */
  2086. listSearchIndexes(options?: ListSearchIndexesOptions): ListSearchIndexesCursor;
  2087. /**
  2088. * Returns all search indexes for the current collection.
  2089. *
  2090. * @param name - The name of the index to search for. Only indexes with matching index names will be returned.
  2091. * @param options - The options for the list indexes operation.
  2092. *
  2093. * @remarks Only available when used against a 7.0+ Atlas cluster.
  2094. */
  2095. listSearchIndexes(name: string, options?: ListSearchIndexesOptions): ListSearchIndexesCursor;
  2096. /**
  2097. * Creates a single search index for the collection.
  2098. *
  2099. * @param description - The index description for the new search index.
  2100. * @returns A promise that resolves to the name of the new search index.
  2101. *
  2102. * @remarks Only available when used against a 7.0+ Atlas cluster.
  2103. */
  2104. createSearchIndex(description: SearchIndexDescription): Promise<string>;
  2105. /**
  2106. * Creates multiple search indexes for the current collection.
  2107. *
  2108. * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes.
  2109. * @returns A promise that resolves to an array of the newly created search index names.
  2110. *
  2111. * @remarks Only available when used against a 7.0+ Atlas cluster.
  2112. * @returns
  2113. */
  2114. createSearchIndexes(descriptions: SearchIndexDescription[]): Promise<string[]>;
  2115. /**
  2116. * Deletes a search index by index name.
  2117. *
  2118. * @param name - The name of the search index to be deleted.
  2119. *
  2120. * @remarks Only available when used against a 7.0+ Atlas cluster.
  2121. */
  2122. dropSearchIndex(name: string): Promise<void>;
  2123. /**
  2124. * Updates a search index by replacing the existing index definition with the provided definition.
  2125. *
  2126. * @param name - The name of the search index to update.
  2127. * @param definition - The new search index definition.
  2128. *
  2129. * @remarks Only available when used against a 7.0+ Atlas cluster.
  2130. */
  2131. updateSearchIndex(name: string, definition: Document): Promise<void>;
  2132. }
  2133. /** @public */
  2134. export declare interface CollectionInfo extends Document {
  2135. name: string;
  2136. type?: string;
  2137. options?: Document;
  2138. info?: {
  2139. readOnly?: false;
  2140. uuid?: Binary;
  2141. };
  2142. idIndex?: Document;
  2143. }
  2144. /** @public */
  2145. export declare interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions {
  2146. /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */
  2147. readConcern?: ReadConcernLike;
  2148. /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */
  2149. readPreference?: ReadPreferenceLike;
  2150. }
  2151. /* Excluded from this release type: CollectionPrivate */
  2152. /**
  2153. * @deprecated the `collStats` operation will be removed in the next major release. Please
  2154. * use an aggregation pipeline with the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) stage instead
  2155. * @public
  2156. * @see https://www.mongodb.com/docs/manual/reference/command/collStats/
  2157. */
  2158. export declare interface CollStats extends Document {
  2159. /** Namespace */
  2160. ns: string;
  2161. /** Number of documents */
  2162. count: number;
  2163. /** Collection size in bytes */
  2164. size: number;
  2165. /** Average object size in bytes */
  2166. avgObjSize: number;
  2167. /** (Pre)allocated space for the collection in bytes */
  2168. storageSize: number;
  2169. /** Number of extents (contiguously allocated chunks of datafile space) */
  2170. numExtents: number;
  2171. /** Number of indexes */
  2172. nindexes: number;
  2173. /** Size of the most recently created extent in bytes */
  2174. lastExtentSize: number;
  2175. /** Padding can speed up updates if documents grow */
  2176. paddingFactor: number;
  2177. /** A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine */
  2178. userFlags?: number;
  2179. /** Total index size in bytes */
  2180. totalIndexSize: number;
  2181. /** Size of specific indexes in bytes */
  2182. indexSizes: {
  2183. _id_: number;
  2184. [index: string]: number;
  2185. };
  2186. /** `true` if the collection is capped */
  2187. capped: boolean;
  2188. /** The maximum number of documents that may be present in a capped collection */
  2189. max: number;
  2190. /** The maximum size of a capped collection */
  2191. maxSize: number;
  2192. /** This document contains data reported directly by the WiredTiger engine and other data for internal diagnostic use */
  2193. wiredTiger?: WiredTigerData;
  2194. /** The fields in this document are the names of the indexes, while the values themselves are documents that contain statistics for the index provided by the storage engine */
  2195. indexDetails?: any;
  2196. ok: number;
  2197. /** The amount of storage available for reuse. The scale argument affects this value. */
  2198. freeStorageSize?: number;
  2199. /** An array that contains the names of the indexes that are currently being built on the collection */
  2200. indexBuilds?: number;
  2201. /** The sum of the storageSize and totalIndexSize. The scale argument affects this value */
  2202. totalSize: number;
  2203. /** The scale value used by the command. */
  2204. scaleFactor: number;
  2205. }
  2206. /**
  2207. * @public
  2208. * @deprecated the `collStats` operation will be removed in the next major release. Please
  2209. * use an aggregation pipeline with the [`$collStats`](https://www.mongodb.com/docs/manual/reference/operator/aggregation/collStats/) stage instead
  2210. */
  2211. export declare interface CollStatsOptions extends CommandOperationOptions {
  2212. /** Divide the returned sizes by scale value. */
  2213. scale?: number;
  2214. }
  2215. /* Excluded from this release type: CommandCallbackOperation */
  2216. /**
  2217. * An event indicating the failure of a given command
  2218. * @public
  2219. * @category Event
  2220. */
  2221. export declare class CommandFailedEvent {
  2222. address: string;
  2223. connectionId?: string | number;
  2224. requestId: number;
  2225. duration: number;
  2226. commandName: string;
  2227. failure: Error;
  2228. serviceId?: ObjectId;
  2229. /* Excluded from this release type: name */
  2230. /* Excluded from this release type: __constructor */
  2231. get hasServiceId(): boolean;
  2232. }
  2233. /* Excluded from this release type: CommandOperation */
  2234. /** @public */
  2235. export declare interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions {
  2236. /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */
  2237. readConcern?: ReadConcernLike;
  2238. /** Collation */
  2239. collation?: CollationOptions;
  2240. maxTimeMS?: number;
  2241. /**
  2242. * Comment to apply to the operation.
  2243. *
  2244. * In server versions pre-4.4, 'comment' must be string. A server
  2245. * error will be thrown if any other type is provided.
  2246. *
  2247. * In server versions 4.4 and above, 'comment' can be any valid BSON type.
  2248. */
  2249. comment?: unknown;
  2250. /** Should retry failed writes */
  2251. retryWrites?: boolean;
  2252. dbName?: string;
  2253. authdb?: string;
  2254. noResponse?: boolean;
  2255. }
  2256. /* Excluded from this release type: CommandOptions */
  2257. /**
  2258. * An event indicating the start of a given command
  2259. * @public
  2260. * @category Event
  2261. */
  2262. export declare class CommandStartedEvent {
  2263. commandObj?: Document;
  2264. requestId: number;
  2265. databaseName: string;
  2266. commandName: string;
  2267. command: Document;
  2268. address: string;
  2269. connectionId?: string | number;
  2270. serviceId?: ObjectId;
  2271. /* Excluded from this release type: name */
  2272. /* Excluded from this release type: __constructor */
  2273. get hasServiceId(): boolean;
  2274. }
  2275. /**
  2276. * An event indicating the success of a given command
  2277. * @public
  2278. * @category Event
  2279. */
  2280. export declare class CommandSucceededEvent {
  2281. address: string;
  2282. connectionId?: string | number;
  2283. requestId: number;
  2284. duration: number;
  2285. commandName: string;
  2286. reply: unknown;
  2287. serviceId?: ObjectId;
  2288. /* Excluded from this release type: name */
  2289. /* Excluded from this release type: __constructor */
  2290. get hasServiceId(): boolean;
  2291. }
  2292. /** @public */
  2293. export declare type CommonEvents = 'newListener' | 'removeListener';
  2294. /** @public */
  2295. export declare const Compressor: Readonly<{
  2296. readonly none: 0;
  2297. readonly snappy: 1;
  2298. readonly zlib: 2;
  2299. readonly zstd: 3;
  2300. }>;
  2301. /** @public */
  2302. export declare type Compressor = (typeof Compressor)[CompressorName];
  2303. /** @public */
  2304. export declare type CompressorName = keyof typeof Compressor;
  2305. /** @public */
  2306. export declare type Condition<T> = AlternativeType<T> | FilterOperators<AlternativeType<T>>;
  2307. /* Excluded from this release type: Connection */
  2308. /* Excluded from this release type: CONNECTION_CHECK_OUT_FAILED */
  2309. /* Excluded from this release type: CONNECTION_CHECK_OUT_STARTED */
  2310. /* Excluded from this release type: CONNECTION_CHECKED_IN */
  2311. /* Excluded from this release type: CONNECTION_CHECKED_OUT */
  2312. /* Excluded from this release type: CONNECTION_CLOSED */
  2313. /* Excluded from this release type: CONNECTION_CREATED */
  2314. /* Excluded from this release type: CONNECTION_POOL_CLEARED */
  2315. /* Excluded from this release type: CONNECTION_POOL_CLOSED */
  2316. /* Excluded from this release type: CONNECTION_POOL_CREATED */
  2317. /* Excluded from this release type: CONNECTION_POOL_READY */
  2318. /* Excluded from this release type: CONNECTION_READY */
  2319. /**
  2320. * An event published when a connection is checked into the connection pool
  2321. * @public
  2322. * @category Event
  2323. */
  2324. export declare class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {
  2325. /** The id of the connection */
  2326. connectionId: number | '<monitor>';
  2327. /* Excluded from this release type: name */
  2328. /* Excluded from this release type: __constructor */
  2329. }
  2330. /**
  2331. * An event published when a connection is checked out of the connection pool
  2332. * @public
  2333. * @category Event
  2334. */
  2335. export declare class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {
  2336. /** The id of the connection */
  2337. connectionId: number | '<monitor>';
  2338. /* Excluded from this release type: name */
  2339. /* Excluded from this release type: __constructor */
  2340. }
  2341. /**
  2342. * An event published when a request to check a connection out fails
  2343. * @public
  2344. * @category Event
  2345. */
  2346. export declare class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {
  2347. /** The reason the attempt to check out failed */
  2348. reason: string;
  2349. /* Excluded from this release type: error */
  2350. /* Excluded from this release type: name */
  2351. /* Excluded from this release type: __constructor */
  2352. }
  2353. /**
  2354. * An event published when a request to check a connection out begins
  2355. * @public
  2356. * @category Event
  2357. */
  2358. export declare class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {
  2359. /* Excluded from this release type: name */
  2360. /* Excluded from this release type: __constructor */
  2361. }
  2362. /**
  2363. * An event published when a connection is closed
  2364. * @public
  2365. * @category Event
  2366. */
  2367. export declare class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {
  2368. /** The id of the connection */
  2369. connectionId: number | '<monitor>';
  2370. /** The reason the connection was closed */
  2371. reason: string;
  2372. serviceId?: ObjectId;
  2373. /* Excluded from this release type: name */
  2374. /* Excluded from this release type: error */
  2375. /* Excluded from this release type: __constructor */
  2376. }
  2377. /**
  2378. * An event published when a connection pool creates a new connection
  2379. * @public
  2380. * @category Event
  2381. */
  2382. export declare class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {
  2383. /** A monotonically increasing, per-pool id for the newly created connection */
  2384. connectionId: number | '<monitor>';
  2385. /* Excluded from this release type: name */
  2386. /* Excluded from this release type: __constructor */
  2387. }
  2388. /** @public */
  2389. export declare type ConnectionEvents = {
  2390. commandStarted(event: CommandStartedEvent): void;
  2391. commandSucceeded(event: CommandSucceededEvent): void;
  2392. commandFailed(event: CommandFailedEvent): void;
  2393. clusterTimeReceived(clusterTime: Document): void;
  2394. close(): void;
  2395. message(message: any): void;
  2396. pinned(pinType: string): void;
  2397. unpinned(pinType: string): void;
  2398. };
  2399. /** @public */
  2400. export declare interface ConnectionOptions extends SupportedNodeConnectionOptions, StreamDescriptionOptions, ProxyOptions {
  2401. id: number | '<monitor>';
  2402. generation: number;
  2403. hostAddress: HostAddress;
  2404. autoEncrypter?: AutoEncrypter;
  2405. serverApi?: ServerApi;
  2406. monitorCommands: boolean;
  2407. /* Excluded from this release type: connectionType */
  2408. credentials?: MongoCredentials;
  2409. connectTimeoutMS?: number;
  2410. tls: boolean;
  2411. /** @deprecated - Will not be able to turn off in the future. */
  2412. keepAlive?: boolean;
  2413. /** @deprecated - Will not be configurable in the future. */
  2414. keepAliveInitialDelay?: number;
  2415. noDelay?: boolean;
  2416. socketTimeoutMS?: number;
  2417. cancellationToken?: CancellationToken;
  2418. metadata: ClientMetadata;
  2419. }
  2420. /* Excluded from this release type: ConnectionPool */
  2421. /**
  2422. * An event published when a connection pool is cleared
  2423. * @public
  2424. * @category Event
  2425. */
  2426. export declare class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {
  2427. /* Excluded from this release type: serviceId */
  2428. interruptInUseConnections?: boolean;
  2429. /* Excluded from this release type: name */
  2430. /* Excluded from this release type: __constructor */
  2431. }
  2432. /**
  2433. * An event published when a connection pool is closed
  2434. * @public
  2435. * @category Event
  2436. */
  2437. export declare class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {
  2438. /* Excluded from this release type: name */
  2439. /* Excluded from this release type: __constructor */
  2440. }
  2441. /**
  2442. * An event published when a connection pool is created
  2443. * @public
  2444. * @category Event
  2445. */
  2446. export declare class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {
  2447. /** The options used to create this connection pool */
  2448. options: Omit<ConnectionPoolOptions, 'credentials'> & {
  2449. credentials?: Record<never, never>;
  2450. };
  2451. /* Excluded from this release type: name */
  2452. /* Excluded from this release type: __constructor */
  2453. }
  2454. /** @public */
  2455. export declare type ConnectionPoolEvents = {
  2456. connectionPoolCreated(event: ConnectionPoolCreatedEvent): void;
  2457. connectionPoolReady(event: ConnectionPoolReadyEvent): void;
  2458. connectionPoolClosed(event: ConnectionPoolClosedEvent): void;
  2459. connectionPoolCleared(event: ConnectionPoolClearedEvent): void;
  2460. connectionCreated(event: ConnectionCreatedEvent): void;
  2461. connectionReady(event: ConnectionReadyEvent): void;
  2462. connectionClosed(event: ConnectionClosedEvent): void;
  2463. connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void;
  2464. connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void;
  2465. connectionCheckedOut(event: ConnectionCheckedOutEvent): void;
  2466. connectionCheckedIn(event: ConnectionCheckedInEvent): void;
  2467. } & Omit<ConnectionEvents, 'close' | 'message'>;
  2468. /* Excluded from this release type: ConnectionPoolMetrics */
  2469. /**
  2470. * The base export class for all monitoring events published from the connection pool
  2471. * @public
  2472. * @category Event
  2473. */
  2474. export declare abstract class ConnectionPoolMonitoringEvent {
  2475. /** A timestamp when the event was created */
  2476. time: Date;
  2477. /** The address (host/port pair) of the pool */
  2478. address: string;
  2479. /* Excluded from this release type: name */
  2480. /* Excluded from this release type: __constructor */
  2481. }
  2482. /** @public */
  2483. export declare interface ConnectionPoolOptions extends Omit<ConnectionOptions, 'id' | 'generation'> {
  2484. /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */
  2485. maxPoolSize: number;
  2486. /** The minimum number of connections that MUST exist at any moment in a single connection pool. */
  2487. minPoolSize: number;
  2488. /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
  2489. maxConnecting: number;
  2490. /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */
  2491. maxIdleTimeMS: number;
  2492. /** The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit. */
  2493. waitQueueTimeoutMS: number;
  2494. /** If we are in load balancer mode. */
  2495. loadBalanced: boolean;
  2496. /* Excluded from this release type: minPoolSizeCheckFrequencyMS */
  2497. }
  2498. /**
  2499. * An event published when a connection pool is ready
  2500. * @public
  2501. * @category Event
  2502. */
  2503. export declare class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent {
  2504. /* Excluded from this release type: name */
  2505. /* Excluded from this release type: __constructor */
  2506. }
  2507. /**
  2508. * An event published when a connection is ready for use
  2509. * @public
  2510. * @category Event
  2511. */
  2512. export declare class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {
  2513. /** The id of the connection */
  2514. connectionId: number | '<monitor>';
  2515. /* Excluded from this release type: name */
  2516. /* Excluded from this release type: __constructor */
  2517. }
  2518. /** @public */
  2519. export declare interface ConnectOptions {
  2520. readPreference?: ReadPreference;
  2521. }
  2522. /** @public */
  2523. export declare interface CountDocumentsOptions extends AggregateOptions {
  2524. /** The number of documents to skip. */
  2525. skip?: number;
  2526. /** The maximum amounts to count before aborting. */
  2527. limit?: number;
  2528. }
  2529. /** @public */
  2530. export declare interface CountOptions extends CommandOperationOptions {
  2531. /** The number of documents to skip. */
  2532. skip?: number;
  2533. /** The maximum amounts to count before aborting. */
  2534. limit?: number;
  2535. /** Number of milliseconds to wait before aborting the query. */
  2536. maxTimeMS?: number;
  2537. /** An index name hint for the query. */
  2538. hint?: string | Document;
  2539. }
  2540. /** @public */
  2541. export declare interface CreateCollectionOptions extends CommandOperationOptions {
  2542. /** Create a capped collection */
  2543. capped?: boolean;
  2544. /** @deprecated Create an index on the _id field of the document. This option is deprecated in MongoDB 3.2+ and will be removed once no longer supported by the server. */
  2545. autoIndexId?: boolean;
  2546. /** The size of the capped collection in bytes */
  2547. size?: number;
  2548. /** The maximum number of documents in the capped collection */
  2549. max?: number;
  2550. /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */
  2551. flags?: number;
  2552. /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection */
  2553. storageEngine?: Document;
  2554. /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */
  2555. validator?: Document;
  2556. /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */
  2557. validationLevel?: string;
  2558. /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */
  2559. validationAction?: string;
  2560. /** Allows users to specify a default configuration for indexes when creating a collection */
  2561. indexOptionDefaults?: Document;
  2562. /** The name of the source collection or view from which to create the view. The name is not the full namespace of the collection or view (i.e., does not include the database name and implies the same database as the view to create) */
  2563. viewOn?: string;
  2564. /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view */
  2565. pipeline?: Document[];
  2566. /** A primary key factory function for generation of custom _id keys. */
  2567. pkFactory?: PkFactory;
  2568. /** A document specifying configuration options for timeseries collections. */
  2569. timeseries?: TimeSeriesCollectionOptions;
  2570. /** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */
  2571. clusteredIndex?: ClusteredCollectionOptions;
  2572. /** The number of seconds after which a document in a timeseries or clustered collection expires. */
  2573. expireAfterSeconds?: number;
  2574. /** @experimental */
  2575. encryptedFields?: Document;
  2576. /**
  2577. * If set, enables pre-update and post-update document events to be included for any
  2578. * change streams that listen on this collection.
  2579. */
  2580. changeStreamPreAndPostImages?: {
  2581. enabled: boolean;
  2582. };
  2583. }
  2584. /** @public */
  2585. export declare interface CreateIndexesOptions extends Omit<CommandOperationOptions, 'writeConcern'> {
  2586. /** Creates the index in the background, yielding whenever possible. */
  2587. background?: boolean;
  2588. /** Creates an unique index. */
  2589. unique?: boolean;
  2590. /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */
  2591. name?: string;
  2592. /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */
  2593. partialFilterExpression?: Document;
  2594. /** Creates a sparse index. */
  2595. sparse?: boolean;
  2596. /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */
  2597. expireAfterSeconds?: number;
  2598. /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */
  2599. storageEngine?: Document;
  2600. /** (MongoDB 4.4. or higher) Specifies how many data-bearing members of a replica set, including the primary, must complete the index builds successfully before the primary marks the indexes as ready. This option accepts the same values for the "w" field in a write concern plus "votingMembers", which indicates all voting data-bearing nodes. */
  2601. commitQuorum?: number | string;
  2602. /** Specifies the index version number, either 0 or 1. */
  2603. version?: number;
  2604. weights?: Document;
  2605. default_language?: string;
  2606. language_override?: string;
  2607. textIndexVersion?: number;
  2608. '2dsphereIndexVersion'?: number;
  2609. bits?: number;
  2610. /** For geospatial indexes set the lower bound for the co-ordinates. */
  2611. min?: number;
  2612. /** For geospatial indexes set the high bound for the co-ordinates. */
  2613. max?: number;
  2614. bucketSize?: number;
  2615. wildcardProjection?: Document;
  2616. /** Specifies that the index should exist on the target collection but should not be used by the query planner when executing operations. (MongoDB 4.4 or higher) */
  2617. hidden?: boolean;
  2618. }
  2619. /** @public */
  2620. export declare const CURSOR_FLAGS: readonly ["tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial"];
  2621. /** @public */
  2622. export declare type CursorFlag = (typeof CURSOR_FLAGS)[number];
  2623. /** @public */
  2624. export declare interface CursorStreamOptions {
  2625. /** A transformation method applied to each document emitted by the stream */
  2626. transform?(this: void, doc: Document): Document;
  2627. }
  2628. /**
  2629. * The **Db** class is a class that represents a MongoDB Database.
  2630. * @public
  2631. *
  2632. * @example
  2633. * ```ts
  2634. * import { MongoClient } from 'mongodb';
  2635. *
  2636. * interface Pet {
  2637. * name: string;
  2638. * kind: 'dog' | 'cat' | 'fish';
  2639. * }
  2640. *
  2641. * const client = new MongoClient('mongodb://localhost:27017');
  2642. * const db = client.db();
  2643. *
  2644. * // Create a collection that validates our union
  2645. * await db.createCollection<Pet>('pets', {
  2646. * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }
  2647. * })
  2648. * ```
  2649. */
  2650. export declare class Db {
  2651. /* Excluded from this release type: s */
  2652. /* Excluded from this release type: client */
  2653. static SYSTEM_NAMESPACE_COLLECTION: string;
  2654. static SYSTEM_INDEX_COLLECTION: string;
  2655. static SYSTEM_PROFILE_COLLECTION: string;
  2656. static SYSTEM_USER_COLLECTION: string;
  2657. static SYSTEM_COMMAND_COLLECTION: string;
  2658. static SYSTEM_JS_COLLECTION: string;
  2659. /**
  2660. * Creates a new Db instance
  2661. *
  2662. * @param client - The MongoClient for the database.
  2663. * @param databaseName - The name of the database this instance represents.
  2664. * @param options - Optional settings for Db construction
  2665. */
  2666. constructor(client: MongoClient, databaseName: string, options?: DbOptions);
  2667. get databaseName(): string;
  2668. get options(): DbOptions | undefined;
  2669. /**
  2670. * Check if a secondary can be used (because the read preference is *not* set to primary)
  2671. */
  2672. get secondaryOk(): boolean;
  2673. get readConcern(): ReadConcern | undefined;
  2674. /**
  2675. * The current readPreference of the Db. If not explicitly defined for
  2676. * this Db, will be inherited from the parent MongoClient
  2677. */
  2678. get readPreference(): ReadPreference;
  2679. get bsonOptions(): BSONSerializeOptions;
  2680. get writeConcern(): WriteConcern | undefined;
  2681. get namespace(): string;
  2682. /**
  2683. * Create a new collection on a server with the specified options. Use this to create capped collections.
  2684. * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
  2685. *
  2686. * @param name - The name of the collection to create
  2687. * @param options - Optional settings for the command
  2688. */
  2689. createCollection<TSchema extends Document = Document>(name: string, options?: CreateCollectionOptions): Promise<Collection<TSchema>>;
  2690. /**
  2691. * Execute a command
  2692. *
  2693. * @remarks
  2694. * This command does not inherit options from the MongoClient.
  2695. *
  2696. * The driver will ensure the following fields are attached to the command sent to the server:
  2697. * - `lsid` - sourced from an implicit session or options.session
  2698. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  2699. * - `$db` - sourced from the name of this database
  2700. *
  2701. * If the client has a serverApi setting:
  2702. * - `apiVersion`
  2703. * - `apiStrict`
  2704. * - `apiDeprecationErrors`
  2705. *
  2706. * When in a transaction:
  2707. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  2708. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  2709. *
  2710. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  2711. *
  2712. * @param command - The command to run
  2713. * @param options - Optional settings for the command
  2714. */
  2715. command(command: Document, options?: RunCommandOptions): Promise<Document>;
  2716. /**
  2717. * Execute an aggregation framework pipeline against the database, needs MongoDB \>= 3.6
  2718. *
  2719. * @param pipeline - An array of aggregation stages to be executed
  2720. * @param options - Optional settings for the command
  2721. */
  2722. aggregate<T extends Document = Document>(pipeline?: Document[], options?: AggregateOptions): AggregationCursor<T>;
  2723. /** Return the Admin db instance */
  2724. admin(): Admin;
  2725. /**
  2726. * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
  2727. *
  2728. * @param name - the collection name we wish to access.
  2729. * @returns return the new Collection instance
  2730. */
  2731. collection<TSchema extends Document = Document>(name: string, options?: CollectionOptions): Collection<TSchema>;
  2732. /**
  2733. * Get all the db statistics.
  2734. *
  2735. * @param options - Optional settings for the command
  2736. */
  2737. stats(options?: DbStatsOptions): Promise<Document>;
  2738. /**
  2739. * List all collections of this database with optional filter
  2740. *
  2741. * @param filter - Query to filter collections by
  2742. * @param options - Optional settings for the command
  2743. */
  2744. listCollections(filter: Document, options: Exclude<ListCollectionsOptions, 'nameOnly'> & {
  2745. nameOnly: true;
  2746. }): ListCollectionsCursor<Pick<CollectionInfo, 'name' | 'type'>>;
  2747. listCollections(filter: Document, options: Exclude<ListCollectionsOptions, 'nameOnly'> & {
  2748. nameOnly: false;
  2749. }): ListCollectionsCursor<CollectionInfo>;
  2750. listCollections<T extends Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo = Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor<T>;
  2751. /**
  2752. * Rename a collection.
  2753. *
  2754. * @remarks
  2755. * This operation does not inherit options from the MongoClient.
  2756. *
  2757. * @param fromCollection - Name of current collection to rename
  2758. * @param toCollection - New name of of the collection
  2759. * @param options - Optional settings for the command
  2760. */
  2761. renameCollection<TSchema extends Document = Document>(fromCollection: string, toCollection: string, options?: RenameOptions): Promise<Collection<TSchema>>;
  2762. /**
  2763. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  2764. *
  2765. * @param name - Name of collection to drop
  2766. * @param options - Optional settings for the command
  2767. */
  2768. dropCollection(name: string, options?: DropCollectionOptions): Promise<boolean>;
  2769. /**
  2770. * Drop a database, removing it permanently from the server.
  2771. *
  2772. * @param options - Optional settings for the command
  2773. */
  2774. dropDatabase(options?: DropDatabaseOptions): Promise<boolean>;
  2775. /**
  2776. * Fetch all collections for the current db.
  2777. *
  2778. * @param options - Optional settings for the command
  2779. */
  2780. collections(options?: ListCollectionsOptions): Promise<Collection[]>;
  2781. /**
  2782. * Creates an index on the db and collection.
  2783. *
  2784. * @param name - Name of the collection to create the index on.
  2785. * @param indexSpec - Specify the field to index, or an index specification
  2786. * @param options - Optional settings for the command
  2787. */
  2788. createIndex(name: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
  2789. /**
  2790. * Add a user to the database
  2791. *
  2792. * @param username - The username for the new user
  2793. * @param passwordOrOptions - An optional password for the new user, or the options for the command
  2794. * @param options - Optional settings for the command
  2795. * @deprecated Use the createUser command in `db.command()` instead.
  2796. * @see https://www.mongodb.com/docs/manual/reference/command/createUser/
  2797. */
  2798. addUser(username: string, passwordOrOptions?: string | AddUserOptions, options?: AddUserOptions): Promise<Document>;
  2799. /**
  2800. * Remove a user from a database
  2801. *
  2802. * @param username - The username to remove
  2803. * @param options - Optional settings for the command
  2804. */
  2805. removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
  2806. /**
  2807. * Set the current profiling level of MongoDB
  2808. *
  2809. * @param level - The new profiling level (off, slow_only, all).
  2810. * @param options - Optional settings for the command
  2811. */
  2812. setProfilingLevel(level: ProfilingLevel, options?: SetProfilingLevelOptions): Promise<ProfilingLevel>;
  2813. /**
  2814. * Retrieve the current profiling Level for MongoDB
  2815. *
  2816. * @param options - Optional settings for the command
  2817. */
  2818. profilingLevel(options?: ProfilingLevelOptions): Promise<string>;
  2819. /**
  2820. * Retrieves this collections index info.
  2821. *
  2822. * @param name - The name of the collection.
  2823. * @param options - Optional settings for the command
  2824. */
  2825. indexInformation(name: string, options?: IndexInformationOptions): Promise<Document>;
  2826. /**
  2827. * Create a new Change Stream, watching for new changes (insertions, updates,
  2828. * replacements, deletions, and invalidations) in this database. Will ignore all
  2829. * changes to system collections.
  2830. *
  2831. * @remarks
  2832. * watch() accepts two generic arguments for distinct use cases:
  2833. * - The first is to provide the schema that may be defined for all the collections within this database
  2834. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  2835. *
  2836. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  2837. * @param options - Optional settings for the command
  2838. * @typeParam TSchema - Type of the data being detected by the change stream
  2839. * @typeParam TChange - Type of the whole change stream document emitted
  2840. */
  2841. watch<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream<TSchema, TChange>;
  2842. /**
  2843. * A low level cursor API providing basic driver functionality:
  2844. * - ClientSession management
  2845. * - ReadPreference for server selection
  2846. * - Running getMores automatically when a local batch is exhausted
  2847. *
  2848. * @param command - The command that will start a cursor on the server.
  2849. * @param options - Configurations for running the command, bson options will apply to getMores
  2850. */
  2851. runCursorCommand(command: Document, options?: RunCursorCommandOptions): RunCommandCursor;
  2852. }
  2853. /* Excluded from this release type: DB_AGGREGATE_COLLECTION */
  2854. /** @public */
  2855. export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions {
  2856. /** If the database authentication is dependent on another databaseName. */
  2857. authSource?: string;
  2858. /** Force server to assign _id values instead of driver. */
  2859. forceServerObjectId?: boolean;
  2860. /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */
  2861. readPreference?: ReadPreferenceLike;
  2862. /** A primary key factory object for generation of custom _id keys. */
  2863. pkFactory?: PkFactory;
  2864. /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */
  2865. readConcern?: ReadConcern;
  2866. /** Should retry failed writes */
  2867. retryWrites?: boolean;
  2868. }
  2869. /* Excluded from this release type: DbPrivate */
  2870. export { DBRef }
  2871. /** @public */
  2872. export declare interface DbStatsOptions extends CommandOperationOptions {
  2873. /** Divide the returned sizes by scale value. */
  2874. scale?: number;
  2875. }
  2876. export { Decimal128 }
  2877. /** @public */
  2878. export declare interface DeleteManyModel<TSchema extends Document = Document> {
  2879. /** The filter to limit the deleted documents. */
  2880. filter: Filter<TSchema>;
  2881. /** Specifies a collation. */
  2882. collation?: CollationOptions;
  2883. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  2884. hint?: Hint;
  2885. }
  2886. /** @public */
  2887. export declare interface DeleteOneModel<TSchema extends Document = Document> {
  2888. /** The filter to limit the deleted documents. */
  2889. filter: Filter<TSchema>;
  2890. /** Specifies a collation. */
  2891. collation?: CollationOptions;
  2892. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  2893. hint?: Hint;
  2894. }
  2895. /** @public */
  2896. export declare interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions {
  2897. /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */
  2898. ordered?: boolean;
  2899. /** Specifies the collation to use for the operation */
  2900. collation?: CollationOptions;
  2901. /** Specify that the update query should only consider plans using the hinted index */
  2902. hint?: string | Document;
  2903. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  2904. let?: Document;
  2905. }
  2906. /** @public */
  2907. export declare interface DeleteResult {
  2908. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */
  2909. acknowledged: boolean;
  2910. /** The number of documents that were deleted */
  2911. deletedCount: number;
  2912. }
  2913. /** @public */
  2914. export declare interface DeleteStatement {
  2915. /** The query that matches documents to delete. */
  2916. q: Document;
  2917. /** The number of matching documents to delete. */
  2918. limit: number;
  2919. /** Specifies the collation to use for the operation. */
  2920. collation?: CollationOptions;
  2921. /** A document or string that specifies the index to use to support the query predicate. */
  2922. hint?: Hint;
  2923. }
  2924. export { deserialize }
  2925. /* Excluded from this release type: DestroyOptions */
  2926. /** @public */
  2927. export declare type DistinctOptions = CommandOperationOptions;
  2928. export { Document }
  2929. export { Double }
  2930. /** @public */
  2931. export declare interface DriverInfo {
  2932. name?: string;
  2933. version?: string;
  2934. platform?: string;
  2935. }
  2936. /** @public */
  2937. export declare interface DropCollectionOptions extends CommandOperationOptions {
  2938. /** @experimental */
  2939. encryptedFields?: Document;
  2940. }
  2941. /** @public */
  2942. export declare type DropDatabaseOptions = CommandOperationOptions;
  2943. /** @public */
  2944. export declare type DropIndexesOptions = CommandOperationOptions;
  2945. /* Excluded from this release type: Encrypter */
  2946. /* Excluded from this release type: EncrypterOptions */
  2947. /** @public */
  2948. export declare interface EndSessionOptions {
  2949. /* Excluded from this release type: error */
  2950. force?: boolean;
  2951. forceClear?: boolean;
  2952. }
  2953. /** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */
  2954. export declare type EnhancedOmit<TRecordOrUnion, KeyUnion> = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>> : never;
  2955. /** @public */
  2956. export declare interface ErrorDescription extends Document {
  2957. message?: string;
  2958. errmsg?: string;
  2959. $err?: string;
  2960. errorLabels?: string[];
  2961. errInfo?: Document;
  2962. }
  2963. /** @public */
  2964. export declare interface EstimatedDocumentCountOptions extends CommandOperationOptions {
  2965. /**
  2966. * The maximum amount of time to allow the operation to run.
  2967. *
  2968. * This option is sent only if the caller explicitly provides a value. The default is to not send a value.
  2969. */
  2970. maxTimeMS?: number;
  2971. }
  2972. /** @public */
  2973. export declare interface EvalOptions extends CommandOperationOptions {
  2974. nolock?: boolean;
  2975. }
  2976. /** @public */
  2977. export declare type EventEmitterWithState = {
  2978. /* Excluded from this release type: stateChanged */
  2979. };
  2980. /**
  2981. * Event description type
  2982. * @public
  2983. */
  2984. export declare type EventsDescription = Record<string, GenericListener>;
  2985. /* Excluded from this release type: ExecutionResult */
  2986. /* Excluded from this release type: Explain */
  2987. /** @public */
  2988. export declare interface ExplainOptions {
  2989. /** Specifies the verbosity mode for the explain output. */
  2990. explain?: ExplainVerbosityLike;
  2991. }
  2992. /** @public */
  2993. export declare const ExplainVerbosity: Readonly<{
  2994. readonly queryPlanner: "queryPlanner";
  2995. readonly queryPlannerExtended: "queryPlannerExtended";
  2996. readonly executionStats: "executionStats";
  2997. readonly allPlansExecution: "allPlansExecution";
  2998. }>;
  2999. /** @public */
  3000. export declare type ExplainVerbosity = string;
  3001. /**
  3002. * For backwards compatibility, true is interpreted as "allPlansExecution"
  3003. * and false as "queryPlanner". Prior to server version 3.6, aggregate()
  3004. * ignores the verbosity parameter and executes in "queryPlanner".
  3005. * @public
  3006. */
  3007. export declare type ExplainVerbosityLike = ExplainVerbosity | boolean;
  3008. /** A MongoDB filter can be some portion of the schema or a set of operators @public */
  3009. export declare type Filter<TSchema> = {
  3010. [P in keyof WithId<TSchema>]?: Condition<WithId<TSchema>[P]>;
  3011. } & RootFilterOperators<WithId<TSchema>>;
  3012. /** @public */
  3013. export declare type FilterOperations<T> = T extends Record<string, any> ? {
  3014. [key in keyof T]?: FilterOperators<T[key]>;
  3015. } : FilterOperators<T>;
  3016. /** @public */
  3017. export declare interface FilterOperators<TValue> extends NonObjectIdLikeDocument {
  3018. $eq?: TValue;
  3019. $gt?: TValue;
  3020. $gte?: TValue;
  3021. $in?: ReadonlyArray<TValue>;
  3022. $lt?: TValue;
  3023. $lte?: TValue;
  3024. $ne?: TValue;
  3025. $nin?: ReadonlyArray<TValue>;
  3026. $not?: TValue extends string ? FilterOperators<TValue> | RegExp : FilterOperators<TValue>;
  3027. /**
  3028. * When `true`, `$exists` matches the documents that contain the field,
  3029. * including documents where the field value is null.
  3030. */
  3031. $exists?: boolean;
  3032. $type?: BSONType | BSONTypeAlias;
  3033. $expr?: Record<string, any>;
  3034. $jsonSchema?: Record<string, any>;
  3035. $mod?: TValue extends number ? [number, number] : never;
  3036. $regex?: TValue extends string ? RegExp | BSONRegExp | string : never;
  3037. $options?: TValue extends string ? string : never;
  3038. $geoIntersects?: {
  3039. $geometry: Document;
  3040. };
  3041. $geoWithin?: Document;
  3042. $near?: Document;
  3043. $nearSphere?: Document;
  3044. $maxDistance?: number;
  3045. $all?: ReadonlyArray<any>;
  3046. $elemMatch?: Document;
  3047. $size?: TValue extends ReadonlyArray<any> ? number : never;
  3048. $bitsAllClear?: BitwiseFilter;
  3049. $bitsAllSet?: BitwiseFilter;
  3050. $bitsAnyClear?: BitwiseFilter;
  3051. $bitsAnySet?: BitwiseFilter;
  3052. $rand?: Record<string, never>;
  3053. }
  3054. /** @public */
  3055. export declare class FindCursor<TSchema = any> extends AbstractCursor<TSchema> {
  3056. /* Excluded from this release type: [kFilter] */
  3057. /* Excluded from this release type: [kNumReturned] */
  3058. /* Excluded from this release type: [kBuiltOptions] */
  3059. /* Excluded from this release type: __constructor */
  3060. clone(): FindCursor<TSchema>;
  3061. map<T>(transform: (doc: TSchema) => T): FindCursor<T>;
  3062. /* Excluded from this release type: _initialize */
  3063. /* Excluded from this release type: _getMore */
  3064. /**
  3065. * Get the count of documents for this cursor
  3066. * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead
  3067. */
  3068. count(options?: CountOptions): Promise<number>;
  3069. /** Execute the explain for the cursor */
  3070. explain(verbosity?: ExplainVerbosityLike): Promise<Document>;
  3071. /** Set the cursor query */
  3072. filter(filter: Document): this;
  3073. /**
  3074. * Set the cursor hint
  3075. *
  3076. * @param hint - If specified, then the query system will only consider plans using the hinted index.
  3077. */
  3078. hint(hint: Hint): this;
  3079. /**
  3080. * Set the cursor min
  3081. *
  3082. * @param min - Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
  3083. */
  3084. min(min: Document): this;
  3085. /**
  3086. * Set the cursor max
  3087. *
  3088. * @param max - Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
  3089. */
  3090. max(max: Document): this;
  3091. /**
  3092. * Set the cursor returnKey.
  3093. * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents.
  3094. * If set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields.
  3095. *
  3096. * @param value - the returnKey value.
  3097. */
  3098. returnKey(value: boolean): this;
  3099. /**
  3100. * Modifies the output of a query by adding a field $recordId to matching documents. $recordId is the internal key which uniquely identifies a document in a collection.
  3101. *
  3102. * @param value - The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
  3103. */
  3104. showRecordId(value: boolean): this;
  3105. /**
  3106. * Add a query modifier to the cursor query
  3107. *
  3108. * @param name - The query modifier (must start with $, such as $orderby etc)
  3109. * @param value - The modifier value.
  3110. */
  3111. addQueryModifier(name: string, value: string | boolean | number | Document): this;
  3112. /**
  3113. * Add a comment to the cursor query allowing for tracking the comment in the log.
  3114. *
  3115. * @param value - The comment attached to this query.
  3116. */
  3117. comment(value: string): this;
  3118. /**
  3119. * Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
  3120. *
  3121. * @param value - Number of milliseconds to wait before aborting the tailed query.
  3122. */
  3123. maxAwaitTimeMS(value: number): this;
  3124. /**
  3125. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  3126. *
  3127. * @param value - Number of milliseconds to wait before aborting the query.
  3128. */
  3129. maxTimeMS(value: number): this;
  3130. /**
  3131. * Add a project stage to the aggregation pipeline
  3132. *
  3133. * @remarks
  3134. * In order to strictly type this function you must provide an interface
  3135. * that represents the effect of your projection on the result documents.
  3136. *
  3137. * By default chaining a projection to your cursor changes the returned type to the generic
  3138. * {@link Document} type.
  3139. * You should specify a parameterized type to have assertions on your final results.
  3140. *
  3141. * @example
  3142. * ```typescript
  3143. * // Best way
  3144. * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
  3145. * // Flexible way
  3146. * const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
  3147. * ```
  3148. *
  3149. * @remarks
  3150. *
  3151. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  3152. * it **does not** return a new instance of a cursor. This means when calling project,
  3153. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  3154. * Take note of the following example:
  3155. *
  3156. * @example
  3157. * ```typescript
  3158. * const cursor: FindCursor<{ a: number; b: string }> = coll.find();
  3159. * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
  3160. * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
  3161. *
  3162. * // or always use chaining and save the final cursor
  3163. *
  3164. * const cursor = coll.find().project<{ a: string }>({
  3165. * _id: 0,
  3166. * a: { $convert: { input: '$a', to: 'string' }
  3167. * }});
  3168. * ```
  3169. */
  3170. project<T extends Document = Document>(value: Document): FindCursor<T>;
  3171. /**
  3172. * Sets the sort order of the cursor query.
  3173. *
  3174. * @param sort - The key or keys set for the sort.
  3175. * @param direction - The direction of the sorting (1 or -1).
  3176. */
  3177. sort(sort: Sort | string, direction?: SortDirection): this;
  3178. /**
  3179. * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher)
  3180. *
  3181. * @remarks
  3182. * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation}
  3183. */
  3184. allowDiskUse(allow?: boolean): this;
  3185. /**
  3186. * Set the collation options for the cursor.
  3187. *
  3188. * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  3189. */
  3190. collation(value: CollationOptions): this;
  3191. /**
  3192. * Set the limit for the cursor.
  3193. *
  3194. * @param value - The limit for the cursor query.
  3195. */
  3196. limit(value: number): this;
  3197. /**
  3198. * Set the skip for the cursor.
  3199. *
  3200. * @param value - The skip for the cursor query.
  3201. */
  3202. skip(value: number): this;
  3203. }
  3204. /** @public */
  3205. export declare interface FindOneAndDeleteOptions extends CommandOperationOptions {
  3206. /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/
  3207. hint?: Document;
  3208. /** Limits the fields to return for all matching documents. */
  3209. projection?: Document;
  3210. /** Determines which document the operation modifies if the query selects multiple documents. */
  3211. sort?: Sort;
  3212. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  3213. let?: Document;
  3214. /**
  3215. * Return the ModifyResult instead of the modified document. Defaults to true
  3216. * but will default to false in the next major version.
  3217. */
  3218. includeResultMetadata?: boolean;
  3219. }
  3220. /** @public */
  3221. export declare interface FindOneAndReplaceOptions extends CommandOperationOptions {
  3222. /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
  3223. bypassDocumentValidation?: boolean;
  3224. /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/
  3225. hint?: Document;
  3226. /** Limits the fields to return for all matching documents. */
  3227. projection?: Document;
  3228. /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */
  3229. returnDocument?: ReturnDocument;
  3230. /** Determines which document the operation modifies if the query selects multiple documents. */
  3231. sort?: Sort;
  3232. /** Upsert the document if it does not exist. */
  3233. upsert?: boolean;
  3234. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  3235. let?: Document;
  3236. /**
  3237. * Return the ModifyResult instead of the modified document. Defaults to true
  3238. * but will default to false in the next major version.
  3239. */
  3240. includeResultMetadata?: boolean;
  3241. }
  3242. /** @public */
  3243. export declare interface FindOneAndUpdateOptions extends CommandOperationOptions {
  3244. /** Optional list of array filters referenced in filtered positional operators */
  3245. arrayFilters?: Document[];
  3246. /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
  3247. bypassDocumentValidation?: boolean;
  3248. /** An optional hint for query optimization. See the {@link https://www.mongodb.com/docs/manual/reference/command/update/#update-command-hint|update command} reference for more information.*/
  3249. hint?: Document;
  3250. /** Limits the fields to return for all matching documents. */
  3251. projection?: Document;
  3252. /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */
  3253. returnDocument?: ReturnDocument;
  3254. /** Determines which document the operation modifies if the query selects multiple documents. */
  3255. sort?: Sort;
  3256. /** Upsert the document if it does not exist. */
  3257. upsert?: boolean;
  3258. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  3259. let?: Document;
  3260. /**
  3261. * Return the ModifyResult instead of the modified document. Defaults to true
  3262. * but will default to false in the next major version.
  3263. */
  3264. includeResultMetadata?: boolean;
  3265. }
  3266. /**
  3267. * A builder object that is returned from {@link BulkOperationBase#find}.
  3268. * Is used to build a write operation that involves a query filter.
  3269. *
  3270. * @public
  3271. */
  3272. export declare class FindOperators {
  3273. bulkOperation: BulkOperationBase;
  3274. /* Excluded from this release type: __constructor */
  3275. /** Add a multiple update operation to the bulk operation */
  3276. update(updateDocument: Document | Document[]): BulkOperationBase;
  3277. /** Add a single update operation to the bulk operation */
  3278. updateOne(updateDocument: Document | Document[]): BulkOperationBase;
  3279. /** Add a replace one operation to the bulk operation */
  3280. replaceOne(replacement: Document): BulkOperationBase;
  3281. /** Add a delete one operation to the bulk operation */
  3282. deleteOne(): BulkOperationBase;
  3283. /** Add a delete many operation to the bulk operation */
  3284. delete(): BulkOperationBase;
  3285. /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */
  3286. upsert(): this;
  3287. /** Specifies the collation for the query condition. */
  3288. collation(collation: CollationOptions): this;
  3289. /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */
  3290. arrayFilters(arrayFilters: Document[]): this;
  3291. /** Specifies hint for the bulk operation. */
  3292. hint(hint: Hint): this;
  3293. }
  3294. /**
  3295. * @public
  3296. * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic
  3297. */
  3298. export declare interface FindOptions<TSchema extends Document = Document> extends Omit<CommandOperationOptions, 'writeConcern'> {
  3299. /** Sets the limit of documents returned in the query. */
  3300. limit?: number;
  3301. /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */
  3302. sort?: Sort;
  3303. /** The fields to return in the query. Object of fields to either include or exclude (one of, not both), `{'a':1, 'b': 1}` **or** `{'a': 0, 'b': 0}` */
  3304. projection?: Document;
  3305. /** Set to skip N documents ahead in your query (useful for pagination). */
  3306. skip?: number;
  3307. /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */
  3308. hint?: Hint;
  3309. /** Specify if the cursor can timeout. */
  3310. timeout?: boolean;
  3311. /** Specify if the cursor is tailable. */
  3312. tailable?: boolean;
  3313. /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */
  3314. awaitData?: boolean;
  3315. /** Set the batchSize for the getMoreCommand when iterating over the query results. */
  3316. batchSize?: number;
  3317. /** If true, returns only the index keys in the resulting documents. */
  3318. returnKey?: boolean;
  3319. /** The inclusive lower bound for a specific index */
  3320. min?: Document;
  3321. /** The exclusive upper bound for a specific index */
  3322. max?: Document;
  3323. /** Number of milliseconds to wait before aborting the query. */
  3324. maxTimeMS?: number;
  3325. /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true */
  3326. maxAwaitTimeMS?: number;
  3327. /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */
  3328. noCursorTimeout?: boolean;
  3329. /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */
  3330. collation?: CollationOptions;
  3331. /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */
  3332. allowDiskUse?: boolean;
  3333. /** Determines whether to close the cursor after the first batch. Defaults to false. */
  3334. singleBatch?: boolean;
  3335. /** For queries against a sharded collection, allows the command (or subsequent getMore commands) to return partial results, rather than an error, if one or more queried shards are unavailable. */
  3336. allowPartialResults?: boolean;
  3337. /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */
  3338. showRecordId?: boolean;
  3339. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  3340. let?: Document;
  3341. /**
  3342. * Option to enable an optimized code path for queries looking for a particular range of `ts` values in the oplog. Requires `tailable` to be true.
  3343. * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored.
  3344. */
  3345. oplogReplay?: boolean;
  3346. }
  3347. /** @public */
  3348. export declare type Flatten<Type> = Type extends ReadonlyArray<infer Item> ? Item : Type;
  3349. /** @public */
  3350. export declare type GenericListener = (...args: any[]) => void;
  3351. /**
  3352. * Constructor for a streaming GridFS interface
  3353. * @public
  3354. */
  3355. export declare class GridFSBucket extends TypedEventEmitter<GridFSBucketEvents> {
  3356. /* Excluded from this release type: s */
  3357. /**
  3358. * When the first call to openUploadStream is made, the upload stream will
  3359. * check to see if it needs to create the proper indexes on the chunks and
  3360. * files collections. This event is fired either when 1) it determines that
  3361. * no index creation is necessary, 2) when it successfully creates the
  3362. * necessary indexes.
  3363. * @event
  3364. */
  3365. static readonly INDEX: "index";
  3366. constructor(db: Db, options?: GridFSBucketOptions);
  3367. /**
  3368. * Returns a writable stream (GridFSBucketWriteStream) for writing
  3369. * buffers to GridFS. The stream's 'id' property contains the resulting
  3370. * file's id.
  3371. *
  3372. * @param filename - The value of the 'filename' key in the files doc
  3373. * @param options - Optional settings.
  3374. */
  3375. openUploadStream(filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream;
  3376. /**
  3377. * Returns a writable stream (GridFSBucketWriteStream) for writing
  3378. * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
  3379. * file's id.
  3380. */
  3381. openUploadStreamWithId(id: ObjectId, filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream;
  3382. /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */
  3383. openDownloadStream(id: ObjectId, options?: GridFSBucketReadStreamOptions): GridFSBucketReadStream;
  3384. /**
  3385. * Deletes a file with the given id
  3386. *
  3387. * @param id - The id of the file doc
  3388. */
  3389. delete(id: ObjectId): Promise<void>;
  3390. /** Convenience wrapper around find on the files collection */
  3391. find(filter?: Filter<GridFSFile>, options?: FindOptions): FindCursor<GridFSFile>;
  3392. /**
  3393. * Returns a readable stream (GridFSBucketReadStream) for streaming the
  3394. * file with the given name from GridFS. If there are multiple files with
  3395. * the same name, this will stream the most recent file with the given name
  3396. * (as determined by the `uploadDate` field). You can set the `revision`
  3397. * option to change this behavior.
  3398. */
  3399. openDownloadStreamByName(filename: string, options?: GridFSBucketReadStreamOptionsWithRevision): GridFSBucketReadStream;
  3400. /**
  3401. * Renames the file with the given _id to the given string
  3402. *
  3403. * @param id - the id of the file to rename
  3404. * @param filename - new name for the file
  3405. */
  3406. rename(id: ObjectId, filename: string): Promise<void>;
  3407. /** Removes this bucket's files collection, followed by its chunks collection. */
  3408. drop(): Promise<void>;
  3409. }
  3410. /** @public */
  3411. export declare type GridFSBucketEvents = {
  3412. index(): void;
  3413. };
  3414. /** @public */
  3415. export declare interface GridFSBucketOptions extends WriteConcernOptions {
  3416. /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */
  3417. bucketName?: string;
  3418. /** Number of bytes stored in each chunk. Defaults to 255KB */
  3419. chunkSizeBytes?: number;
  3420. /** Read preference to be passed to read operations */
  3421. readPreference?: ReadPreference;
  3422. }
  3423. /* Excluded from this release type: GridFSBucketPrivate */
  3424. /**
  3425. * A readable stream that enables you to read buffers from GridFS.
  3426. *
  3427. * Do not instantiate this class directly. Use `openDownloadStream()` instead.
  3428. * @public
  3429. */
  3430. export declare class GridFSBucketReadStream extends Readable implements NodeJS.ReadableStream {
  3431. /* Excluded from this release type: s */
  3432. /**
  3433. * An error occurred
  3434. * @event
  3435. */
  3436. static readonly ERROR: "error";
  3437. /**
  3438. * Fires when the stream loaded the file document corresponding to the provided id.
  3439. * @event
  3440. */
  3441. static readonly FILE: "file";
  3442. /**
  3443. * Emitted when a chunk of data is available to be consumed.
  3444. * @event
  3445. */
  3446. static readonly DATA: "data";
  3447. /**
  3448. * Fired when the stream is exhausted (no more data events).
  3449. * @event
  3450. */
  3451. static readonly END: "end";
  3452. /**
  3453. * Fired when the stream is exhausted and the underlying cursor is killed
  3454. * @event
  3455. */
  3456. static readonly CLOSE: "close";
  3457. /* Excluded from this release type: __constructor */
  3458. /* Excluded from this release type: _read */
  3459. /**
  3460. * Sets the 0-based offset in bytes to start streaming from. Throws
  3461. * an error if this stream has entered flowing mode
  3462. * (e.g. if you've already called `on('data')`)
  3463. *
  3464. * @param start - 0-based offset in bytes to start streaming from
  3465. */
  3466. start(start?: number): this;
  3467. /**
  3468. * Sets the 0-based offset in bytes to start streaming from. Throws
  3469. * an error if this stream has entered flowing mode
  3470. * (e.g. if you've already called `on('data')`)
  3471. *
  3472. * @param end - Offset in bytes to stop reading at
  3473. */
  3474. end(end?: number): this;
  3475. /**
  3476. * Marks this stream as aborted (will never push another `data` event)
  3477. * and kills the underlying cursor. Will emit the 'end' event, and then
  3478. * the 'close' event once the cursor is successfully killed.
  3479. */
  3480. abort(): Promise<void>;
  3481. }
  3482. /** @public */
  3483. export declare interface GridFSBucketReadStreamOptions {
  3484. sort?: Sort;
  3485. skip?: number;
  3486. /**
  3487. * 0-indexed non-negative byte offset from the beginning of the file
  3488. */
  3489. start?: number;
  3490. /**
  3491. * 0-indexed non-negative byte offset to the end of the file contents
  3492. * to be returned by the stream. `end` is non-inclusive
  3493. */
  3494. end?: number;
  3495. }
  3496. /** @public */
  3497. export declare interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions {
  3498. /** The revision number relative to the oldest file with the given filename. 0
  3499. * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the
  3500. * newest. */
  3501. revision?: number;
  3502. }
  3503. /* Excluded from this release type: GridFSBucketReadStreamPrivate */
  3504. /**
  3505. * A writable stream that enables you to write buffers to GridFS.
  3506. *
  3507. * Do not instantiate this class directly. Use `openUploadStream()` instead.
  3508. * @public
  3509. */
  3510. export declare class GridFSBucketWriteStream extends Writable implements NodeJS.WritableStream {
  3511. bucket: GridFSBucket;
  3512. chunks: Collection<GridFSChunk>;
  3513. filename: string;
  3514. files: Collection<GridFSFile>;
  3515. options: GridFSBucketWriteStreamOptions;
  3516. done: boolean;
  3517. id: ObjectId;
  3518. chunkSizeBytes: number;
  3519. bufToStore: Buffer;
  3520. length: number;
  3521. n: number;
  3522. pos: number;
  3523. state: {
  3524. streamEnd: boolean;
  3525. outstandingRequests: number;
  3526. errored: boolean;
  3527. aborted: boolean;
  3528. };
  3529. writeConcern?: WriteConcern;
  3530. /** @event */
  3531. static readonly CLOSE = "close";
  3532. /** @event */
  3533. static readonly ERROR = "error";
  3534. /**
  3535. * `end()` was called and the write stream successfully wrote the file metadata and all the chunks to MongoDB.
  3536. * @event
  3537. */
  3538. static readonly FINISH = "finish";
  3539. /* Excluded from this release type: __constructor */
  3540. /**
  3541. * Write a buffer to the stream.
  3542. *
  3543. * @param chunk - Buffer to write
  3544. * @param encodingOrCallback - Optional encoding for the buffer
  3545. * @param callback - Function to call when the chunk was added to the buffer, or if the entire chunk was persisted to MongoDB if this chunk caused a flush.
  3546. * @returns False if this write required flushing a chunk to MongoDB. True otherwise.
  3547. */
  3548. write(chunk: Buffer | string): boolean;
  3549. write(chunk: Buffer | string, callback: Callback<void>): boolean;
  3550. write(chunk: Buffer | string, encoding: BufferEncoding | undefined): boolean;
  3551. write(chunk: Buffer | string, encoding: BufferEncoding | undefined, callback: Callback<void>): boolean;
  3552. /**
  3553. * Places this write stream into an aborted state (all future writes fail)
  3554. * and deletes all chunks that have already been written.
  3555. */
  3556. abort(): Promise<void>;
  3557. /**
  3558. * Tells the stream that no more data will be coming in. The stream will
  3559. * persist the remaining data to MongoDB, write the files document, and
  3560. * then emit a 'finish' event.
  3561. *
  3562. * @param chunk - Buffer to write
  3563. * @param encoding - Optional encoding for the buffer
  3564. * @param callback - Function to call when all files and chunks have been persisted to MongoDB
  3565. */
  3566. end(): this;
  3567. end(chunk: Buffer): this;
  3568. end(callback: Callback<GridFSFile | void>): this;
  3569. end(chunk: Buffer, callback: Callback<GridFSFile | void>): this;
  3570. end(chunk: Buffer, encoding: BufferEncoding): this;
  3571. end(chunk: Buffer, encoding: BufferEncoding | undefined, callback: Callback<GridFSFile | void>): this;
  3572. }
  3573. /** @public */
  3574. export declare interface GridFSBucketWriteStreamOptions extends WriteConcernOptions {
  3575. /** Overwrite this bucket's chunkSizeBytes for this file */
  3576. chunkSizeBytes?: number;
  3577. /** Custom file id for the GridFS file. */
  3578. id?: ObjectId;
  3579. /** Object to store in the file document's `metadata` field */
  3580. metadata?: Document;
  3581. /** String to store in the file document's `contentType` field */
  3582. contentType?: string;
  3583. /** Array of strings to store in the file document's `aliases` field */
  3584. aliases?: string[];
  3585. }
  3586. /** @public */
  3587. export declare interface GridFSChunk {
  3588. _id: ObjectId;
  3589. files_id: ObjectId;
  3590. n: number;
  3591. data: Buffer | Uint8Array;
  3592. }
  3593. /** @public */
  3594. export declare interface GridFSFile {
  3595. _id: ObjectId;
  3596. length: number;
  3597. chunkSize: number;
  3598. filename: string;
  3599. contentType?: string;
  3600. aliases?: string[];
  3601. metadata?: Document;
  3602. uploadDate: Date;
  3603. }
  3604. /** @public */
  3605. export declare const GSSAPICanonicalizationValue: Readonly<{
  3606. readonly on: true;
  3607. readonly off: false;
  3608. readonly none: "none";
  3609. readonly forward: "forward";
  3610. readonly forwardAndReverse: "forwardAndReverse";
  3611. }>;
  3612. /** @public */
  3613. export declare type GSSAPICanonicalizationValue = (typeof GSSAPICanonicalizationValue)[keyof typeof GSSAPICanonicalizationValue];
  3614. /** @public */
  3615. export declare interface HedgeOptions {
  3616. /** Explicitly enable or disable hedged reads. */
  3617. enabled?: boolean;
  3618. }
  3619. /** @public */
  3620. export declare type Hint = string | Document;
  3621. /** @public */
  3622. export declare class HostAddress {
  3623. host: string | undefined;
  3624. port: number | undefined;
  3625. socketPath: string | undefined;
  3626. isIPv6: boolean;
  3627. constructor(hostString: string);
  3628. inspect(): string;
  3629. toString(): string;
  3630. static fromString(this: void, s: string): HostAddress;
  3631. static fromHostPort(host: string, port: number): HostAddress;
  3632. static fromSrvRecord({ name, port }: SrvRecord): HostAddress;
  3633. toHostPort(): {
  3634. host: string;
  3635. port: number;
  3636. };
  3637. }
  3638. /**
  3639. * @public
  3640. * @experimental
  3641. */
  3642. export declare interface IdPServerInfo {
  3643. issuer: string;
  3644. clientId: string;
  3645. requestScopes?: string[];
  3646. }
  3647. /**
  3648. * @public
  3649. * @experimental
  3650. */
  3651. export declare interface IdPServerResponse {
  3652. accessToken: string;
  3653. expiresInSeconds?: number;
  3654. refreshToken?: string;
  3655. }
  3656. /** @public */
  3657. export declare interface IndexDescription extends Pick<CreateIndexesOptions, 'background' | 'unique' | 'partialFilterExpression' | 'sparse' | 'hidden' | 'expireAfterSeconds' | 'storageEngine' | 'version' | 'weights' | 'default_language' | 'language_override' | 'textIndexVersion' | '2dsphereIndexVersion' | 'bits' | 'min' | 'max' | 'bucketSize' | 'wildcardProjection'> {
  3658. collation?: CollationOptions;
  3659. name?: string;
  3660. key: {
  3661. [key: string]: IndexDirection;
  3662. } | Map<string, IndexDirection>;
  3663. }
  3664. /** @public */
  3665. export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | 'hashed' | number;
  3666. /** @public */
  3667. export declare interface IndexInformationOptions {
  3668. full?: boolean;
  3669. readPreference?: ReadPreference;
  3670. session?: ClientSession;
  3671. }
  3672. /** @public */
  3673. export declare type IndexSpecification = OneOrMore<string | [string, IndexDirection] | {
  3674. [key: string]: IndexDirection;
  3675. } | Map<string, IndexDirection>>;
  3676. /** Given an object shaped type, return the type of the _id field or default to ObjectId @public */
  3677. export declare type InferIdType<TSchema> = TSchema extends {
  3678. _id: infer IdType;
  3679. } ? Record<any, never> extends IdType ? never : IdType : TSchema extends {
  3680. _id?: infer IdType;
  3681. } ? unknown extends IdType ? ObjectId : IdType : ObjectId;
  3682. /** @public */
  3683. export declare interface InsertManyResult<TSchema = Document> {
  3684. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  3685. acknowledged: boolean;
  3686. /** The number of inserted documents for this operations */
  3687. insertedCount: number;
  3688. /** Map of the index of the inserted document to the id of the inserted document */
  3689. insertedIds: {
  3690. [key: number]: InferIdType<TSchema>;
  3691. };
  3692. }
  3693. /** @public */
  3694. export declare interface InsertOneModel<TSchema extends Document = Document> {
  3695. /** The document to insert. */
  3696. document: OptionalId<TSchema>;
  3697. }
  3698. /** @public */
  3699. export declare interface InsertOneOptions extends CommandOperationOptions {
  3700. /** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
  3701. bypassDocumentValidation?: boolean;
  3702. /** Force server to assign _id values instead of driver. */
  3703. forceServerObjectId?: boolean;
  3704. }
  3705. /** @public */
  3706. export declare interface InsertOneResult<TSchema = Document> {
  3707. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  3708. acknowledged: boolean;
  3709. /** The identifier that was inserted. If the server generated the identifier, this value will be null as the driver does not have access to that data */
  3710. insertedId: InferIdType<TSchema>;
  3711. }
  3712. export { Int32 }
  3713. /** @public */
  3714. export declare type IntegerType = number | Int32 | Long | bigint;
  3715. /* Excluded from this release type: InternalAbstractCursorOptions */
  3716. /** @public */
  3717. export declare type IsAny<Type, ResultIfAny, ResultIfNotAny> = true extends false & Type ? ResultIfAny : ResultIfNotAny;
  3718. /**
  3719. * Helper types for dot-notation filter attributes
  3720. */
  3721. /** @public */
  3722. export declare type Join<T extends unknown[], D extends string> = T extends [] ? '' : T extends [string | number] ? `${T[0]}` : T extends [string | number, ...infer R] ? `${T[0]}${D}${Join<R, D>}` : string;
  3723. /* Excluded from this release type: kBeforeHandshake */
  3724. /* Excluded from this release type: kBuffer */
  3725. /* Excluded from this release type: kBuiltOptions */
  3726. /* Excluded from this release type: kCancellationToken */
  3727. /* Excluded from this release type: kCancellationToken_2 */
  3728. /* Excluded from this release type: kCancelled */
  3729. /* Excluded from this release type: kCancelled_2 */
  3730. /* Excluded from this release type: kCheckedOut */
  3731. /* Excluded from this release type: kClient */
  3732. /* Excluded from this release type: kClosed */
  3733. /* Excluded from this release type: kClosed_2 */
  3734. /* Excluded from this release type: kClusterTime */
  3735. /* Excluded from this release type: kConnection */
  3736. /* Excluded from this release type: kConnectionCounter */
  3737. /* Excluded from this release type: kConnections */
  3738. /* Excluded from this release type: kCursorStream */
  3739. /* Excluded from this release type: kDelayedTimeoutId */
  3740. /* Excluded from this release type: kDescription */
  3741. /* Excluded from this release type: kDocuments */
  3742. /* Excluded from this release type: kErrorLabels */
  3743. /** @public */
  3744. export declare type KeysOfAType<TSchema, Type> = {
  3745. [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? key : never;
  3746. }[keyof TSchema];
  3747. /** @public */
  3748. export declare type KeysOfOtherType<TSchema, Type> = {
  3749. [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? never : key;
  3750. }[keyof TSchema];
  3751. /* Excluded from this release type: kFilter */
  3752. /* Excluded from this release type: kGeneration */
  3753. /* Excluded from this release type: kGeneration_2 */
  3754. /* Excluded from this release type: kHello */
  3755. /* Excluded from this release type: kId */
  3756. /* Excluded from this release type: kInit */
  3757. /* Excluded from this release type: kInitialized */
  3758. /* Excluded from this release type: kInternalClient */
  3759. /* Excluded from this release type: kKilled */
  3760. /* Excluded from this release type: kLastUseTime */
  3761. /* Excluded from this release type: kMessageStream */
  3762. /* Excluded from this release type: kMetrics */
  3763. /* Excluded from this release type: kMinPoolSizeTimer */
  3764. /* Excluded from this release type: kMode */
  3765. /* Excluded from this release type: kMonitor */
  3766. /* Excluded from this release type: kMonitorId */
  3767. /* Excluded from this release type: kNamespace */
  3768. /* Excluded from this release type: kNumReturned */
  3769. /* Excluded from this release type: kOptions */
  3770. /* Excluded from this release type: kOptions_2 */
  3771. /* Excluded from this release type: kOptions_3 */
  3772. /* Excluded from this release type: kPending */
  3773. /* Excluded from this release type: kPinnedConnection */
  3774. /* Excluded from this release type: kPipeline */
  3775. /* Excluded from this release type: kPoolState */
  3776. /* Excluded from this release type: kProcessingWaitQueue */
  3777. /* Excluded from this release type: kQueue */
  3778. /* Excluded from this release type: kRoundTripTime */
  3779. /* Excluded from this release type: kRTTPinger */
  3780. /* Excluded from this release type: kServer */
  3781. /* Excluded from this release type: kServer_2 */
  3782. /* Excluded from this release type: kServer_3 */
  3783. /* Excluded from this release type: kServerError */
  3784. /* Excluded from this release type: kServerSession */
  3785. /* Excluded from this release type: kServiceGenerations */
  3786. /* Excluded from this release type: kSession */
  3787. /* Excluded from this release type: kSession_2 */
  3788. /* Excluded from this release type: kSnapshotEnabled */
  3789. /* Excluded from this release type: kSnapshotTime */
  3790. /* Excluded from this release type: kStream */
  3791. /* Excluded from this release type: kTransform */
  3792. /* Excluded from this release type: kTxnNumberIncrement */
  3793. /* Excluded from this release type: kWaitQueue */
  3794. /* Excluded from this release type: kWaitQueue_2 */
  3795. /** @public */
  3796. export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["family", "hints", "localAddress", "localPort", "lookup"];
  3797. /** @public */
  3798. export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly ["ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"];
  3799. /* Excluded from this release type: List */
  3800. /** @public */
  3801. export declare class ListCollectionsCursor<T extends Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo = Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo> extends AbstractCursor<T> {
  3802. parent: Db;
  3803. filter: Document;
  3804. options?: ListCollectionsOptions;
  3805. constructor(db: Db, filter: Document, options?: ListCollectionsOptions);
  3806. clone(): ListCollectionsCursor<T>;
  3807. /* Excluded from this release type: _initialize */
  3808. }
  3809. /** @public */
  3810. export declare interface ListCollectionsOptions extends Omit<CommandOperationOptions, 'writeConcern'> {
  3811. /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */
  3812. nameOnly?: boolean;
  3813. /** Since 4.0: If true and nameOnly is true, allows a user without the required privilege (i.e. listCollections action on the database) to run the command when access control is enforced. */
  3814. authorizedCollections?: boolean;
  3815. /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */
  3816. batchSize?: number;
  3817. }
  3818. /** @public */
  3819. export declare interface ListDatabasesOptions extends CommandOperationOptions {
  3820. /** A query predicate that determines which databases are listed */
  3821. filter?: Document;
  3822. /** A flag to indicate whether the command should return just the database names, or return both database names and size information */
  3823. nameOnly?: boolean;
  3824. /** A flag that determines which databases are returned based on the user privileges when access control is enabled */
  3825. authorizedDatabases?: boolean;
  3826. }
  3827. /** @public */
  3828. export declare interface ListDatabasesResult {
  3829. databases: ({
  3830. name: string;
  3831. sizeOnDisk?: number;
  3832. empty?: boolean;
  3833. } & Document)[];
  3834. totalSize?: number;
  3835. totalSizeMb?: number;
  3836. ok: 1 | 0;
  3837. }
  3838. /** @public */
  3839. export declare class ListIndexesCursor extends AbstractCursor {
  3840. parent: Collection;
  3841. options?: ListIndexesOptions;
  3842. constructor(collection: Collection, options?: ListIndexesOptions);
  3843. clone(): ListIndexesCursor;
  3844. /* Excluded from this release type: _initialize */
  3845. }
  3846. /** @public */
  3847. export declare interface ListIndexesOptions extends Omit<CommandOperationOptions, 'writeConcern'> {
  3848. /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */
  3849. batchSize?: number;
  3850. }
  3851. /** @public */
  3852. export declare class ListSearchIndexesCursor extends AggregationCursor<{
  3853. name: string;
  3854. }> {
  3855. /* Excluded from this release type: __constructor */
  3856. }
  3857. /** @public */
  3858. export declare type ListSearchIndexesOptions = AggregateOptions;
  3859. /* Excluded from this release type: Log */
  3860. /* Excluded from this release type: LogConvertible */
  3861. /* Excluded from this release type: Loggable */
  3862. /* Excluded from this release type: LoggableEvent */
  3863. export { Long }
  3864. /** @public */
  3865. export declare type MatchKeysAndValues<TSchema> = Readonly<Partial<TSchema>> & Record<string, any>;
  3866. export { MaxKey }
  3867. /* Excluded from this release type: MessageHeader */
  3868. /* Excluded from this release type: MessageStream */
  3869. /* Excluded from this release type: MessageStreamOptions */
  3870. export { MinKey }
  3871. /** @public */
  3872. export declare interface ModifyResult<TSchema = Document> {
  3873. value: WithId<TSchema> | null;
  3874. lastErrorObject?: Document;
  3875. ok: 0 | 1;
  3876. }
  3877. /** @public */
  3878. export declare const MONGO_CLIENT_EVENTS: readonly ["connectionPoolCreated", "connectionPoolReady", "connectionPoolCleared", "connectionPoolClosed", "connectionCreated", "connectionReady", "connectionClosed", "connectionCheckOutStarted", "connectionCheckOutFailed", "connectionCheckedOut", "connectionCheckedIn", "commandStarted", "commandSucceeded", "commandFailed", "serverOpening", "serverClosed", "serverDescriptionChanged", "topologyOpening", "topologyClosed", "topologyDescriptionChanged", "error", "timeout", "close", "serverHeartbeatStarted", "serverHeartbeatSucceeded", "serverHeartbeatFailed"];
  3879. /**
  3880. * An error generated when the driver API is used incorrectly
  3881. *
  3882. * @privateRemarks
  3883. * Should **never** be directly instantiated
  3884. *
  3885. * @public
  3886. * @category Error
  3887. */
  3888. export declare class MongoAPIError extends MongoDriverError {
  3889. constructor(message: string);
  3890. get name(): string;
  3891. }
  3892. /**
  3893. * A error generated when the user attempts to authenticate
  3894. * via AWS, but fails
  3895. *
  3896. * @public
  3897. * @category Error
  3898. */
  3899. export declare class MongoAWSError extends MongoRuntimeError {
  3900. constructor(message: string);
  3901. get name(): string;
  3902. }
  3903. /**
  3904. * A error generated when the user attempts to authenticate
  3905. * via Azure, but fails.
  3906. *
  3907. * @public
  3908. * @category Error
  3909. */
  3910. export declare class MongoAzureError extends MongoRuntimeError {
  3911. constructor(message: string);
  3912. get name(): string;
  3913. }
  3914. /**
  3915. * An error generated when a batch command is re-executed after one of the commands in the batch
  3916. * has failed
  3917. *
  3918. * @public
  3919. * @category Error
  3920. */
  3921. export declare class MongoBatchReExecutionError extends MongoAPIError {
  3922. constructor(message?: string);
  3923. get name(): string;
  3924. }
  3925. /**
  3926. * An error indicating an unsuccessful Bulk Write
  3927. * @public
  3928. * @category Error
  3929. */
  3930. export declare class MongoBulkWriteError extends MongoServerError {
  3931. result: BulkWriteResult;
  3932. writeErrors: OneOrMore<WriteError>;
  3933. err?: WriteConcernError;
  3934. /** Creates a new MongoBulkWriteError */
  3935. constructor(error: {
  3936. message: string;
  3937. code: number;
  3938. writeErrors?: WriteError[];
  3939. } | WriteConcernError | AnyError, result: BulkWriteResult);
  3940. get name(): string;
  3941. /** Number of documents inserted. */
  3942. get insertedCount(): number;
  3943. /** Number of documents matched for update. */
  3944. get matchedCount(): number;
  3945. /** Number of documents modified. */
  3946. get modifiedCount(): number;
  3947. /** Number of documents deleted. */
  3948. get deletedCount(): number;
  3949. /** Number of documents upserted. */
  3950. get upsertedCount(): number;
  3951. /** Inserted document generated Id's, hash key is the index of the originating operation */
  3952. get insertedIds(): {
  3953. [key: number]: any;
  3954. };
  3955. /** Upserted document generated Id's, hash key is the index of the originating operation */
  3956. get upsertedIds(): {
  3957. [key: number]: any;
  3958. };
  3959. }
  3960. /**
  3961. * An error generated when a ChangeStream operation fails to execute.
  3962. *
  3963. * @public
  3964. * @category Error
  3965. */
  3966. export declare class MongoChangeStreamError extends MongoRuntimeError {
  3967. constructor(message: string);
  3968. get name(): string;
  3969. }
  3970. /**
  3971. * The **MongoClient** class is a class that allows for making Connections to MongoDB.
  3972. * @public
  3973. *
  3974. * @remarks
  3975. * The programmatically provided options take precedence over the URI options.
  3976. *
  3977. * @example
  3978. * ```ts
  3979. * import { MongoClient } from 'mongodb';
  3980. *
  3981. * // Enable command monitoring for debugging
  3982. * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });
  3983. *
  3984. * client.on('commandStarted', started => console.log(started));
  3985. * client.db().collection('pets');
  3986. * await client.insertOne({ name: 'spot', kind: 'dog' });
  3987. * ```
  3988. */
  3989. export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> {
  3990. /* Excluded from this release type: s */
  3991. /* Excluded from this release type: topology */
  3992. /* Excluded from this release type: mongoLogger */
  3993. /* Excluded from this release type: connectionLock */
  3994. /* Excluded from this release type: [kOptions] */
  3995. constructor(url: string, options?: MongoClientOptions);
  3996. /** @see MongoOptions */
  3997. get options(): Readonly<MongoOptions>;
  3998. get serverApi(): Readonly<ServerApi | undefined>;
  3999. /* Excluded from this release type: monitorCommands */
  4000. /* Excluded from this release type: monitorCommands */
  4001. /**
  4002. * @deprecated This method will be removed in the next major version.
  4003. */
  4004. get autoEncrypter(): AutoEncrypter | undefined;
  4005. get readConcern(): ReadConcern | undefined;
  4006. get writeConcern(): WriteConcern | undefined;
  4007. get readPreference(): ReadPreference;
  4008. get bsonOptions(): BSONSerializeOptions;
  4009. /**
  4010. * Connect to MongoDB using a url
  4011. *
  4012. * @see docs.mongodb.org/manual/reference/connection-string/
  4013. */
  4014. connect(): Promise<this>;
  4015. /* Excluded from this release type: _connect */
  4016. /**
  4017. * Close the client and its underlying connections
  4018. *
  4019. * @param force - Force close, emitting no events
  4020. */
  4021. close(force?: boolean): Promise<void>;
  4022. /**
  4023. * Create a new Db instance sharing the current socket connections.
  4024. *
  4025. * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
  4026. * @param options - Optional settings for Db construction
  4027. */
  4028. db(dbName?: string, options?: DbOptions): Db;
  4029. /**
  4030. * Connect to MongoDB using a url
  4031. *
  4032. * @remarks
  4033. * The programmatically provided options take precedence over the URI options.
  4034. *
  4035. * @see https://www.mongodb.com/docs/manual/reference/connection-string/
  4036. */
  4037. static connect(url: string, options?: MongoClientOptions): Promise<MongoClient>;
  4038. /** Starts a new session on the server */
  4039. startSession(options?: ClientSessionOptions): ClientSession;
  4040. /**
  4041. * Runs a given operation with an implicitly created session. The lifetime of the session
  4042. * will be handled without the need for user interaction.
  4043. *
  4044. * NOTE: presently the operation MUST return a Promise (either explicit or implicitly as an async function)
  4045. *
  4046. * @param options - Optional settings for the command
  4047. * @param callback - An callback to execute with an implicitly created session
  4048. */
  4049. withSession(callback: WithSessionCallback): Promise<void>;
  4050. withSession(options: ClientSessionOptions, callback: WithSessionCallback): Promise<void>;
  4051. /**
  4052. * Create a new Change Stream, watching for new changes (insertions, updates,
  4053. * replacements, deletions, and invalidations) in this cluster. Will ignore all
  4054. * changes to system collections, as well as the local, admin, and config databases.
  4055. *
  4056. * @remarks
  4057. * watch() accepts two generic arguments for distinct use cases:
  4058. * - The first is to provide the schema that may be defined for all the data within the current cluster
  4059. * - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
  4060. *
  4061. * @param pipeline - An array of {@link https://www.mongodb.com/docs/manual/reference/operator/aggregation-pipeline/|aggregation pipeline stages} through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
  4062. * @param options - Optional settings for the command
  4063. * @typeParam TSchema - Type of the data being detected by the change stream
  4064. * @typeParam TChange - Type of the whole change stream document emitted
  4065. */
  4066. watch<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream<TSchema, TChange>;
  4067. }
  4068. /** @public */
  4069. export declare type MongoClientEvents = Pick<TopologyEvents, (typeof MONGO_CLIENT_EVENTS)[number]> & {
  4070. open(mongoClient: MongoClient): void;
  4071. };
  4072. /**
  4073. * Describes all possible URI query options for the mongo client
  4074. * @public
  4075. * @see https://www.mongodb.com/docs/manual/reference/connection-string
  4076. */
  4077. export declare interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions {
  4078. /** Specifies the name of the replica set, if the mongod is a member of a replica set. */
  4079. replicaSet?: string;
  4080. /** Enables or disables TLS/SSL for the connection. */
  4081. tls?: boolean;
  4082. /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
  4083. ssl?: boolean;
  4084. /**
  4085. * Specifies the location of a local TLS Certificate
  4086. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  4087. */
  4088. tlsCertificateFile?: string;
  4089. /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key or only the client's TLS/SSL key when tlsCertificateFile is used to provide the certificate. */
  4090. tlsCertificateKeyFile?: string;
  4091. /** Specifies the password to de-crypt the tlsCertificateKeyFile. */
  4092. tlsCertificateKeyFilePassword?: string;
  4093. /** Specifies the location of a local .pem file that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by the mongod/mongos instance. */
  4094. tlsCAFile?: string;
  4095. /** Bypasses validation of the certificates presented by the mongod/mongos instance */
  4096. tlsAllowInvalidCertificates?: boolean;
  4097. /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
  4098. tlsAllowInvalidHostnames?: boolean;
  4099. /** Disables various certificate validations. */
  4100. tlsInsecure?: boolean;
  4101. /** The time in milliseconds to attempt a connection before timing out. */
  4102. connectTimeoutMS?: number;
  4103. /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
  4104. socketTimeoutMS?: number;
  4105. /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
  4106. compressors?: CompressorName[] | string;
  4107. /** An integer that specifies the compression level if using zlib for network compression. */
  4108. zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
  4109. /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
  4110. srvMaxHosts?: number;
  4111. /**
  4112. * Modifies the srv URI to look like:
  4113. *
  4114. * `_{srvServiceName}._tcp.{hostname}.{domainname}`
  4115. *
  4116. * Querying this DNS URI is expected to respond with SRV records
  4117. */
  4118. srvServiceName?: string;
  4119. /** The maximum number of connections in the connection pool. */
  4120. maxPoolSize?: number;
  4121. /** The minimum number of connections in the connection pool. */
  4122. minPoolSize?: number;
  4123. /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
  4124. maxConnecting?: number;
  4125. /** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */
  4126. maxIdleTimeMS?: number;
  4127. /** The maximum time in milliseconds that a thread can wait for a connection to become available. */
  4128. waitQueueTimeoutMS?: number;
  4129. /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
  4130. readConcern?: ReadConcernLike;
  4131. /** The level of isolation */
  4132. readConcernLevel?: ReadConcernLevel;
  4133. /** Specifies the read preferences for this connection */
  4134. readPreference?: ReadPreferenceMode | ReadPreference;
  4135. /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
  4136. maxStalenessSeconds?: number;
  4137. /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */
  4138. readPreferenceTags?: TagSet[];
  4139. /** The auth settings for when connection to server. */
  4140. auth?: Auth;
  4141. /** Specify the database name associated with the user’s credentials. */
  4142. authSource?: string;
  4143. /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
  4144. authMechanism?: AuthMechanism;
  4145. /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
  4146. authMechanismProperties?: AuthMechanismProperties;
  4147. /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
  4148. localThresholdMS?: number;
  4149. /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
  4150. serverSelectionTimeoutMS?: number;
  4151. /** heartbeatFrequencyMS controls when the driver checks the state of the MongoDB deployment. Specify the interval (in milliseconds) between checks, counted from the end of the previous check until the beginning of the next one. */
  4152. heartbeatFrequencyMS?: number;
  4153. /** Sets the minimum heartbeat frequency. In the event that the driver has to frequently re-check a server's availability, it will wait at least this long since the previous check to avoid wasted effort. */
  4154. minHeartbeatFrequencyMS?: number;
  4155. /** The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections */
  4156. appName?: string;
  4157. /** Enables retryable reads. */
  4158. retryReads?: boolean;
  4159. /** Enable retryable writes. */
  4160. retryWrites?: boolean;
  4161. /** Allow a driver to force a Single topology type with a connection string containing one host */
  4162. directConnection?: boolean;
  4163. /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
  4164. loadBalanced?: boolean;
  4165. /**
  4166. * The write concern w value
  4167. * @deprecated Please use the `writeConcern` option instead
  4168. */
  4169. w?: W;
  4170. /**
  4171. * The write concern timeout
  4172. * @deprecated Please use the `writeConcern` option instead
  4173. */
  4174. wtimeoutMS?: number;
  4175. /**
  4176. * The journal write concern
  4177. * @deprecated Please use the `writeConcern` option instead
  4178. */
  4179. journal?: boolean;
  4180. /**
  4181. * A MongoDB WriteConcern, which describes the level of acknowledgement
  4182. * requested from MongoDB for write operations.
  4183. *
  4184. * @see https://www.mongodb.com/docs/manual/reference/write-concern/
  4185. */
  4186. writeConcern?: WriteConcern | WriteConcernSettings;
  4187. /**
  4188. * Validate mongod server certificate against Certificate Authority
  4189. * @deprecated Will be removed in the next major version. Please use tlsAllowInvalidCertificates instead.
  4190. */
  4191. sslValidate?: boolean;
  4192. /**
  4193. * SSL Certificate file path.
  4194. * @deprecated Will be removed in the next major version. Please use tlsCAFile instead.
  4195. */
  4196. sslCA?: string;
  4197. /**
  4198. * SSL Certificate file path.
  4199. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  4200. */
  4201. sslCert?: string;
  4202. /**
  4203. * SSL Key file file path.
  4204. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  4205. */
  4206. sslKey?: string;
  4207. /**
  4208. * SSL Certificate pass phrase.
  4209. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFilePassword instead.
  4210. */
  4211. sslPass?: string;
  4212. /**
  4213. * SSL Certificate revocation list file path.
  4214. * @deprecated Will be removed in the next major version. Please use tlsCertificateKeyFile instead.
  4215. */
  4216. sslCRL?: string;
  4217. /** TCP Connection no delay */
  4218. noDelay?: boolean;
  4219. /** @deprecated TCP Connection keep alive enabled. Will not be able to turn off in the future. */
  4220. keepAlive?: boolean;
  4221. /**
  4222. * @deprecated The number of milliseconds to wait before initiating keepAlive on the TCP socket.
  4223. * Will not be configurable in the future.
  4224. */
  4225. keepAliveInitialDelay?: number;
  4226. /** Force server to assign `_id` values instead of driver */
  4227. forceServerObjectId?: boolean;
  4228. /** A primary key factory function for generation of custom `_id` keys */
  4229. pkFactory?: PkFactory;
  4230. /** Enable command monitoring for this client */
  4231. monitorCommands?: boolean;
  4232. /** Server API version */
  4233. serverApi?: ServerApi | ServerApiVersion;
  4234. /**
  4235. * Optionally enable in-use auto encryption
  4236. *
  4237. * @remarks
  4238. * Automatic encryption is an enterprise only feature that only applies to operations on a collection. Automatic encryption is not supported for operations on a database or view, and operations that are not bypassed will result in error
  4239. * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.rst#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
  4240. *
  4241. * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
  4242. *
  4243. * If a MongoClient with a limited connection pool size (i.e a non-zero maxPoolSize) is configured with AutoEncryptionOptions, a separate internal MongoClient is created if any of the following are true:
  4244. * - AutoEncryptionOptions.keyVaultClient is not passed.
  4245. * - AutoEncryptionOptions.bypassAutomaticEncryption is false.
  4246. *
  4247. * If an internal MongoClient is created, it is configured with the same options as the parent MongoClient except minPoolSize is set to 0 and AutoEncryptionOptions is omitted.
  4248. */
  4249. autoEncryption?: AutoEncryptionOptions;
  4250. /** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */
  4251. driverInfo?: DriverInfo;
  4252. /** Configures a Socks5 proxy host used for creating TCP connections. */
  4253. proxyHost?: string;
  4254. /** Configures a Socks5 proxy port used for creating TCP connections. */
  4255. proxyPort?: number;
  4256. /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
  4257. proxyUsername?: string;
  4258. /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
  4259. proxyPassword?: string;
  4260. /* Excluded from this release type: srvPoller */
  4261. /* Excluded from this release type: connectionType */
  4262. /* Excluded from this release type: __index */
  4263. }
  4264. /* Excluded from this release type: MongoClientPrivate */
  4265. /**
  4266. * An error generated when a feature that is not enabled or allowed for the current server
  4267. * configuration is used
  4268. *
  4269. *
  4270. * @public
  4271. * @category Error
  4272. */
  4273. export declare class MongoCompatibilityError extends MongoAPIError {
  4274. constructor(message: string);
  4275. get name(): string;
  4276. }
  4277. /**
  4278. * A representation of the credentials used by MongoDB
  4279. * @public
  4280. */
  4281. export declare class MongoCredentials {
  4282. /** The username used for authentication */
  4283. readonly username: string;
  4284. /** The password used for authentication */
  4285. readonly password: string;
  4286. /** The database that the user should authenticate against */
  4287. readonly source: string;
  4288. /** The method used to authenticate */
  4289. readonly mechanism: AuthMechanism;
  4290. /** Special properties used by some types of auth mechanisms */
  4291. readonly mechanismProperties: AuthMechanismProperties;
  4292. constructor(options: MongoCredentialsOptions);
  4293. /** Determines if two MongoCredentials objects are equivalent */
  4294. equals(other: MongoCredentials): boolean;
  4295. /**
  4296. * If the authentication mechanism is set to "default", resolves the authMechanism
  4297. * based on the server version and server supported sasl mechanisms.
  4298. *
  4299. * @param hello - A hello response from the server
  4300. */
  4301. resolveAuthMechanism(hello?: Document): MongoCredentials;
  4302. validate(): void;
  4303. static merge(creds: MongoCredentials | undefined, options: Partial<MongoCredentialsOptions>): MongoCredentials;
  4304. }
  4305. /** @public */
  4306. export declare interface MongoCredentialsOptions {
  4307. username?: string;
  4308. password: string;
  4309. source: string;
  4310. db?: string;
  4311. mechanism?: AuthMechanism;
  4312. mechanismProperties: AuthMechanismProperties;
  4313. }
  4314. /**
  4315. * An error thrown when an attempt is made to read from a cursor that has been exhausted
  4316. *
  4317. * @public
  4318. * @category Error
  4319. */
  4320. export declare class MongoCursorExhaustedError extends MongoAPIError {
  4321. constructor(message?: string);
  4322. get name(): string;
  4323. }
  4324. /**
  4325. * An error thrown when the user attempts to add options to a cursor that has already been
  4326. * initialized
  4327. *
  4328. * @public
  4329. * @category Error
  4330. */
  4331. export declare class MongoCursorInUseError extends MongoAPIError {
  4332. constructor(message?: string);
  4333. get name(): string;
  4334. }
  4335. /**
  4336. * @public
  4337. *
  4338. * A class representing a collection's namespace. This class enforces (through Typescript) that
  4339. * the `collection` portion of the namespace is defined and should only be
  4340. * used in scenarios where this can be guaranteed.
  4341. */
  4342. export declare class MongoDBCollectionNamespace extends MongoDBNamespace {
  4343. collection: string;
  4344. constructor(db: string, collection: string);
  4345. }
  4346. /* Excluded from this release type: MongoDBLogWritable */
  4347. /** @public */
  4348. export declare class MongoDBNamespace {
  4349. db: string;
  4350. collection?: string | undefined;
  4351. /**
  4352. * Create a namespace object
  4353. *
  4354. * @param db - database name
  4355. * @param collection - collection name
  4356. */
  4357. constructor(db: string, collection?: string | undefined);
  4358. toString(): string;
  4359. withCollection(collection: string): MongoDBCollectionNamespace;
  4360. static fromString(namespace?: string): MongoDBNamespace;
  4361. }
  4362. /**
  4363. * An error generated when the driver fails to decompress
  4364. * data received from the server.
  4365. *
  4366. * @public
  4367. * @category Error
  4368. */
  4369. export declare class MongoDecompressionError extends MongoRuntimeError {
  4370. constructor(message: string);
  4371. get name(): string;
  4372. }
  4373. /**
  4374. * An error generated by the driver
  4375. *
  4376. * @public
  4377. * @category Error
  4378. */
  4379. export declare class MongoDriverError extends MongoError {
  4380. constructor(message: string);
  4381. get name(): string;
  4382. }
  4383. /**
  4384. * @public
  4385. * @category Error
  4386. *
  4387. * @privateRemarks
  4388. * mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument
  4389. */
  4390. export declare class MongoError extends Error {
  4391. /* Excluded from this release type: [kErrorLabels] */
  4392. /**
  4393. * This is a number in MongoServerError and a string in MongoDriverError
  4394. * @privateRemarks
  4395. * Define the type override on the subclasses when we can use the override keyword
  4396. */
  4397. code?: number | string;
  4398. topologyVersion?: TopologyVersion;
  4399. connectionGeneration?: number;
  4400. cause?: Error;
  4401. constructor(message: string | Error);
  4402. /* Excluded from this release type: buildErrorMessage */
  4403. get name(): string;
  4404. /** Legacy name for server error responses */
  4405. get errmsg(): string;
  4406. /**
  4407. * Checks the error to see if it has an error label
  4408. *
  4409. * @param label - The error label to check for
  4410. * @returns returns true if the error has the provided error label
  4411. */
  4412. hasErrorLabel(label: string): boolean;
  4413. addErrorLabel(label: string): void;
  4414. get errorLabels(): string[];
  4415. }
  4416. /** @public */
  4417. export declare const MongoErrorLabel: Readonly<{
  4418. readonly RetryableWriteError: "RetryableWriteError";
  4419. readonly TransientTransactionError: "TransientTransactionError";
  4420. readonly UnknownTransactionCommitResult: "UnknownTransactionCommitResult";
  4421. readonly ResumableChangeStreamError: "ResumableChangeStreamError";
  4422. readonly HandshakeError: "HandshakeError";
  4423. readonly ResetPool: "ResetPool";
  4424. readonly InterruptInUseConnections: "InterruptInUseConnections";
  4425. readonly NoWritesPerformed: "NoWritesPerformed";
  4426. }>;
  4427. /** @public */
  4428. export declare type MongoErrorLabel = (typeof MongoErrorLabel)[keyof typeof MongoErrorLabel];
  4429. /**
  4430. * An error generated when the user attempts to operate
  4431. * on a session that has expired or has been closed.
  4432. *
  4433. * @public
  4434. * @category Error
  4435. */
  4436. export declare class MongoExpiredSessionError extends MongoAPIError {
  4437. constructor(message?: string);
  4438. get name(): string;
  4439. }
  4440. /**
  4441. * An error generated when a malformed or invalid chunk is
  4442. * encountered when reading from a GridFSStream.
  4443. *
  4444. * @public
  4445. * @category Error
  4446. */
  4447. export declare class MongoGridFSChunkError extends MongoRuntimeError {
  4448. constructor(message: string);
  4449. get name(): string;
  4450. }
  4451. /** An error generated when a GridFSStream operation fails to execute.
  4452. *
  4453. * @public
  4454. * @category Error
  4455. */
  4456. export declare class MongoGridFSStreamError extends MongoRuntimeError {
  4457. constructor(message: string);
  4458. get name(): string;
  4459. }
  4460. /**
  4461. * An error generated when the user supplies malformed or unexpected arguments
  4462. * or when a required argument or field is not provided.
  4463. *
  4464. *
  4465. * @public
  4466. * @category Error
  4467. */
  4468. export declare class MongoInvalidArgumentError extends MongoAPIError {
  4469. constructor(message: string);
  4470. get name(): string;
  4471. }
  4472. /**
  4473. * A error generated when the user attempts to authenticate
  4474. * via Kerberos, but fails to connect to the Kerberos client.
  4475. *
  4476. * @public
  4477. * @category Error
  4478. */
  4479. export declare class MongoKerberosError extends MongoRuntimeError {
  4480. constructor(message: string);
  4481. get name(): string;
  4482. }
  4483. /* Excluded from this release type: MongoLoggableComponent */
  4484. /* Excluded from this release type: MongoLogger */
  4485. /* Excluded from this release type: MongoLoggerEnvOptions */
  4486. /* Excluded from this release type: MongoLoggerMongoClientOptions */
  4487. /* Excluded from this release type: MongoLoggerOptions */
  4488. /**
  4489. * An error generated when the user fails to provide authentication credentials before attempting
  4490. * to connect to a mongo server instance.
  4491. *
  4492. *
  4493. * @public
  4494. * @category Error
  4495. */
  4496. export declare class MongoMissingCredentialsError extends MongoAPIError {
  4497. constructor(message: string);
  4498. get name(): string;
  4499. }
  4500. /**
  4501. * An error generated when a required module or dependency is not present in the local environment
  4502. *
  4503. * @public
  4504. * @category Error
  4505. */
  4506. export declare class MongoMissingDependencyError extends MongoAPIError {
  4507. constructor(message: string, { cause }?: {
  4508. cause?: Error;
  4509. });
  4510. get name(): string;
  4511. }
  4512. /**
  4513. * An error indicating an issue with the network, including TCP errors and timeouts.
  4514. * @public
  4515. * @category Error
  4516. */
  4517. export declare class MongoNetworkError extends MongoError {
  4518. /* Excluded from this release type: [kBeforeHandshake] */
  4519. constructor(message: string | Error, options?: MongoNetworkErrorOptions);
  4520. get name(): string;
  4521. }
  4522. /** @public */
  4523. export declare interface MongoNetworkErrorOptions {
  4524. /** Indicates the timeout happened before a connection handshake completed */
  4525. beforeHandshake: boolean;
  4526. }
  4527. /**
  4528. * An error indicating a network timeout occurred
  4529. * @public
  4530. * @category Error
  4531. *
  4532. * @privateRemarks
  4533. * mongodb-client-encryption has a dependency on this error with an instanceof check
  4534. */
  4535. export declare class MongoNetworkTimeoutError extends MongoNetworkError {
  4536. constructor(message: string, options?: MongoNetworkErrorOptions);
  4537. get name(): string;
  4538. }
  4539. /**
  4540. * An error thrown when the user attempts to operate on a database or collection through a MongoClient
  4541. * that has not yet successfully called the "connect" method
  4542. *
  4543. * @public
  4544. * @category Error
  4545. */
  4546. export declare class MongoNotConnectedError extends MongoAPIError {
  4547. constructor(message: string);
  4548. get name(): string;
  4549. }
  4550. /**
  4551. * Parsed Mongo Client Options.
  4552. *
  4553. * User supplied options are documented by `MongoClientOptions`.
  4554. *
  4555. * **NOTE:** The client's options parsing is subject to change to support new features.
  4556. * This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically.
  4557. *
  4558. * Options are sourced from:
  4559. * - connection string
  4560. * - options object passed to the MongoClient constructor
  4561. * - file system (ex. tls settings)
  4562. * - environment variables
  4563. * - DNS SRV records and TXT records
  4564. *
  4565. * Not all options may be present after client construction as some are obtained from asynchronous operations.
  4566. *
  4567. * @public
  4568. */
  4569. export declare interface MongoOptions extends Required<Pick<MongoClientOptions, 'autoEncryption' | 'connectTimeoutMS' | 'directConnection' | 'driverInfo' | 'forceServerObjectId' | 'minHeartbeatFrequencyMS' | 'heartbeatFrequencyMS' | 'keepAlive' | 'keepAliveInitialDelay' | 'localThresholdMS' | 'maxConnecting' | 'maxIdleTimeMS' | 'maxPoolSize' | 'minPoolSize' | 'monitorCommands' | 'noDelay' | 'pkFactory' | 'raw' | 'replicaSet' | 'retryReads' | 'retryWrites' | 'serverSelectionTimeoutMS' | 'socketTimeoutMS' | 'srvMaxHosts' | 'srvServiceName' | 'tlsAllowInvalidCertificates' | 'tlsAllowInvalidHostnames' | 'tlsInsecure' | 'waitQueueTimeoutMS' | 'zlibCompressionLevel'>>, SupportedNodeConnectionOptions {
  4570. appName?: string;
  4571. hosts: HostAddress[];
  4572. srvHost?: string;
  4573. credentials?: MongoCredentials;
  4574. readPreference: ReadPreference;
  4575. readConcern: ReadConcern;
  4576. loadBalanced: boolean;
  4577. serverApi: ServerApi;
  4578. compressors: CompressorName[];
  4579. writeConcern: WriteConcern;
  4580. dbName: string;
  4581. metadata: ClientMetadata;
  4582. /**
  4583. * @deprecated This option will be removed in the next major version.
  4584. */
  4585. autoEncrypter?: AutoEncrypter;
  4586. proxyHost?: string;
  4587. proxyPort?: number;
  4588. proxyUsername?: string;
  4589. proxyPassword?: string;
  4590. /* Excluded from this release type: connectionType */
  4591. /* Excluded from this release type: encrypter */
  4592. /* Excluded from this release type: userSpecifiedAuthSource */
  4593. /* Excluded from this release type: userSpecifiedReplicaSet */
  4594. /**
  4595. * # NOTE ABOUT TLS Options
  4596. *
  4597. * If `tls` is provided as an option, it is equivalent to setting the `ssl` option.
  4598. *
  4599. * NodeJS native TLS options are passed through to the socket and retain their original types.
  4600. *
  4601. * ### Additional options:
  4602. *
  4603. * | nodejs native option | driver spec compliant option name | legacy option name | driver option type |
  4604. * |:----------------------|:----------------------------------------------|:-------------------|:-------------------|
  4605. * | `ca` | `tlsCAFile` | `sslCA` | `string` |
  4606. * | `crl` | `tlsCRLFile` (next major version) | `sslCRL` | `string` |
  4607. * | `cert` | `tlsCertificateFile`, `tlsCertificateKeyFile` | `sslCert` | `string` |
  4608. * | `key` | `tlsCertificateKeyFile` | `sslKey` | `string` |
  4609. * | `passphrase` | `tlsCertificateKeyFilePassword` | `sslPass` | `string` |
  4610. * | `rejectUnauthorized` | `tlsAllowInvalidCertificates` | `sslValidate` | `boolean` |
  4611. * | `checkServerIdentity` | `tlsAllowInvalidHostnames` | N/A | `boolean` |
  4612. * | see note below | `tlsInsecure` | N/A | `boolean` |
  4613. *
  4614. * If `tlsInsecure` is set to `true`, then it will set the node native options `checkServerIdentity`
  4615. * to a no-op and `rejectUnauthorized` to `false`.
  4616. *
  4617. * If `tlsInsecure` is set to `false`, then it will set the node native options `checkServerIdentity`
  4618. * to a no-op and `rejectUnauthorized` to the inverse value of `tlsAllowInvalidCertificates`. If
  4619. * `tlsAllowInvalidCertificates` is not set, then `rejectUnauthorized` will be set to `true`.
  4620. */
  4621. tls: boolean;
  4622. /* Excluded from this release type: __index */
  4623. /* Excluded from this release type: mongoLoggerOptions */
  4624. }
  4625. /**
  4626. * An error used when attempting to parse a value (like a connection string)
  4627. * @public
  4628. * @category Error
  4629. */
  4630. export declare class MongoParseError extends MongoDriverError {
  4631. constructor(message: string);
  4632. get name(): string;
  4633. }
  4634. /**
  4635. * An error generated when the driver encounters unexpected input
  4636. * or reaches an unexpected/invalid internal state
  4637. *
  4638. * @privateRemarks
  4639. * Should **never** be directly instantiated.
  4640. *
  4641. * @public
  4642. * @category Error
  4643. */
  4644. export declare class MongoRuntimeError extends MongoDriverError {
  4645. constructor(message: string);
  4646. get name(): string;
  4647. }
  4648. /**
  4649. * An error generated when an attempt is made to operate
  4650. * on a closed/closing server.
  4651. *
  4652. * @public
  4653. * @category Error
  4654. */
  4655. export declare class MongoServerClosedError extends MongoAPIError {
  4656. constructor(message?: string);
  4657. get name(): string;
  4658. }
  4659. /**
  4660. * An error coming from the mongo server
  4661. *
  4662. * @public
  4663. * @category Error
  4664. */
  4665. export declare class MongoServerError extends MongoError {
  4666. codeName?: string;
  4667. writeConcernError?: Document;
  4668. errInfo?: Document;
  4669. ok?: number;
  4670. [key: string]: any;
  4671. constructor(message: ErrorDescription);
  4672. get name(): string;
  4673. }
  4674. /**
  4675. * An error signifying a client-side server selection error
  4676. * @public
  4677. * @category Error
  4678. */
  4679. export declare class MongoServerSelectionError extends MongoSystemError {
  4680. constructor(message: string, reason: TopologyDescription);
  4681. get name(): string;
  4682. }
  4683. /**
  4684. * An error signifying a general system issue
  4685. * @public
  4686. * @category Error
  4687. */
  4688. export declare class MongoSystemError extends MongoError {
  4689. /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */
  4690. reason?: TopologyDescription;
  4691. constructor(message: string, reason: TopologyDescription);
  4692. get name(): string;
  4693. }
  4694. /**
  4695. * An error thrown when the user calls a function or method not supported on a tailable cursor
  4696. *
  4697. * @public
  4698. * @category Error
  4699. */
  4700. export declare class MongoTailableCursorError extends MongoAPIError {
  4701. constructor(message?: string);
  4702. get name(): string;
  4703. }
  4704. /**
  4705. * An error generated when an attempt is made to operate on a
  4706. * dropped, or otherwise unavailable, database.
  4707. *
  4708. * @public
  4709. * @category Error
  4710. */
  4711. export declare class MongoTopologyClosedError extends MongoAPIError {
  4712. constructor(message?: string);
  4713. get name(): string;
  4714. }
  4715. /**
  4716. * An error generated when the user makes a mistake in the usage of transactions.
  4717. * (e.g. attempting to commit a transaction with a readPreference other than primary)
  4718. *
  4719. * @public
  4720. * @category Error
  4721. */
  4722. export declare class MongoTransactionError extends MongoAPIError {
  4723. constructor(message: string);
  4724. get name(): string;
  4725. }
  4726. /**
  4727. * An error generated when a **parsable** unexpected response comes from the server.
  4728. * This is generally an error where the driver in a state expecting a certain behavior to occur in
  4729. * the next message from MongoDB but it receives something else.
  4730. * This error **does not** represent an issue with wire message formatting.
  4731. *
  4732. * #### Example
  4733. * When an operation fails, it is the driver's job to retry it. It must perform serverSelection
  4734. * again to make sure that it attempts the operation against a server in a good state. If server
  4735. * selection returns a server that does not support retryable operations, this error is used.
  4736. * This scenario is unlikely as retryable support would also have been determined on the first attempt
  4737. * but it is possible the state change could report a selectable server that does not support retries.
  4738. *
  4739. * @public
  4740. * @category Error
  4741. */
  4742. export declare class MongoUnexpectedServerResponseError extends MongoRuntimeError {
  4743. constructor(message: string);
  4744. get name(): string;
  4745. }
  4746. /**
  4747. * An error thrown when the server reports a writeConcernError
  4748. * @public
  4749. * @category Error
  4750. */
  4751. export declare class MongoWriteConcernError extends MongoServerError {
  4752. /** The result document (provided if ok: 1) */
  4753. result?: Document;
  4754. constructor(message: ErrorDescription, result?: Document);
  4755. get name(): string;
  4756. }
  4757. /* Excluded from this release type: Monitor */
  4758. /** @public */
  4759. export declare type MonitorEvents = {
  4760. serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
  4761. serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
  4762. serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
  4763. resetServer(error?: MongoError): void;
  4764. resetConnectionPool(): void;
  4765. close(): void;
  4766. } & EventEmitterWithState;
  4767. /* Excluded from this release type: MonitorInterval */
  4768. /* Excluded from this release type: MonitorIntervalOptions */
  4769. /** @public */
  4770. export declare interface MonitorOptions extends Omit<ConnectionOptions, 'id' | 'generation' | 'hostAddress'> {
  4771. connectTimeoutMS: number;
  4772. heartbeatFrequencyMS: number;
  4773. minHeartbeatFrequencyMS: number;
  4774. }
  4775. /* Excluded from this release type: MonitorPrivate */
  4776. /* Excluded from this release type: Msg */
  4777. /**
  4778. * @public
  4779. * returns tuple of strings (keys to be joined on '.') that represent every path into a schema
  4780. * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
  4781. *
  4782. * @remarks
  4783. * Through testing we determined that a depth of 8 is safe for the typescript compiler
  4784. * and provides reasonable compilation times. This number is otherwise not special and
  4785. * should be changed if issues are found with this level of checking. Beyond this
  4786. * depth any helpers that make use of NestedPaths should devolve to not asserting any
  4787. * type safety on the input.
  4788. */
  4789. export declare type NestedPaths<Type, Depth extends number[]> = Depth['length'] extends 8 ? [] : Type extends string | number | bigint | boolean | Date | RegExp | Buffer | Uint8Array | ((...args: any[]) => any) | {
  4790. _bsontype: string;
  4791. } ? [] : Type extends ReadonlyArray<infer ArrayType> ? [] | [number, ...NestedPaths<ArrayType, [...Depth, 1]>] : Type extends Map<string, any> ? [string] : Type extends object ? {
  4792. [Key in Extract<keyof Type, string>]: Type[Key] extends Type ? [Key] : Type extends Type[Key] ? [Key] : Type[Key] extends ReadonlyArray<infer ArrayType> ? Type extends ArrayType ? [Key] : ArrayType extends Type ? [Key] : [
  4793. Key,
  4794. ...NestedPaths<Type[Key], [...Depth, 1]>
  4795. ] : // child is not structured the same as the parent
  4796. [
  4797. Key,
  4798. ...NestedPaths<Type[Key], [...Depth, 1]>
  4799. ] | [Key];
  4800. }[Extract<keyof Type, string>] : [];
  4801. /**
  4802. * @public
  4803. * returns keys (strings) for every path into a schema with a value of type
  4804. * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
  4805. */
  4806. export declare type NestedPathsOfType<TSchema, Type> = KeysOfAType<{
  4807. [Property in Join<NestedPaths<TSchema, []>, '.'>]: PropertyType<TSchema, Property>;
  4808. }, Type>;
  4809. /**
  4810. * @public
  4811. * A type that extends Document but forbids anything that "looks like" an object id.
  4812. */
  4813. export declare type NonObjectIdLikeDocument = {
  4814. [key in keyof ObjectIdLike]?: never;
  4815. } & Document;
  4816. /** It avoids using fields with not acceptable types @public */
  4817. export declare type NotAcceptedFields<TSchema, FieldType> = {
  4818. readonly [key in KeysOfOtherType<TSchema, FieldType>]?: never;
  4819. };
  4820. /** @public */
  4821. export declare type NumericType = IntegerType | Decimal128 | Double;
  4822. export { ObjectId }
  4823. /**
  4824. * @public
  4825. * @experimental
  4826. */
  4827. export declare interface OIDCCallbackContext {
  4828. refreshToken?: string;
  4829. timeoutSeconds?: number;
  4830. timeoutContext?: AbortSignal;
  4831. version: number;
  4832. }
  4833. /**
  4834. * @public
  4835. * @experimental
  4836. */
  4837. export declare type OIDCRefreshFunction = (info: IdPServerInfo, context: OIDCCallbackContext) => Promise<IdPServerResponse>;
  4838. /**
  4839. * @public
  4840. * @experimental
  4841. */
  4842. export declare type OIDCRequestFunction = (info: IdPServerInfo, context: OIDCCallbackContext) => Promise<IdPServerResponse>;
  4843. /** @public */
  4844. export declare type OneOrMore<T> = T | ReadonlyArray<T>;
  4845. /** @public */
  4846. export declare type OnlyFieldsOfType<TSchema, FieldType = any, AssignableType = FieldType> = IsAny<TSchema[keyof TSchema], Record<string, FieldType>, AcceptedFields<TSchema, FieldType, AssignableType> & NotAcceptedFields<TSchema, FieldType> & Record<string, AssignableType>>;
  4847. /* Excluded from this release type: OperationDescription */
  4848. /** @public */
  4849. export declare interface OperationOptions extends BSONSerializeOptions {
  4850. /** Specify ClientSession for this command */
  4851. session?: ClientSession;
  4852. willRetryWrite?: boolean;
  4853. /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */
  4854. readPreference?: ReadPreferenceLike;
  4855. /* Excluded from this release type: bypassPinningCheck */
  4856. omitReadPreference?: boolean;
  4857. }
  4858. /* Excluded from this release type: OperationParent */
  4859. /**
  4860. * Represents a specific point in time on a server. Can be retrieved by using `db.command()`
  4861. * @public
  4862. * @see https://www.mongodb.com/docs/manual/reference/method/db.runCommand/#response
  4863. */
  4864. export declare type OperationTime = Timestamp;
  4865. /* Excluded from this release type: OpMsgOptions */
  4866. /* Excluded from this release type: OpQueryOptions */
  4867. /* Excluded from this release type: OpResponseOptions */
  4868. /**
  4869. * Add an optional _id field to an object shaped type
  4870. * @public
  4871. */
  4872. export declare type OptionalId<TSchema> = EnhancedOmit<TSchema, '_id'> & {
  4873. _id?: InferIdType<TSchema>;
  4874. };
  4875. /**
  4876. * Adds an optional _id field to an object shaped type, unless the _id field is required on that type.
  4877. * In the case _id is required, this method continues to require_id.
  4878. *
  4879. * @public
  4880. *
  4881. * @privateRemarks
  4882. * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask
  4883. * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?"
  4884. * we instead ask "Does ObjectId look like (have the same shape) as the _id?"
  4885. */
  4886. export declare type OptionalUnlessRequiredId<TSchema> = TSchema extends {
  4887. _id: any;
  4888. } ? TSchema : OptionalId<TSchema>;
  4889. /** @public */
  4890. export declare class OrderedBulkOperation extends BulkOperationBase {
  4891. /* Excluded from this release type: __constructor */
  4892. addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
  4893. }
  4894. /** @public */
  4895. export declare interface PkFactory {
  4896. createPk(): any;
  4897. }
  4898. /* Excluded from this release type: PoolState */
  4899. /** @public */
  4900. export declare const ProfilingLevel: Readonly<{
  4901. readonly off: "off";
  4902. readonly slowOnly: "slow_only";
  4903. readonly all: "all";
  4904. }>;
  4905. /** @public */
  4906. export declare type ProfilingLevel = (typeof ProfilingLevel)[keyof typeof ProfilingLevel];
  4907. /** @public */
  4908. export declare type ProfilingLevelOptions = CommandOperationOptions;
  4909. /** @public */
  4910. export declare type PropertyType<Type, Property extends string> = string extends Property ? unknown : Property extends keyof Type ? Type[Property] : Property extends `${number}` ? Type extends ReadonlyArray<infer ArrayType> ? ArrayType : unknown : Property extends `${infer Key}.${infer Rest}` ? Key extends `${number}` ? Type extends ReadonlyArray<infer ArrayType> ? PropertyType<ArrayType, Rest> : unknown : Key extends keyof Type ? Type[Key] extends Map<string, infer MapType> ? MapType : PropertyType<Type[Key], Rest> : unknown : unknown;
  4911. /** @public */
  4912. export declare interface ProxyOptions {
  4913. proxyHost?: string;
  4914. proxyPort?: number;
  4915. proxyUsername?: string;
  4916. proxyPassword?: string;
  4917. }
  4918. /** @public */
  4919. export declare type PullAllOperator<TSchema> = ({
  4920. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: TSchema[key];
  4921. } & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
  4922. readonly [key: string]: ReadonlyArray<any>;
  4923. };
  4924. /** @public */
  4925. export declare type PullOperator<TSchema> = ({
  4926. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: Partial<Flatten<TSchema[key]>> | FilterOperations<Flatten<TSchema[key]>>;
  4927. } & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
  4928. readonly [key: string]: FilterOperators<any> | any;
  4929. };
  4930. /** @public */
  4931. export declare type PushOperator<TSchema> = ({
  4932. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: Flatten<TSchema[key]> | ArrayOperator<Array<Flatten<TSchema[key]>>>;
  4933. } & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
  4934. readonly [key: string]: ArrayOperator<any> | any;
  4935. };
  4936. /* Excluded from this release type: Query */
  4937. /**
  4938. * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
  4939. * of the data read from replica sets and replica set shards.
  4940. * @public
  4941. *
  4942. * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html
  4943. */
  4944. export declare class ReadConcern {
  4945. level: ReadConcernLevel | string;
  4946. /** Constructs a ReadConcern from the read concern level.*/
  4947. constructor(level: ReadConcernLevel);
  4948. /**
  4949. * Construct a ReadConcern given an options object.
  4950. *
  4951. * @param options - The options object from which to extract the write concern.
  4952. */
  4953. static fromOptions(options?: {
  4954. readConcern?: ReadConcernLike;
  4955. level?: ReadConcernLevel;
  4956. }): ReadConcern | undefined;
  4957. static get MAJORITY(): 'majority';
  4958. static get AVAILABLE(): 'available';
  4959. static get LINEARIZABLE(): 'linearizable';
  4960. static get SNAPSHOT(): 'snapshot';
  4961. toJSON(): Document;
  4962. }
  4963. /** @public */
  4964. export declare const ReadConcernLevel: Readonly<{
  4965. readonly local: "local";
  4966. readonly majority: "majority";
  4967. readonly linearizable: "linearizable";
  4968. readonly available: "available";
  4969. readonly snapshot: "snapshot";
  4970. }>;
  4971. /** @public */
  4972. export declare type ReadConcernLevel = (typeof ReadConcernLevel)[keyof typeof ReadConcernLevel];
  4973. /** @public */
  4974. export declare type ReadConcernLike = ReadConcern | {
  4975. level: ReadConcernLevel;
  4976. } | ReadConcernLevel;
  4977. /**
  4978. * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is
  4979. * used to construct connections.
  4980. * @public
  4981. *
  4982. * @see https://www.mongodb.com/docs/manual/core/read-preference/
  4983. */
  4984. export declare class ReadPreference {
  4985. mode: ReadPreferenceMode;
  4986. tags?: TagSet[];
  4987. hedge?: HedgeOptions;
  4988. maxStalenessSeconds?: number;
  4989. minWireVersion?: number;
  4990. static PRIMARY: "primary";
  4991. static PRIMARY_PREFERRED: "primaryPreferred";
  4992. static SECONDARY: "secondary";
  4993. static SECONDARY_PREFERRED: "secondaryPreferred";
  4994. static NEAREST: "nearest";
  4995. static primary: ReadPreference;
  4996. static primaryPreferred: ReadPreference;
  4997. static secondary: ReadPreference;
  4998. static secondaryPreferred: ReadPreference;
  4999. static nearest: ReadPreference;
  5000. /**
  5001. * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
  5002. * @param tags - A tag set used to target reads to members with the specified tag(s). tagSet is not available if using read preference mode primary.
  5003. * @param options - Additional read preference options
  5004. */
  5005. constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions);
  5006. get preference(): ReadPreferenceMode;
  5007. static fromString(mode: string): ReadPreference;
  5008. /**
  5009. * Construct a ReadPreference given an options object.
  5010. *
  5011. * @param options - The options object from which to extract the read preference.
  5012. */
  5013. static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined;
  5014. /**
  5015. * Replaces options.readPreference with a ReadPreference instance
  5016. */
  5017. static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions;
  5018. /**
  5019. * Validate if a mode is legal
  5020. *
  5021. * @param mode - The string representing the read preference mode.
  5022. */
  5023. static isValid(mode: string): boolean;
  5024. /**
  5025. * Validate if a mode is legal
  5026. *
  5027. * @param mode - The string representing the read preference mode.
  5028. */
  5029. isValid(mode?: string): boolean;
  5030. /**
  5031. * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire
  5032. * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query
  5033. */
  5034. secondaryOk(): boolean;
  5035. /**
  5036. * Check if the two ReadPreferences are equivalent
  5037. *
  5038. * @param readPreference - The read preference with which to check equality
  5039. */
  5040. equals(readPreference: ReadPreference): boolean;
  5041. /** Return JSON representation */
  5042. toJSON(): Document;
  5043. }
  5044. /** @public */
  5045. export declare interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions {
  5046. session?: ClientSession;
  5047. readPreferenceTags?: TagSet[];
  5048. hedge?: HedgeOptions;
  5049. }
  5050. /** @public */
  5051. export declare type ReadPreferenceLike = ReadPreference | ReadPreferenceMode;
  5052. /** @public */
  5053. export declare interface ReadPreferenceLikeOptions extends ReadPreferenceOptions {
  5054. readPreference?: ReadPreferenceLike | {
  5055. mode?: ReadPreferenceMode;
  5056. preference?: ReadPreferenceMode;
  5057. tags?: TagSet[];
  5058. maxStalenessSeconds?: number;
  5059. };
  5060. }
  5061. /** @public */
  5062. export declare const ReadPreferenceMode: Readonly<{
  5063. readonly primary: "primary";
  5064. readonly primaryPreferred: "primaryPreferred";
  5065. readonly secondary: "secondary";
  5066. readonly secondaryPreferred: "secondaryPreferred";
  5067. readonly nearest: "nearest";
  5068. }>;
  5069. /** @public */
  5070. export declare type ReadPreferenceMode = (typeof ReadPreferenceMode)[keyof typeof ReadPreferenceMode];
  5071. /** @public */
  5072. export declare interface ReadPreferenceOptions {
  5073. /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/
  5074. maxStalenessSeconds?: number;
  5075. /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */
  5076. hedge?: HedgeOptions;
  5077. }
  5078. /** @public */
  5079. export declare type RegExpOrString<T> = T extends string ? BSONRegExp | RegExp | T : T;
  5080. /** @public */
  5081. export declare type RemoveUserOptions = CommandOperationOptions;
  5082. /** @public */
  5083. export declare interface RenameOptions extends CommandOperationOptions {
  5084. /** Drop the target name collection if it previously exists. */
  5085. dropTarget?: boolean;
  5086. /** Unclear */
  5087. new_collection?: boolean;
  5088. }
  5089. /** @public */
  5090. export declare interface ReplaceOneModel<TSchema extends Document = Document> {
  5091. /** The filter to limit the replaced document. */
  5092. filter: Filter<TSchema>;
  5093. /** The document with which to replace the matched document. */
  5094. replacement: WithoutId<TSchema>;
  5095. /** Specifies a collation. */
  5096. collation?: CollationOptions;
  5097. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  5098. hint?: Hint;
  5099. /** When true, creates a new document if no document matches the query. */
  5100. upsert?: boolean;
  5101. }
  5102. /** @public */
  5103. export declare interface ReplaceOptions extends CommandOperationOptions {
  5104. /** If true, allows the write to opt-out of document level validation */
  5105. bypassDocumentValidation?: boolean;
  5106. /** Specifies a collation */
  5107. collation?: CollationOptions;
  5108. /** Specify that the update query should only consider plans using the hinted index */
  5109. hint?: string | Document;
  5110. /** When true, creates a new document if no document matches the query */
  5111. upsert?: boolean;
  5112. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  5113. let?: Document;
  5114. }
  5115. /* Excluded from this release type: Response */
  5116. /**
  5117. * @public
  5118. * @deprecated Please use the ChangeStreamCursorOptions type instead.
  5119. */
  5120. export declare interface ResumeOptions {
  5121. startAtOperationTime?: Timestamp;
  5122. batchSize?: number;
  5123. maxAwaitTimeMS?: number;
  5124. collation?: CollationOptions;
  5125. readPreference?: ReadPreference;
  5126. resumeAfter?: ResumeToken;
  5127. startAfter?: ResumeToken;
  5128. fullDocument?: string;
  5129. }
  5130. /**
  5131. * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server.
  5132. * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume
  5133. * @public
  5134. */
  5135. export declare type ResumeToken = unknown;
  5136. /** @public */
  5137. export declare const ReturnDocument: Readonly<{
  5138. readonly BEFORE: "before";
  5139. readonly AFTER: "after";
  5140. }>;
  5141. /** @public */
  5142. export declare type ReturnDocument = (typeof ReturnDocument)[keyof typeof ReturnDocument];
  5143. /**
  5144. * @public
  5145. * @deprecated Use the createUser command directly instead.
  5146. */
  5147. export declare interface RoleSpecification {
  5148. /**
  5149. * A role grants privileges to perform sets of actions on defined resources.
  5150. * A given role applies to the database on which it is defined and can grant access down to a collection level of granularity.
  5151. */
  5152. role: string;
  5153. /** The database this user's role should effect. */
  5154. db: string;
  5155. }
  5156. /** @public */
  5157. export declare interface RootFilterOperators<TSchema> extends Document {
  5158. $and?: Filter<TSchema>[];
  5159. $nor?: Filter<TSchema>[];
  5160. $or?: Filter<TSchema>[];
  5161. $text?: {
  5162. $search: string;
  5163. $language?: string;
  5164. $caseSensitive?: boolean;
  5165. $diacriticSensitive?: boolean;
  5166. };
  5167. $where?: string | ((this: TSchema) => boolean);
  5168. $comment?: string | Document;
  5169. }
  5170. /* Excluded from this release type: RTTPinger */
  5171. /* Excluded from this release type: RTTPingerOptions */
  5172. /** @public */
  5173. export declare class RunCommandCursor extends AbstractCursor {
  5174. readonly command: Readonly<Record<string, any>>;
  5175. readonly getMoreOptions: {
  5176. comment?: any;
  5177. maxAwaitTimeMS?: number;
  5178. batchSize?: number;
  5179. };
  5180. /**
  5181. * Controls the `getMore.comment` field
  5182. * @param comment - any BSON value
  5183. */
  5184. setComment(comment: any): this;
  5185. /**
  5186. * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await
  5187. * @param maxTimeMS - the number of milliseconds to wait for new data
  5188. */
  5189. setMaxTimeMS(maxTimeMS: number): this;
  5190. /**
  5191. * Controls the `getMore.batchSize` field
  5192. * @param maxTimeMS - the number documents to return in the `nextBatch`
  5193. */
  5194. setBatchSize(batchSize: number): this;
  5195. /** Unsupported for RunCommandCursor */
  5196. clone(): never;
  5197. /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */
  5198. withReadConcern(_: ReadConcernLike): never;
  5199. /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */
  5200. addCursorFlag(_: string, __: boolean): never;
  5201. /** Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document */
  5202. maxTimeMS(_: number): never;
  5203. /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */
  5204. batchSize(_: number): never;
  5205. /* Excluded from this release type: db */
  5206. /* Excluded from this release type: __constructor */
  5207. /* Excluded from this release type: _initialize */
  5208. /* Excluded from this release type: _getMore */
  5209. }
  5210. /** @public */
  5211. export declare type RunCommandOptions = {
  5212. /** Specify ClientSession for this command */
  5213. session?: ClientSession;
  5214. /** The read preference */
  5215. readPreference?: ReadPreferenceLike;
  5216. /** @deprecated This is an internal option that has undefined behavior for this API */
  5217. willRetryWrite?: any;
  5218. /** @deprecated This is an internal option that has undefined behavior for this API */
  5219. omitReadPreference?: any;
  5220. /** @deprecated This is an internal option that has undefined behavior for this API */
  5221. writeConcern?: any;
  5222. /** @deprecated This is an internal option that has undefined behavior for this API */
  5223. explain?: any;
  5224. /** @deprecated This is an internal option that has undefined behavior for this API */
  5225. readConcern?: any;
  5226. /** @deprecated This is an internal option that has undefined behavior for this API */
  5227. collation?: any;
  5228. /** @deprecated This is an internal option that has undefined behavior for this API */
  5229. maxTimeMS?: any;
  5230. /** @deprecated This is an internal option that has undefined behavior for this API */
  5231. comment?: any;
  5232. /** @deprecated This is an internal option that has undefined behavior for this API */
  5233. retryWrites?: any;
  5234. /** @deprecated This is an internal option that has undefined behavior for this API */
  5235. dbName?: any;
  5236. /** @deprecated This is an internal option that has undefined behavior for this API */
  5237. authdb?: any;
  5238. /** @deprecated This is an internal option that has undefined behavior for this API */
  5239. noResponse?: any;
  5240. /* Excluded from this release type: bypassPinningCheck */
  5241. } & BSONSerializeOptions;
  5242. /** @public */
  5243. export declare type RunCursorCommandOptions = {
  5244. readPreference?: ReadPreferenceLike;
  5245. session?: ClientSession;
  5246. } & BSONSerializeOptions;
  5247. /** @public */
  5248. export declare type SchemaMember<T, V> = {
  5249. [P in keyof T]?: V;
  5250. } | {
  5251. [key: string]: V;
  5252. };
  5253. /**
  5254. * @public
  5255. */
  5256. export declare interface SearchIndexDescription {
  5257. /** The name of the index. */
  5258. name?: string;
  5259. /** The index definition. */
  5260. definition: Document;
  5261. }
  5262. /** @public */
  5263. export declare interface SelectServerOptions {
  5264. readPreference?: ReadPreferenceLike;
  5265. /** How long to block for server selection before throwing an error */
  5266. serverSelectionTimeoutMS?: number;
  5267. session?: ClientSession;
  5268. }
  5269. export { serialize }
  5270. /* Excluded from this release type: Server */
  5271. /** @public */
  5272. export declare interface ServerApi {
  5273. version: ServerApiVersion;
  5274. strict?: boolean;
  5275. deprecationErrors?: boolean;
  5276. }
  5277. /** @public */
  5278. export declare const ServerApiVersion: Readonly<{
  5279. readonly v1: "1";
  5280. }>;
  5281. /** @public */
  5282. export declare type ServerApiVersion = (typeof ServerApiVersion)[keyof typeof ServerApiVersion];
  5283. /** @public */
  5284. export declare class ServerCapabilities {
  5285. maxWireVersion: number;
  5286. minWireVersion: number;
  5287. constructor(hello: Document);
  5288. get hasAggregationCursor(): boolean;
  5289. get hasWriteCommands(): boolean;
  5290. get hasTextSearch(): boolean;
  5291. get hasAuthCommands(): boolean;
  5292. get hasListCollectionsCommand(): boolean;
  5293. get hasListIndexesCommand(): boolean;
  5294. get supportsSnapshotReads(): boolean;
  5295. get commandsTakeWriteConcern(): boolean;
  5296. get commandsTakeCollation(): boolean;
  5297. }
  5298. /**
  5299. * Emitted when server is closed.
  5300. * @public
  5301. * @category Event
  5302. */
  5303. export declare class ServerClosedEvent {
  5304. /** A unique identifier for the topology */
  5305. topologyId: number;
  5306. /** The address (host/port pair) of the server */
  5307. address: string;
  5308. /* Excluded from this release type: __constructor */
  5309. }
  5310. /**
  5311. * The client's view of a single server, based on the most recent hello outcome.
  5312. *
  5313. * Internal type, not meant to be directly instantiated
  5314. * @public
  5315. */
  5316. export declare class ServerDescription {
  5317. address: string;
  5318. type: ServerType;
  5319. hosts: string[];
  5320. passives: string[];
  5321. arbiters: string[];
  5322. tags: TagSet;
  5323. error: MongoError | null;
  5324. topologyVersion: TopologyVersion | null;
  5325. minWireVersion: number;
  5326. maxWireVersion: number;
  5327. roundTripTime: number;
  5328. lastUpdateTime: number;
  5329. lastWriteDate: number;
  5330. me: string | null;
  5331. primary: string | null;
  5332. setName: string | null;
  5333. setVersion: number | null;
  5334. electionId: ObjectId | null;
  5335. logicalSessionTimeoutMinutes: number | null;
  5336. $clusterTime?: ClusterTime;
  5337. /* Excluded from this release type: __constructor */
  5338. get hostAddress(): HostAddress;
  5339. get allHosts(): string[];
  5340. /** Is this server available for reads*/
  5341. get isReadable(): boolean;
  5342. /** Is this server data bearing */
  5343. get isDataBearing(): boolean;
  5344. /** Is this server available for writes */
  5345. get isWritable(): boolean;
  5346. get host(): string;
  5347. get port(): number;
  5348. /**
  5349. * Determines if another `ServerDescription` is equal to this one per the rules defined
  5350. * in the {@link https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst#serverdescription|SDAM spec}
  5351. */
  5352. equals(other?: ServerDescription | null): boolean;
  5353. }
  5354. /**
  5355. * Emitted when server description changes, but does NOT include changes to the RTT.
  5356. * @public
  5357. * @category Event
  5358. */
  5359. export declare class ServerDescriptionChangedEvent {
  5360. /** A unique identifier for the topology */
  5361. topologyId: number;
  5362. /** The address (host/port pair) of the server */
  5363. address: string;
  5364. /** The previous server description */
  5365. previousDescription: ServerDescription;
  5366. /** The new server description */
  5367. newDescription: ServerDescription;
  5368. /* Excluded from this release type: __constructor */
  5369. }
  5370. /* Excluded from this release type: ServerDescriptionOptions */
  5371. /** @public */
  5372. export declare type ServerEvents = {
  5373. serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
  5374. serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
  5375. serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
  5376. /* Excluded from this release type: connect */
  5377. descriptionReceived(description: ServerDescription): void;
  5378. closed(): void;
  5379. ended(): void;
  5380. } & ConnectionPoolEvents & EventEmitterWithState;
  5381. /**
  5382. * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception.
  5383. * @public
  5384. * @category Event
  5385. */
  5386. export declare class ServerHeartbeatFailedEvent {
  5387. /** The connection id for the command */
  5388. connectionId: string;
  5389. /** The execution time of the event in ms */
  5390. duration: number;
  5391. /** The command failure */
  5392. failure: Error;
  5393. /* Excluded from this release type: __constructor */
  5394. }
  5395. /**
  5396. * Emitted when the server monitor’s hello command is started - immediately before
  5397. * the hello command is serialized into raw BSON and written to the socket.
  5398. *
  5399. * @public
  5400. * @category Event
  5401. */
  5402. export declare class ServerHeartbeatStartedEvent {
  5403. /** The connection id for the command */
  5404. connectionId: string;
  5405. /* Excluded from this release type: __constructor */
  5406. }
  5407. /**
  5408. * Emitted when the server monitor’s hello succeeds.
  5409. * @public
  5410. * @category Event
  5411. */
  5412. export declare class ServerHeartbeatSucceededEvent {
  5413. /** The connection id for the command */
  5414. connectionId: string;
  5415. /** The execution time of the event in ms */
  5416. duration: number;
  5417. /** The command reply */
  5418. reply: Document;
  5419. /* Excluded from this release type: __constructor */
  5420. }
  5421. /**
  5422. * Emitted when server is initialized.
  5423. * @public
  5424. * @category Event
  5425. */
  5426. export declare class ServerOpeningEvent {
  5427. /** A unique identifier for the topology */
  5428. topologyId: number;
  5429. /** The address (host/port pair) of the server */
  5430. address: string;
  5431. /* Excluded from this release type: __constructor */
  5432. }
  5433. /* Excluded from this release type: ServerOptions */
  5434. /* Excluded from this release type: ServerPrivate */
  5435. /* Excluded from this release type: ServerSelectionCallback */
  5436. /* Excluded from this release type: ServerSelectionRequest */
  5437. /* Excluded from this release type: ServerSelector */
  5438. /**
  5439. * Reflects the existence of a session on the server. Can be reused by the session pool.
  5440. * WARNING: not meant to be instantiated directly. For internal use only.
  5441. * @public
  5442. */
  5443. export declare class ServerSession {
  5444. id: ServerSessionId;
  5445. lastUse: number;
  5446. txnNumber: number;
  5447. isDirty: boolean;
  5448. /* Excluded from this release type: __constructor */
  5449. /**
  5450. * Determines if the server session has timed out.
  5451. *
  5452. * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
  5453. */
  5454. hasTimedOut(sessionTimeoutMinutes: number): boolean;
  5455. /* Excluded from this release type: clone */
  5456. }
  5457. /** @public */
  5458. export declare type ServerSessionId = {
  5459. id: Binary;
  5460. };
  5461. /* Excluded from this release type: ServerSessionPool */
  5462. /**
  5463. * An enumeration of server types we know about
  5464. * @public
  5465. */
  5466. export declare const ServerType: Readonly<{
  5467. readonly Standalone: "Standalone";
  5468. readonly Mongos: "Mongos";
  5469. readonly PossiblePrimary: "PossiblePrimary";
  5470. readonly RSPrimary: "RSPrimary";
  5471. readonly RSSecondary: "RSSecondary";
  5472. readonly RSArbiter: "RSArbiter";
  5473. readonly RSOther: "RSOther";
  5474. readonly RSGhost: "RSGhost";
  5475. readonly Unknown: "Unknown";
  5476. readonly LoadBalancer: "LoadBalancer";
  5477. }>;
  5478. /** @public */
  5479. export declare type ServerType = (typeof ServerType)[keyof typeof ServerType];
  5480. /** @public */
  5481. export declare type SetFields<TSchema> = ({
  5482. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any> | undefined>]?: OptionalId<Flatten<TSchema[key]>> | AddToSetOperators<Array<OptionalId<Flatten<TSchema[key]>>>>;
  5483. } & NotAcceptedFields<TSchema, ReadonlyArray<any> | undefined>) & {
  5484. readonly [key: string]: AddToSetOperators<any> | any;
  5485. };
  5486. /** @public */
  5487. export declare type SetProfilingLevelOptions = CommandOperationOptions;
  5488. /* Excluded from this release type: SeverityLevel */
  5489. /** @public */
  5490. export declare type Sort = string | Exclude<SortDirection, {
  5491. $meta: string;
  5492. }> | string[] | {
  5493. [key: string]: SortDirection;
  5494. } | Map<string, SortDirection> | [string, SortDirection][] | [string, SortDirection];
  5495. /** @public */
  5496. export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | {
  5497. $meta: string;
  5498. };
  5499. /* Excluded from this release type: SortDirectionForCmd */
  5500. /* Excluded from this release type: SortForCmd */
  5501. /* Excluded from this release type: SrvPoller */
  5502. /* Excluded from this release type: SrvPollerEvents */
  5503. /* Excluded from this release type: SrvPollerOptions */
  5504. /* Excluded from this release type: SrvPollingEvent */
  5505. /** @public */
  5506. export declare type Stream = Socket | TLSSocket;
  5507. /** @public */
  5508. export declare class StreamDescription {
  5509. address: string;
  5510. type: string;
  5511. minWireVersion?: number;
  5512. maxWireVersion?: number;
  5513. maxBsonObjectSize: number;
  5514. maxMessageSizeBytes: number;
  5515. maxWriteBatchSize: number;
  5516. compressors: CompressorName[];
  5517. compressor?: CompressorName;
  5518. logicalSessionTimeoutMinutes?: number;
  5519. loadBalanced: boolean;
  5520. __nodejs_mock_server__?: boolean;
  5521. zlibCompressionLevel?: number;
  5522. constructor(address: string, options?: StreamDescriptionOptions);
  5523. receiveResponse(response: Document | null): void;
  5524. }
  5525. /** @public */
  5526. export declare interface StreamDescriptionOptions {
  5527. compressors?: CompressorName[];
  5528. logicalSessionTimeoutMinutes?: number;
  5529. loadBalanced: boolean;
  5530. }
  5531. /**
  5532. * @public
  5533. * @experimental
  5534. */
  5535. export declare type StrictFilter<TSchema> = Partial<TSchema> | ({
  5536. [Property in Join<NestedPaths<WithId<TSchema>, []>, '.'>]?: Condition<PropertyType<WithId<TSchema>, Property>>;
  5537. } & RootFilterOperators<WithId<TSchema>>);
  5538. /**
  5539. * @public
  5540. * @experimental
  5541. */
  5542. export declare type StrictMatchKeysAndValues<TSchema> = Readonly<{
  5543. [Property in Join<NestedPaths<TSchema, []>, '.'>]?: PropertyType<TSchema, Property>;
  5544. } & {
  5545. [Property in `${NestedPathsOfType<TSchema, any[]>}.$${`[${string}]` | ''}`]?: ArrayElement<PropertyType<TSchema, Property extends `${infer Key}.$${string}` ? Key : never>>;
  5546. } & {
  5547. [Property in `${NestedPathsOfType<TSchema, Record<string, any>[]>}.$${`[${string}]` | ''}.${string}`]?: any;
  5548. } & Document>;
  5549. /**
  5550. * @public
  5551. * @experimental
  5552. */
  5553. export declare type StrictUpdateFilter<TSchema> = {
  5554. $currentDate?: OnlyFieldsOfType<TSchema, Date | Timestamp, true | {
  5555. $type: 'date' | 'timestamp';
  5556. }>;
  5557. $inc?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  5558. $min?: StrictMatchKeysAndValues<TSchema>;
  5559. $max?: StrictMatchKeysAndValues<TSchema>;
  5560. $mul?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  5561. $rename?: Record<string, string>;
  5562. $set?: StrictMatchKeysAndValues<TSchema>;
  5563. $setOnInsert?: StrictMatchKeysAndValues<TSchema>;
  5564. $unset?: OnlyFieldsOfType<TSchema, any, '' | true | 1>;
  5565. $addToSet?: SetFields<TSchema>;
  5566. $pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
  5567. $pull?: PullOperator<TSchema>;
  5568. $push?: PushOperator<TSchema>;
  5569. $pullAll?: PullAllOperator<TSchema>;
  5570. $bit?: OnlyFieldsOfType<TSchema, NumericType | undefined, {
  5571. and: IntegerType;
  5572. } | {
  5573. or: IntegerType;
  5574. } | {
  5575. xor: IntegerType;
  5576. }>;
  5577. } & Document;
  5578. /** @public */
  5579. export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & SupportedTLSSocketOptions & SupportedSocketOptions;
  5580. /** @public */
  5581. export declare type SupportedSocketOptions = Pick<TcpNetConnectOpts, (typeof LEGAL_TCP_SOCKET_OPTIONS)[number]>;
  5582. /** @public */
  5583. export declare type SupportedTLSConnectionOptions = Pick<ConnectionOptions_2, Extract<keyof ConnectionOptions_2, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>>;
  5584. /** @public */
  5585. export declare type SupportedTLSSocketOptions = Pick<TLSSocketOptions, Extract<keyof TLSSocketOptions, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>>;
  5586. /** @public */
  5587. export declare type TagSet = {
  5588. [key: string]: string;
  5589. };
  5590. /* Excluded from this release type: TimerQueue */
  5591. /** @public
  5592. * Configuration options for timeseries collections
  5593. * @see https://www.mongodb.com/docs/manual/core/timeseries-collections/
  5594. */
  5595. export declare interface TimeSeriesCollectionOptions extends Document {
  5596. timeField: string;
  5597. metaField?: string;
  5598. granularity?: 'seconds' | 'minutes' | 'hours' | string;
  5599. bucketMaxSpanSeconds?: number;
  5600. bucketRoundingSeconds?: number;
  5601. }
  5602. export { Timestamp }
  5603. /* Excluded from this release type: Topology */
  5604. /**
  5605. * Emitted when topology is closed.
  5606. * @public
  5607. * @category Event
  5608. */
  5609. export declare class TopologyClosedEvent {
  5610. /** A unique identifier for the topology */
  5611. topologyId: number;
  5612. /* Excluded from this release type: __constructor */
  5613. }
  5614. /**
  5615. * Representation of a deployment of servers
  5616. * @public
  5617. */
  5618. export declare class TopologyDescription {
  5619. type: TopologyType;
  5620. setName: string | null;
  5621. maxSetVersion: number | null;
  5622. maxElectionId: ObjectId | null;
  5623. servers: Map<string, ServerDescription>;
  5624. stale: boolean;
  5625. compatible: boolean;
  5626. compatibilityError?: string;
  5627. logicalSessionTimeoutMinutes: number | null;
  5628. heartbeatFrequencyMS: number;
  5629. localThresholdMS: number;
  5630. commonWireVersion: number;
  5631. /**
  5632. * Create a TopologyDescription
  5633. */
  5634. constructor(topologyType: TopologyType, serverDescriptions?: Map<string, ServerDescription> | null, setName?: string | null, maxSetVersion?: number | null, maxElectionId?: ObjectId | null, commonWireVersion?: number | null, options?: TopologyDescriptionOptions | null);
  5635. /* Excluded from this release type: updateFromSrvPollingEvent */
  5636. /* Excluded from this release type: update */
  5637. get error(): MongoServerError | null;
  5638. /**
  5639. * Determines if the topology description has any known servers
  5640. */
  5641. get hasKnownServers(): boolean;
  5642. /**
  5643. * Determines if this topology description has a data-bearing server available.
  5644. */
  5645. get hasDataBearingServers(): boolean;
  5646. /* Excluded from this release type: hasServer */
  5647. }
  5648. /**
  5649. * Emitted when topology description changes.
  5650. * @public
  5651. * @category Event
  5652. */
  5653. export declare class TopologyDescriptionChangedEvent {
  5654. /** A unique identifier for the topology */
  5655. topologyId: number;
  5656. /** The old topology description */
  5657. previousDescription: TopologyDescription;
  5658. /** The new topology description */
  5659. newDescription: TopologyDescription;
  5660. /* Excluded from this release type: __constructor */
  5661. }
  5662. /** @public */
  5663. export declare interface TopologyDescriptionOptions {
  5664. heartbeatFrequencyMS?: number;
  5665. localThresholdMS?: number;
  5666. }
  5667. /** @public */
  5668. export declare type TopologyEvents = {
  5669. /* Excluded from this release type: connect */
  5670. serverOpening(event: ServerOpeningEvent): void;
  5671. serverClosed(event: ServerClosedEvent): void;
  5672. serverDescriptionChanged(event: ServerDescriptionChangedEvent): void;
  5673. topologyClosed(event: TopologyClosedEvent): void;
  5674. topologyOpening(event: TopologyOpeningEvent): void;
  5675. topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void;
  5676. error(error: Error): void;
  5677. /* Excluded from this release type: open */
  5678. close(): void;
  5679. timeout(): void;
  5680. } & Omit<ServerEvents, 'connect'> & ConnectionPoolEvents & ConnectionEvents & EventEmitterWithState;
  5681. /**
  5682. * Emitted when topology is initialized.
  5683. * @public
  5684. * @category Event
  5685. */
  5686. export declare class TopologyOpeningEvent {
  5687. /** A unique identifier for the topology */
  5688. topologyId: number;
  5689. /* Excluded from this release type: __constructor */
  5690. }
  5691. /* Excluded from this release type: TopologyOptions */
  5692. /* Excluded from this release type: TopologyPrivate */
  5693. /**
  5694. * An enumeration of topology types we know about
  5695. * @public
  5696. */
  5697. export declare const TopologyType: Readonly<{
  5698. readonly Single: "Single";
  5699. readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary";
  5700. readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary";
  5701. readonly Sharded: "Sharded";
  5702. readonly Unknown: "Unknown";
  5703. readonly LoadBalanced: "LoadBalanced";
  5704. }>;
  5705. /** @public */
  5706. export declare type TopologyType = (typeof TopologyType)[keyof typeof TopologyType];
  5707. /** @public */
  5708. export declare interface TopologyVersion {
  5709. processId: ObjectId;
  5710. counter: Long;
  5711. }
  5712. /**
  5713. * @public
  5714. * A class maintaining state related to a server transaction. Internal Only
  5715. */
  5716. export declare class Transaction {
  5717. /* Excluded from this release type: state */
  5718. options: TransactionOptions;
  5719. /* Excluded from this release type: _pinnedServer */
  5720. /* Excluded from this release type: _recoveryToken */
  5721. /* Excluded from this release type: __constructor */
  5722. /* Excluded from this release type: server */
  5723. get recoveryToken(): Document | undefined;
  5724. get isPinned(): boolean;
  5725. /** @returns Whether the transaction has started */
  5726. get isStarting(): boolean;
  5727. /**
  5728. * @returns Whether this session is presently in a transaction
  5729. */
  5730. get isActive(): boolean;
  5731. get isCommitted(): boolean;
  5732. /* Excluded from this release type: transition */
  5733. /* Excluded from this release type: pinServer */
  5734. /* Excluded from this release type: unpinServer */
  5735. }
  5736. /**
  5737. * Configuration options for a transaction.
  5738. * @public
  5739. */
  5740. export declare interface TransactionOptions extends CommandOperationOptions {
  5741. /** A default read concern for commands in this transaction */
  5742. readConcern?: ReadConcernLike;
  5743. /** A default writeConcern for commands in this transaction */
  5744. writeConcern?: WriteConcern;
  5745. /** A default read preference for commands in this transaction */
  5746. readPreference?: ReadPreferenceLike;
  5747. /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */
  5748. maxCommitTimeMS?: number;
  5749. }
  5750. /* Excluded from this release type: TxnState */
  5751. /**
  5752. * Typescript type safe event emitter
  5753. * @public
  5754. */
  5755. export declare interface TypedEventEmitter<Events extends EventsDescription> extends EventEmitter {
  5756. addListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5757. addListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5758. addListener(event: string | symbol, listener: GenericListener): this;
  5759. on<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5760. on(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5761. on(event: string | symbol, listener: GenericListener): this;
  5762. once<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5763. once(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5764. once(event: string | symbol, listener: GenericListener): this;
  5765. removeListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5766. removeListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5767. removeListener(event: string | symbol, listener: GenericListener): this;
  5768. off<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5769. off(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5770. off(event: string | symbol, listener: GenericListener): this;
  5771. removeAllListeners<EventKey extends keyof Events>(event?: EventKey | CommonEvents | symbol | string): this;
  5772. listeners<EventKey extends keyof Events>(event: EventKey | CommonEvents | symbol | string): Events[EventKey][];
  5773. rawListeners<EventKey extends keyof Events>(event: EventKey | CommonEvents | symbol | string): Events[EventKey][];
  5774. emit<EventKey extends keyof Events>(event: EventKey | symbol, ...args: Parameters<Events[EventKey]>): boolean;
  5775. listenerCount<EventKey extends keyof Events>(type: EventKey | CommonEvents | symbol | string): number;
  5776. prependListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5777. prependListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5778. prependListener(event: string | symbol, listener: GenericListener): this;
  5779. prependOnceListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  5780. prependOnceListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  5781. prependOnceListener(event: string | symbol, listener: GenericListener): this;
  5782. eventNames(): string[];
  5783. getMaxListeners(): number;
  5784. setMaxListeners(n: number): this;
  5785. }
  5786. /**
  5787. * Typescript type safe event emitter
  5788. * @public
  5789. */
  5790. export declare class TypedEventEmitter<Events extends EventsDescription> extends EventEmitter {
  5791. /* Excluded from this release type: mongoLogger */
  5792. /* Excluded from this release type: component */
  5793. /* Excluded from this release type: emitAndLog */
  5794. }
  5795. /** @public */
  5796. export declare class UnorderedBulkOperation extends BulkOperationBase {
  5797. /* Excluded from this release type: __constructor */
  5798. handleWriteError(callback: Callback, writeResult: BulkWriteResult): boolean;
  5799. addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
  5800. }
  5801. /** @public */
  5802. export declare interface UpdateDescription<TSchema extends Document = Document> {
  5803. /**
  5804. * A document containing key:value pairs of names of the fields that were
  5805. * changed, and the new value for those fields.
  5806. */
  5807. updatedFields?: Partial<TSchema>;
  5808. /**
  5809. * An array of field names that were removed from the document.
  5810. */
  5811. removedFields?: string[];
  5812. /**
  5813. * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages:
  5814. * - $addFields
  5815. * - $set
  5816. * - $replaceRoot
  5817. * - $replaceWith
  5818. */
  5819. truncatedArrays?: Array<{
  5820. /** The name of the truncated field. */
  5821. field: string;
  5822. /** The number of elements in the truncated array. */
  5823. newSize: number;
  5824. }>;
  5825. /**
  5826. * A document containing additional information about any ambiguous update paths from the update event. The document
  5827. * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example,
  5828. * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like
  5829. * the following:
  5830. *
  5831. * ```
  5832. * {
  5833. * 'a.0': ['a', '0']
  5834. * }
  5835. * ```
  5836. *
  5837. * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents`
  5838. * is enabled for the change stream.
  5839. * @sinceServerVersion 6.1.0
  5840. */
  5841. disambiguatedPaths?: Document;
  5842. }
  5843. /** @public */
  5844. export declare type UpdateFilter<TSchema> = {
  5845. $currentDate?: OnlyFieldsOfType<TSchema, Date | Timestamp, true | {
  5846. $type: 'date' | 'timestamp';
  5847. }>;
  5848. $inc?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  5849. $min?: MatchKeysAndValues<TSchema>;
  5850. $max?: MatchKeysAndValues<TSchema>;
  5851. $mul?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  5852. $rename?: Record<string, string>;
  5853. $set?: MatchKeysAndValues<TSchema>;
  5854. $setOnInsert?: MatchKeysAndValues<TSchema>;
  5855. $unset?: OnlyFieldsOfType<TSchema, any, '' | true | 1>;
  5856. $addToSet?: SetFields<TSchema>;
  5857. $pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
  5858. $pull?: PullOperator<TSchema>;
  5859. $push?: PushOperator<TSchema>;
  5860. $pullAll?: PullAllOperator<TSchema>;
  5861. $bit?: OnlyFieldsOfType<TSchema, NumericType | undefined, {
  5862. and: IntegerType;
  5863. } | {
  5864. or: IntegerType;
  5865. } | {
  5866. xor: IntegerType;
  5867. }>;
  5868. } & Document;
  5869. /** @public */
  5870. export declare interface UpdateManyModel<TSchema extends Document = Document> {
  5871. /** The filter to limit the updated documents. */
  5872. filter: Filter<TSchema>;
  5873. /** A document or pipeline containing update operators. */
  5874. update: UpdateFilter<TSchema> | UpdateFilter<TSchema>[];
  5875. /** A set of filters specifying to which array elements an update should apply. */
  5876. arrayFilters?: Document[];
  5877. /** Specifies a collation. */
  5878. collation?: CollationOptions;
  5879. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  5880. hint?: Hint;
  5881. /** When true, creates a new document if no document matches the query. */
  5882. upsert?: boolean;
  5883. }
  5884. /** @public */
  5885. export declare interface UpdateOneModel<TSchema extends Document = Document> {
  5886. /** The filter to limit the updated documents. */
  5887. filter: Filter<TSchema>;
  5888. /** A document or pipeline containing update operators. */
  5889. update: UpdateFilter<TSchema> | UpdateFilter<TSchema>[];
  5890. /** A set of filters specifying to which array elements an update should apply. */
  5891. arrayFilters?: Document[];
  5892. /** Specifies a collation. */
  5893. collation?: CollationOptions;
  5894. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  5895. hint?: Hint;
  5896. /** When true, creates a new document if no document matches the query. */
  5897. upsert?: boolean;
  5898. }
  5899. /** @public */
  5900. export declare interface UpdateOptions extends CommandOperationOptions {
  5901. /** A set of filters specifying to which array elements an update should apply */
  5902. arrayFilters?: Document[];
  5903. /** If true, allows the write to opt-out of document level validation */
  5904. bypassDocumentValidation?: boolean;
  5905. /** Specifies a collation */
  5906. collation?: CollationOptions;
  5907. /** Specify that the update query should only consider plans using the hinted index */
  5908. hint?: Hint;
  5909. /** When true, creates a new document if no document matches the query */
  5910. upsert?: boolean;
  5911. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  5912. let?: Document;
  5913. }
  5914. /**
  5915. * @public
  5916. * `TSchema` is the schema of the collection
  5917. */
  5918. export declare interface UpdateResult<TSchema extends Document = Document> {
  5919. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  5920. acknowledged: boolean;
  5921. /** The number of documents that matched the filter */
  5922. matchedCount: number;
  5923. /** The number of documents that were modified */
  5924. modifiedCount: number;
  5925. /** The number of documents that were upserted */
  5926. upsertedCount: number;
  5927. /** The identifier of the inserted document if an upsert took place */
  5928. upsertedId: InferIdType<TSchema> | null;
  5929. }
  5930. /** @public */
  5931. export declare interface UpdateStatement {
  5932. /** The query that matches documents to update. */
  5933. q: Document;
  5934. /** The modifications to apply. */
  5935. u: Document | Document[];
  5936. /** If true, perform an insert if no documents match the query. */
  5937. upsert?: boolean;
  5938. /** If true, updates all documents that meet the query criteria. */
  5939. multi?: boolean;
  5940. /** Specifies the collation to use for the operation. */
  5941. collation?: CollationOptions;
  5942. /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */
  5943. arrayFilters?: Document[];
  5944. /** A document or string that specifies the index to use to support the query predicate. */
  5945. hint?: Hint;
  5946. }
  5947. /** @public */
  5948. export declare interface ValidateCollectionOptions extends CommandOperationOptions {
  5949. /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */
  5950. background?: boolean;
  5951. }
  5952. /** @public */
  5953. export declare type W = number | 'majority';
  5954. /* Excluded from this release type: WaitQueueMember */
  5955. /**
  5956. * @public
  5957. * @deprecated This type is only used for the deprecated `collStats` operation and will be removed in the next major release.
  5958. */
  5959. export declare interface WiredTigerData extends Document {
  5960. LSM: {
  5961. 'bloom filter false positives': number;
  5962. 'bloom filter hits': number;
  5963. 'bloom filter misses': number;
  5964. 'bloom filter pages evicted from cache': number;
  5965. 'bloom filter pages read into cache': number;
  5966. 'bloom filters in the LSM tree': number;
  5967. 'chunks in the LSM tree': number;
  5968. 'highest merge generation in the LSM tree': number;
  5969. 'queries that could have benefited from a Bloom filter that did not exist': number;
  5970. 'sleep for LSM checkpoint throttle': number;
  5971. 'sleep for LSM merge throttle': number;
  5972. 'total size of bloom filters': number;
  5973. } & Document;
  5974. 'block-manager': {
  5975. 'allocations requiring file extension': number;
  5976. 'blocks allocated': number;
  5977. 'blocks freed': number;
  5978. 'checkpoint size': number;
  5979. 'file allocation unit size': number;
  5980. 'file bytes available for reuse': number;
  5981. 'file magic number': number;
  5982. 'file major version number': number;
  5983. 'file size in bytes': number;
  5984. 'minor version number': number;
  5985. };
  5986. btree: {
  5987. 'btree checkpoint generation': number;
  5988. 'column-store fixed-size leaf pages': number;
  5989. 'column-store internal pages': number;
  5990. 'column-store variable-size RLE encoded values': number;
  5991. 'column-store variable-size deleted values': number;
  5992. 'column-store variable-size leaf pages': number;
  5993. 'fixed-record size': number;
  5994. 'maximum internal page key size': number;
  5995. 'maximum internal page size': number;
  5996. 'maximum leaf page key size': number;
  5997. 'maximum leaf page size': number;
  5998. 'maximum leaf page value size': number;
  5999. 'maximum tree depth': number;
  6000. 'number of key/value pairs': number;
  6001. 'overflow pages': number;
  6002. 'pages rewritten by compaction': number;
  6003. 'row-store internal pages': number;
  6004. 'row-store leaf pages': number;
  6005. } & Document;
  6006. cache: {
  6007. 'bytes currently in the cache': number;
  6008. 'bytes read into cache': number;
  6009. 'bytes written from cache': number;
  6010. 'checkpoint blocked page eviction': number;
  6011. 'data source pages selected for eviction unable to be evicted': number;
  6012. 'hazard pointer blocked page eviction': number;
  6013. 'in-memory page passed criteria to be split': number;
  6014. 'in-memory page splits': number;
  6015. 'internal pages evicted': number;
  6016. 'internal pages split during eviction': number;
  6017. 'leaf pages split during eviction': number;
  6018. 'modified pages evicted': number;
  6019. 'overflow pages read into cache': number;
  6020. 'overflow values cached in memory': number;
  6021. 'page split during eviction deepened the tree': number;
  6022. 'page written requiring lookaside records': number;
  6023. 'pages read into cache': number;
  6024. 'pages read into cache requiring lookaside entries': number;
  6025. 'pages requested from the cache': number;
  6026. 'pages written from cache': number;
  6027. 'pages written requiring in-memory restoration': number;
  6028. 'tracked dirty bytes in the cache': number;
  6029. 'unmodified pages evicted': number;
  6030. } & Document;
  6031. cache_walk: {
  6032. 'Average difference between current eviction generation when the page was last considered': number;
  6033. 'Average on-disk page image size seen': number;
  6034. 'Clean pages currently in cache': number;
  6035. 'Current eviction generation': number;
  6036. 'Dirty pages currently in cache': number;
  6037. 'Entries in the root page': number;
  6038. 'Internal pages currently in cache': number;
  6039. 'Leaf pages currently in cache': number;
  6040. 'Maximum difference between current eviction generation when the page was last considered': number;
  6041. 'Maximum page size seen': number;
  6042. 'Minimum on-disk page image size seen': number;
  6043. 'On-disk page image sizes smaller than a single allocation unit': number;
  6044. 'Pages created in memory and never written': number;
  6045. 'Pages currently queued for eviction': number;
  6046. 'Pages that could not be queued for eviction': number;
  6047. 'Refs skipped during cache traversal': number;
  6048. 'Size of the root page': number;
  6049. 'Total number of pages currently in cache': number;
  6050. } & Document;
  6051. compression: {
  6052. 'compressed pages read': number;
  6053. 'compressed pages written': number;
  6054. 'page written failed to compress': number;
  6055. 'page written was too small to compress': number;
  6056. 'raw compression call failed, additional data available': number;
  6057. 'raw compression call failed, no additional data available': number;
  6058. 'raw compression call succeeded': number;
  6059. } & Document;
  6060. cursor: {
  6061. 'bulk-loaded cursor-insert calls': number;
  6062. 'create calls': number;
  6063. 'cursor-insert key and value bytes inserted': number;
  6064. 'cursor-remove key bytes removed': number;
  6065. 'cursor-update value bytes updated': number;
  6066. 'insert calls': number;
  6067. 'next calls': number;
  6068. 'prev calls': number;
  6069. 'remove calls': number;
  6070. 'reset calls': number;
  6071. 'restarted searches': number;
  6072. 'search calls': number;
  6073. 'search near calls': number;
  6074. 'truncate calls': number;
  6075. 'update calls': number;
  6076. };
  6077. reconciliation: {
  6078. 'dictionary matches': number;
  6079. 'fast-path pages deleted': number;
  6080. 'internal page key bytes discarded using suffix compression': number;
  6081. 'internal page multi-block writes': number;
  6082. 'internal-page overflow keys': number;
  6083. 'leaf page key bytes discarded using prefix compression': number;
  6084. 'leaf page multi-block writes': number;
  6085. 'leaf-page overflow keys': number;
  6086. 'maximum blocks required for a page': number;
  6087. 'overflow values written': number;
  6088. 'page checksum matches': number;
  6089. 'page reconciliation calls': number;
  6090. 'page reconciliation calls for eviction': number;
  6091. 'pages deleted': number;
  6092. } & Document;
  6093. }
  6094. /* Excluded from this release type: WithConnectionCallback */
  6095. /** Add an _id field to an object shaped type @public */
  6096. export declare type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {
  6097. _id: InferIdType<TSchema>;
  6098. };
  6099. /** Remove the _id field from an object shaped type @public */
  6100. export declare type WithoutId<TSchema> = Omit<TSchema, '_id'>;
  6101. /** @public */
  6102. export declare type WithSessionCallback = (session: ClientSession) => Promise<any>;
  6103. /** @public */
  6104. export declare type WithTransactionCallback<T = void> = (session: ClientSession) => Promise<T>;
  6105. /**
  6106. * A MongoDB WriteConcern, which describes the level of acknowledgement
  6107. * requested from MongoDB for write operations.
  6108. * @public
  6109. *
  6110. * @see https://www.mongodb.com/docs/manual/reference/write-concern/
  6111. */
  6112. export declare class WriteConcern {
  6113. /** Request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags. */
  6114. readonly w?: W;
  6115. /** Request acknowledgment that the write operation has been written to the on-disk journal */
  6116. readonly journal?: boolean;
  6117. /** Specify a time limit to prevent write operations from blocking indefinitely */
  6118. readonly wtimeoutMS?: number;
  6119. /**
  6120. * Specify a time limit to prevent write operations from blocking indefinitely.
  6121. * @deprecated Will be removed in the next major version. Please use wtimeoutMS.
  6122. */
  6123. wtimeout?: number;
  6124. /**
  6125. * Request acknowledgment that the write operation has been written to the on-disk journal.
  6126. * @deprecated Will be removed in the next major version. Please use journal.
  6127. */
  6128. j?: boolean;
  6129. /**
  6130. * Equivalent to the j option.
  6131. * @deprecated Will be removed in the next major version. Please use journal.
  6132. */
  6133. fsync?: boolean | 1;
  6134. /**
  6135. * Constructs a WriteConcern from the write concern properties.
  6136. * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
  6137. * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely
  6138. * @param journal - request acknowledgment that the write operation has been written to the on-disk journal
  6139. * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version.
  6140. */
  6141. constructor(w?: W, wtimeoutMS?: number, journal?: boolean, fsync?: boolean | 1);
  6142. /**
  6143. * Apply a write concern to a command document. Will modify and return the command.
  6144. */
  6145. static apply(command: Document, writeConcern: WriteConcern): Document;
  6146. /** Construct a WriteConcern given an options object. */
  6147. static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined;
  6148. }
  6149. /**
  6150. * An error representing a failure by the server to apply the requested write concern to the bulk operation.
  6151. * @public
  6152. * @category Error
  6153. */
  6154. export declare class WriteConcernError {
  6155. /* Excluded from this release type: [kServerError] */
  6156. constructor(error: WriteConcernErrorData);
  6157. /** Write concern error code. */
  6158. get code(): number | undefined;
  6159. /** Write concern error message. */
  6160. get errmsg(): string | undefined;
  6161. /** Write concern error info. */
  6162. get errInfo(): Document | undefined;
  6163. toJSON(): WriteConcernErrorData;
  6164. toString(): string;
  6165. }
  6166. /** @public */
  6167. export declare interface WriteConcernErrorData {
  6168. code: number;
  6169. errmsg: string;
  6170. errInfo?: Document;
  6171. }
  6172. /** @public */
  6173. export declare interface WriteConcernOptions {
  6174. /** Write Concern as an object */
  6175. writeConcern?: WriteConcern | WriteConcernSettings;
  6176. }
  6177. /** @public */
  6178. export declare interface WriteConcernSettings {
  6179. /** The write concern */
  6180. w?: W;
  6181. /** The write concern timeout */
  6182. wtimeoutMS?: number;
  6183. /** The journal write concern */
  6184. journal?: boolean;
  6185. /**
  6186. * The journal write concern.
  6187. * @deprecated Will be removed in the next major version. Please use the journal option.
  6188. */
  6189. j?: boolean;
  6190. /**
  6191. * The write concern timeout.
  6192. * @deprecated Will be removed in the next major version. Please use the wtimeoutMS option.
  6193. */
  6194. wtimeout?: number;
  6195. /**
  6196. * The file sync write concern.
  6197. * @deprecated Will be removed in the next major version. Please use the journal option.
  6198. */
  6199. fsync?: boolean | 1;
  6200. }
  6201. /**
  6202. * An error that occurred during a BulkWrite on the server.
  6203. * @public
  6204. * @category Error
  6205. */
  6206. export declare class WriteError {
  6207. err: BulkWriteOperationError;
  6208. constructor(err: BulkWriteOperationError);
  6209. /** WriteError code. */
  6210. get code(): number;
  6211. /** WriteError original bulk operation index. */
  6212. get index(): number;
  6213. /** WriteError message. */
  6214. get errmsg(): string | undefined;
  6215. /** WriteError details. */
  6216. get errInfo(): Document | undefined;
  6217. /** Returns the underlying operation that caused the error */
  6218. getOperation(): Document;
  6219. toJSON(): {
  6220. code: number;
  6221. index: number;
  6222. errmsg?: string;
  6223. op: Document;
  6224. };
  6225. toString(): string;
  6226. }
  6227. /* Excluded from this release type: WriteProtocolMessageType */
  6228. export { }