mongodb.d.ts 342 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010
  1. import type { DeserializeOptions } from 'bson';
  2. import type { ObjectIdLike } from 'bson';
  3. import type { SerializeOptions } from 'bson';
  4. import { Binary } from 'bson';
  5. import { BSON } from 'bson';
  6. import { BSONRegExp } from 'bson';
  7. import { BSONSymbol } from 'bson';
  8. import { BSONType } from 'bson';
  9. import { Code } from 'bson';
  10. import { DBRef } from 'bson';
  11. import { Decimal128 } from 'bson';
  12. import { deserialize } from 'bson';
  13. import { Document } from 'bson';
  14. import { Double } from 'bson';
  15. import { Int32 } from 'bson';
  16. import { Long } from 'bson';
  17. import { MaxKey } from 'bson';
  18. import { MinKey } from 'bson';
  19. import { ObjectId } from 'bson';
  20. import { serialize } from 'bson';
  21. import { Timestamp } from 'bson';
  22. import { UUID } from 'bson';
  23. import type { SrvRecord } from 'dns';
  24. import { EventEmitter } from 'events';
  25. import type { Socket } from 'net';
  26. import type { TcpNetConnectOpts } from 'net';
  27. import { Readable } from 'stream';
  28. import { Writable } from 'stream';
  29. import type { ConnectionOptions as ConnectionOptions_2 } from 'tls';
  30. import type { TLSSocket } from 'tls';
  31. import type { TLSSocketOptions } from 'tls';
  32. /** @public */
  33. export declare type Abortable = {
  34. /**
  35. * @experimental
  36. * When provided, the corresponding `AbortController` can be used to abort an asynchronous action.
  37. *
  38. * The `signal.reason` value is used as the error thrown.
  39. *
  40. * @remarks
  41. * **NOTE:** If an abort signal aborts an operation while the driver is writing to the underlying
  42. * socket or reading the response from the server, the socket will be closed.
  43. * If signals are aborted at a high rate during socket read/writes this can lead to a high rate of connection reestablishment.
  44. *
  45. * We plan to mitigate this in a future release, please follow NODE-6062 (`timeoutMS` expiration suffers the same limitation).
  46. *
  47. * AbortSignals are likely a best fit for human interactive interruption (ex. ctrl-C) where the frequency
  48. * of cancellation is reasonably low. If a signal is programmatically aborted for 100s of operations you can empty
  49. * the driver's connection pool.
  50. *
  51. * @example
  52. * ```js
  53. * const controller = new AbortController();
  54. * const { signal } = controller;
  55. * process.on('SIGINT', () => controller.abort(new Error('^C pressed')));
  56. *
  57. * try {
  58. * const res = await fetch('...', { signal });
  59. * await collection.findOne(await res.json(), { signal });
  60. * catch (error) {
  61. * if (error === signal.reason) {
  62. * // signal abort error handling
  63. * }
  64. * }
  65. * ```
  66. */
  67. signal?: AbortSignal | undefined;
  68. };
  69. /** @public */
  70. export declare abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> implements AsyncDisposable {
  71. /* Excluded from this release type: cursorId */
  72. /* Excluded from this release type: cursorSession */
  73. /* Excluded from this release type: selectedServer */
  74. /* Excluded from this release type: cursorNamespace */
  75. /* Excluded from this release type: documents */
  76. /* Excluded from this release type: cursorClient */
  77. /* Excluded from this release type: transform */
  78. /* Excluded from this release type: initialized */
  79. /* Excluded from this release type: isClosed */
  80. /* Excluded from this release type: isKilled */
  81. /* Excluded from this release type: cursorOptions */
  82. /* Excluded from this release type: timeoutContext */
  83. /** @event */
  84. static readonly CLOSE: "close";
  85. /* Excluded from this release type: deserializationOptions */
  86. protected signal: AbortSignal | undefined;
  87. private abortListener;
  88. /* Excluded from this release type: __constructor */
  89. /**
  90. * The cursor has no id until it receives a response from the initial cursor creating command.
  91. *
  92. * It is non-zero for as long as the database has an open cursor.
  93. *
  94. * The initiating command may receive a zero id if the entire result is in the `firstBatch`.
  95. */
  96. get id(): Long | undefined;
  97. /* Excluded from this release type: isDead */
  98. /* Excluded from this release type: client */
  99. /* Excluded from this release type: server */
  100. get namespace(): MongoDBNamespace;
  101. get readPreference(): ReadPreference;
  102. get readConcern(): ReadConcern | undefined;
  103. /* Excluded from this release type: session */
  104. /* Excluded from this release type: session */
  105. /**
  106. * The cursor is closed and all remaining locally buffered documents have been iterated.
  107. */
  108. get closed(): boolean;
  109. /**
  110. * A `killCursors` command was attempted on this cursor.
  111. * This is performed if the cursor id is non zero.
  112. */
  113. get killed(): boolean;
  114. get loadBalanced(): boolean;
  115. /**
  116. * @experimental
  117. * An alias for {@link AbstractCursor.close|AbstractCursor.close()}.
  118. */
  119. [Symbol.asyncDispose](): Promise<void>;
  120. /** Adds cursor to client's tracking so it will be closed by MongoClient.close() */
  121. private trackCursor;
  122. /** Returns current buffered documents length */
  123. bufferedCount(): number;
  124. /** Returns current buffered documents */
  125. readBufferedDocuments(number?: number): NonNullable<TSchema>[];
  126. [Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void>;
  127. stream(): Readable & AsyncIterable<TSchema>;
  128. hasNext(): Promise<boolean>;
  129. /** Get the next available document from the cursor, returns null if no more documents are available. */
  130. next(): Promise<TSchema | null>;
  131. /**
  132. * Try to get the next available document from the cursor or `null` if an empty batch is returned
  133. */
  134. tryNext(): Promise<TSchema | null>;
  135. /**
  136. * Iterates over all the documents for this cursor using the iterator, callback pattern.
  137. *
  138. * If the iterator returns `false`, iteration will stop.
  139. *
  140. * @param iterator - The iteration callback.
  141. * @deprecated - Will be removed in a future release. Use for await...of instead.
  142. */
  143. forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>;
  144. /**
  145. * Frees any client-side resources used by the cursor.
  146. */
  147. close(options?: {
  148. timeoutMS?: number;
  149. }): Promise<void>;
  150. /**
  151. * Returns an array of documents. The caller is responsible for making sure that there
  152. * is enough memory to store the results. Note that the array only contains partial
  153. * results when this cursor had been previously accessed. In that case,
  154. * cursor.rewind() can be used to reset the cursor.
  155. */
  156. toArray(): Promise<TSchema[]>;
  157. /**
  158. * Add a cursor flag to the cursor
  159. *
  160. * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
  161. * @param value - The flag boolean value.
  162. */
  163. addCursorFlag(flag: CursorFlag, value: boolean): this;
  164. /**
  165. * Map all documents using the provided function
  166. * If there is a transform set on the cursor, that will be called first and the result passed to
  167. * this function's transform.
  168. *
  169. * @remarks
  170. *
  171. * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
  172. * function that maps values to `null` will result in the cursor closing itself before it has finished iterating
  173. * all documents. This will **not** result in a memory leak, just surprising behavior. For example:
  174. *
  175. * ```typescript
  176. * const cursor = collection.find({});
  177. * cursor.map(() => null);
  178. *
  179. * const documents = await cursor.toArray();
  180. * // documents is always [], regardless of how many documents are in the collection.
  181. * ```
  182. *
  183. * Other falsey values are allowed:
  184. *
  185. * ```typescript
  186. * const cursor = collection.find({});
  187. * cursor.map(() => '');
  188. *
  189. * const documents = await cursor.toArray();
  190. * // documents is now an array of empty strings
  191. * ```
  192. *
  193. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  194. * it **does not** return a new instance of a cursor. This means when calling map,
  195. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  196. * Take note of the following example:
  197. *
  198. * @example
  199. * ```typescript
  200. * const cursor: FindCursor<Document> = coll.find();
  201. * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
  202. * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
  203. * ```
  204. * @param transform - The mapping transformation method.
  205. */
  206. map<T = any>(transform: (doc: TSchema) => T): AbstractCursor<T>;
  207. /**
  208. * Set the ReadPreference for the cursor.
  209. *
  210. * @param readPreference - The new read preference for the cursor.
  211. */
  212. withReadPreference(readPreference: ReadPreferenceLike): this;
  213. /**
  214. * Set the ReadPreference for the cursor.
  215. *
  216. * @param readPreference - The new read preference for the cursor.
  217. */
  218. withReadConcern(readConcern: ReadConcernLike): this;
  219. /**
  220. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  221. *
  222. * @param value - Number of milliseconds to wait before aborting the query.
  223. */
  224. maxTimeMS(value: number): this;
  225. /**
  226. * Set the batch size for the cursor.
  227. *
  228. * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
  229. */
  230. batchSize(value: number): this;
  231. /**
  232. * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
  233. * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
  234. * if the resultant data has already been retrieved by this cursor.
  235. */
  236. rewind(): void;
  237. /**
  238. * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
  239. */
  240. abstract clone(): AbstractCursor<TSchema>;
  241. /* Excluded from this release type: _initialize */
  242. /* Excluded from this release type: getMore */
  243. /* Excluded from this release type: cursorInit */
  244. /* Excluded from this release type: fetchBatch */
  245. /* Excluded from this release type: cleanup */
  246. /* Excluded from this release type: hasEmittedClose */
  247. /* Excluded from this release type: emitClose */
  248. /* Excluded from this release type: transformDocument */
  249. /* Excluded from this release type: throwIfInitialized */
  250. }
  251. /** @public */
  252. export declare type AbstractCursorEvents = {
  253. [AbstractCursor.CLOSE](): void;
  254. };
  255. /** @public */
  256. export declare interface AbstractCursorOptions extends BSONSerializeOptions {
  257. session?: ClientSession;
  258. readPreference?: ReadPreferenceLike;
  259. readConcern?: ReadConcernLike;
  260. /**
  261. * Specifies the number of documents to return in each response from MongoDB
  262. */
  263. batchSize?: number;
  264. /**
  265. * When applicable `maxTimeMS` controls the amount of time the initial command
  266. * that constructs a cursor should take. (ex. find, aggregate, listCollections)
  267. */
  268. maxTimeMS?: number;
  269. /**
  270. * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores
  271. * that a cursor uses to fetch more data should take. (ex. cursor.next())
  272. */
  273. maxAwaitTimeMS?: number;
  274. /**
  275. * Comment to apply to the operation.
  276. *
  277. * In server versions pre-4.4, 'comment' must be string. A server
  278. * error will be thrown if any other type is provided.
  279. *
  280. * In server versions 4.4 and above, 'comment' can be any valid BSON type.
  281. */
  282. comment?: unknown;
  283. /**
  284. * By default, MongoDB will automatically close a cursor when the
  285. * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections)
  286. * you may use a Tailable Cursor that remains open after the client exhausts
  287. * the results in the initial cursor.
  288. */
  289. tailable?: boolean;
  290. /**
  291. * If awaitData is set to true, when the cursor reaches the end of the capped collection,
  292. * MongoDB blocks the query thread for a period of time waiting for new data to arrive.
  293. * When new data is inserted into the capped collection, the blocked thread is signaled
  294. * to wake up and return the next batch to the client.
  295. */
  296. awaitData?: boolean;
  297. noCursorTimeout?: boolean;
  298. /** Specifies the time an operation will run until it throws a timeout error. See {@link AbstractCursorOptions.timeoutMode} for more details on how this option applies to cursors. */
  299. timeoutMS?: number;
  300. /**
  301. * @public
  302. * @experimental
  303. * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
  304. * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
  305. * `cursor.next()`.
  306. * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
  307. *
  308. * Depending on the type of cursor being used, this option has different default values.
  309. * For non-tailable cursors, this value defaults to `'cursorLifetime'`
  310. * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
  311. * definition can have an arbitrarily long lifetime.
  312. *
  313. * @example
  314. * ```ts
  315. * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
  316. * for await (const doc of cursor) {
  317. * // process doc
  318. * // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
  319. * // will continue to iterate successfully otherwise, regardless of the number of batches.
  320. * }
  321. * ```
  322. *
  323. * @example
  324. * ```ts
  325. * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
  326. * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
  327. * ```
  328. */
  329. timeoutMode?: CursorTimeoutMode;
  330. /* Excluded from this release type: timeoutContext */
  331. }
  332. /* Excluded from this release type: AbstractOperation */
  333. /** @public */
  334. export declare type AcceptedFields<TSchema, FieldType, AssignableType> = {
  335. readonly [key in KeysOfAType<TSchema, FieldType>]?: AssignableType;
  336. };
  337. /** @public */
  338. export declare type AddToSetOperators<Type> = {
  339. $each?: Array<Flatten<Type>>;
  340. };
  341. /**
  342. * The **Admin** class is an internal class that allows convenient access to
  343. * the admin functionality and commands for MongoDB.
  344. *
  345. * **ADMIN Cannot directly be instantiated**
  346. * @public
  347. *
  348. * @example
  349. * ```ts
  350. * import { MongoClient } from 'mongodb';
  351. *
  352. * const client = new MongoClient('mongodb://localhost:27017');
  353. * const admin = client.db().admin();
  354. * const dbInfo = await admin.listDatabases();
  355. * for (const db of dbInfo.databases) {
  356. * console.log(db.name);
  357. * }
  358. * ```
  359. */
  360. export declare class Admin {
  361. /* Excluded from this release type: s */
  362. /* Excluded from this release type: __constructor */
  363. /**
  364. * Execute a command
  365. *
  366. * The driver will ensure the following fields are attached to the command sent to the server:
  367. * - `lsid` - sourced from an implicit session or options.session
  368. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  369. * - `$db` - sourced from the name of this database
  370. *
  371. * If the client has a serverApi setting:
  372. * - `apiVersion`
  373. * - `apiStrict`
  374. * - `apiDeprecationErrors`
  375. *
  376. * When in a transaction:
  377. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  378. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  379. *
  380. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  381. *
  382. * @param command - The command to execute
  383. * @param options - Optional settings for the command
  384. */
  385. command(command: Document, options?: RunCommandOptions): Promise<Document>;
  386. /**
  387. * Retrieve the server build information
  388. *
  389. * @param options - Optional settings for the command
  390. */
  391. buildInfo(options?: CommandOperationOptions): Promise<Document>;
  392. /**
  393. * Retrieve the server build information
  394. *
  395. * @param options - Optional settings for the command
  396. */
  397. serverInfo(options?: CommandOperationOptions): Promise<Document>;
  398. /**
  399. * Retrieve this db's server status.
  400. *
  401. * @param options - Optional settings for the command
  402. */
  403. serverStatus(options?: CommandOperationOptions): Promise<Document>;
  404. /**
  405. * Ping the MongoDB server and retrieve results
  406. *
  407. * @param options - Optional settings for the command
  408. */
  409. ping(options?: CommandOperationOptions): Promise<Document>;
  410. /**
  411. * Remove a user from a database
  412. *
  413. * @param username - The username to remove
  414. * @param options - Optional settings for the command
  415. */
  416. removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
  417. /**
  418. * Validate an existing collection
  419. *
  420. * @param collectionName - The name of the collection to validate.
  421. * @param options - Optional settings for the command
  422. */
  423. validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise<Document>;
  424. /**
  425. * List the available databases
  426. *
  427. * @param options - Optional settings for the command
  428. */
  429. listDatabases(options?: ListDatabasesOptions): Promise<ListDatabasesResult>;
  430. /**
  431. * Get ReplicaSet status
  432. *
  433. * @param options - Optional settings for the command
  434. */
  435. replSetGetStatus(options?: CommandOperationOptions): Promise<Document>;
  436. }
  437. /* Excluded from this release type: AdminPrivate */
  438. /* Excluded from this release type: AggregateOperation */
  439. /** @public */
  440. export declare interface AggregateOptions extends Omit<CommandOperationOptions, 'explain'> {
  441. /** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */
  442. allowDiskUse?: boolean;
  443. /** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */
  444. batchSize?: number;
  445. /** Allow driver to bypass schema validation. */
  446. bypassDocumentValidation?: boolean;
  447. /** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */
  448. cursor?: Document;
  449. /**
  450. * Specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
  451. */
  452. maxTimeMS?: number;
  453. /** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */
  454. maxAwaitTimeMS?: number;
  455. /** Specify collation. */
  456. collation?: CollationOptions;
  457. /** Add an index selection hint to an aggregation command */
  458. hint?: Hint;
  459. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  460. let?: Document;
  461. out?: string;
  462. /**
  463. * Specifies the verbosity mode for the explain output.
  464. * @deprecated This API is deprecated in favor of `collection.aggregate().explain()`
  465. * or `db.aggregate().explain()`.
  466. */
  467. explain?: ExplainOptions['explain'];
  468. /* Excluded from this release type: timeoutMode */
  469. }
  470. /**
  471. * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
  472. * allowing for iteration over the results returned from the underlying query. It supports
  473. * one by one document iteration, conversion to an array or can be iterated as a Node 4.X
  474. * or higher stream
  475. * @public
  476. */
  477. export declare class AggregationCursor<TSchema = any> extends ExplainableCursor<TSchema> {
  478. readonly pipeline: Document[];
  479. /* Excluded from this release type: aggregateOptions */
  480. /* Excluded from this release type: __constructor */
  481. clone(): AggregationCursor<TSchema>;
  482. map<T>(transform: (doc: TSchema) => T): AggregationCursor<T>;
  483. /* Excluded from this release type: _initialize */
  484. /** Execute the explain for the cursor */
  485. explain(): Promise<Document>;
  486. explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;
  487. explain(options: {
  488. timeoutMS?: number;
  489. }): Promise<Document>;
  490. explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions, options: {
  491. timeoutMS?: number;
  492. }): Promise<Document>;
  493. /** Add a stage to the aggregation pipeline
  494. * @example
  495. * ```
  496. * const documents = await users.aggregate().addStage({ $match: { name: /Mike/ } }).toArray();
  497. * ```
  498. * @example
  499. * ```
  500. * const documents = await users.aggregate()
  501. * .addStage<{ name: string }>({ $project: { name: true } })
  502. * .toArray(); // type of documents is { name: string }[]
  503. * ```
  504. */
  505. addStage(stage: Document): this;
  506. addStage<T = Document>(stage: Document): AggregationCursor<T>;
  507. /** Add a group stage to the aggregation pipeline */
  508. group<T = TSchema>($group: Document): AggregationCursor<T>;
  509. /** Add a limit stage to the aggregation pipeline */
  510. limit($limit: number): this;
  511. /** Add a match stage to the aggregation pipeline */
  512. match($match: Document): this;
  513. /** Add an out stage to the aggregation pipeline */
  514. out($out: {
  515. db: string;
  516. coll: string;
  517. } | string): this;
  518. /**
  519. * Add a project stage to the aggregation pipeline
  520. *
  521. * @remarks
  522. * In order to strictly type this function you must provide an interface
  523. * that represents the effect of your projection on the result documents.
  524. *
  525. * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
  526. * You should specify a parameterized type to have assertions on your final results.
  527. *
  528. * @example
  529. * ```typescript
  530. * // Best way
  531. * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
  532. * // Flexible way
  533. * const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
  534. * ```
  535. *
  536. * @remarks
  537. * In order to strictly type this function you must provide an interface
  538. * that represents the effect of your projection on the result documents.
  539. *
  540. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  541. * it **does not** return a new instance of a cursor. This means when calling project,
  542. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  543. * Take note of the following example:
  544. *
  545. * @example
  546. * ```typescript
  547. * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
  548. * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
  549. * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
  550. *
  551. * // or always use chaining and save the final cursor
  552. *
  553. * const cursor = coll.aggregate().project<{ a: string }>({
  554. * _id: 0,
  555. * a: { $convert: { input: '$a', to: 'string' }
  556. * }});
  557. * ```
  558. */
  559. project<T extends Document = Document>($project: Document): AggregationCursor<T>;
  560. /** Add a lookup stage to the aggregation pipeline */
  561. lookup($lookup: Document): this;
  562. /** Add a redact stage to the aggregation pipeline */
  563. redact($redact: Document): this;
  564. /** Add a skip stage to the aggregation pipeline */
  565. skip($skip: number): this;
  566. /** Add a sort stage to the aggregation pipeline */
  567. sort($sort: Sort): this;
  568. /** Add a unwind stage to the aggregation pipeline */
  569. unwind($unwind: Document | string): this;
  570. /** Add a geoNear stage to the aggregation pipeline */
  571. geoNear($geoNear: Document): this;
  572. }
  573. /** @public */
  574. export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {
  575. }
  576. /**
  577. * It is possible to search using alternative types in mongodb e.g.
  578. * string types can be searched using a regex in mongo
  579. * array types can be searched using their element type
  580. * @public
  581. */
  582. export declare type AlternativeType<T> = T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;
  583. /** @public */
  584. export declare type AnyBulkWriteOperation<TSchema extends Document = Document> = {
  585. insertOne: InsertOneModel<TSchema>;
  586. } | {
  587. replaceOne: ReplaceOneModel<TSchema>;
  588. } | {
  589. updateOne: UpdateOneModel<TSchema>;
  590. } | {
  591. updateMany: UpdateManyModel<TSchema>;
  592. } | {
  593. deleteOne: DeleteOneModel<TSchema>;
  594. } | {
  595. deleteMany: DeleteManyModel<TSchema>;
  596. };
  597. /**
  598. * Used to represent any of the client bulk write models that can be passed as an array
  599. * to MongoClient#bulkWrite.
  600. * @public
  601. */
  602. export declare type AnyClientBulkWriteModel<TSchema extends Document> = ClientInsertOneModel<TSchema> | ClientReplaceOneModel<TSchema> | ClientUpdateOneModel<TSchema> | ClientUpdateManyModel<TSchema> | ClientDeleteOneModel<TSchema> | ClientDeleteManyModel<TSchema>;
  603. /** @public */
  604. export declare type AnyError = MongoError | Error;
  605. /** @public */
  606. export declare type ArrayElement<Type> = Type extends ReadonlyArray<infer Item> ? Item : never;
  607. /** @public */
  608. export declare type ArrayOperator<Type> = {
  609. $each?: Array<Flatten<Type>>;
  610. $slice?: number;
  611. $position?: number;
  612. $sort?: Sort;
  613. };
  614. /** @public */
  615. export declare interface Auth {
  616. /** The username for auth */
  617. username?: string;
  618. /** The password for auth */
  619. password?: string;
  620. }
  621. /* Excluded from this release type: AuthContext */
  622. /** @public */
  623. export declare const AuthMechanism: Readonly<{
  624. readonly MONGODB_AWS: "MONGODB-AWS";
  625. readonly MONGODB_DEFAULT: "DEFAULT";
  626. readonly MONGODB_GSSAPI: "GSSAPI";
  627. readonly MONGODB_PLAIN: "PLAIN";
  628. readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1";
  629. readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256";
  630. readonly MONGODB_X509: "MONGODB-X509";
  631. readonly MONGODB_OIDC: "MONGODB-OIDC";
  632. }>;
  633. /** @public */
  634. export declare type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism];
  635. /** @public */
  636. export declare interface AuthMechanismProperties extends Document {
  637. SERVICE_HOST?: string;
  638. SERVICE_NAME?: string;
  639. SERVICE_REALM?: string;
  640. CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue;
  641. /* Excluded from this release type: AWS_SESSION_TOKEN */
  642. /** A user provided OIDC machine callback function. */
  643. OIDC_CALLBACK?: OIDCCallbackFunction;
  644. /** A user provided OIDC human interacted callback function. */
  645. OIDC_HUMAN_CALLBACK?: OIDCCallbackFunction;
  646. /** The OIDC environment. Note that 'test' is for internal use only. */
  647. ENVIRONMENT?: 'test' | 'azure' | 'gcp' | 'k8s';
  648. /** Allowed hosts that OIDC auth can connect to. */
  649. ALLOWED_HOSTS?: string[];
  650. /** The resource token for OIDC auth in Azure and GCP. */
  651. TOKEN_RESOURCE?: string;
  652. /**
  653. * A custom AWS credential provider to use. An example using the AWS SDK default provider chain:
  654. *
  655. * ```ts
  656. * const client = new MongoClient(process.env.MONGODB_URI, {
  657. * authMechanismProperties: {
  658. * AWS_CREDENTIAL_PROVIDER: fromNodeProviderChain()
  659. * }
  660. * });
  661. * ```
  662. *
  663. * Using a custom function that returns AWS credentials:
  664. *
  665. * ```ts
  666. * const client = new MongoClient(process.env.MONGODB_URI, {
  667. * authMechanismProperties: {
  668. * AWS_CREDENTIAL_PROVIDER: async () => {
  669. * return {
  670. * accessKeyId: process.env.ACCESS_KEY_ID,
  671. * secretAccessKey: process.env.SECRET_ACCESS_KEY
  672. * }
  673. * }
  674. * }
  675. * });
  676. * ```
  677. */
  678. AWS_CREDENTIAL_PROVIDER?: AWSCredentialProvider;
  679. }
  680. /* Excluded from this release type: AuthProvider */
  681. /* Excluded from this release type: AutoEncrypter */
  682. /**
  683. * @public
  684. *
  685. * Extra options related to the mongocryptd process
  686. * \* _Available in MongoDB 6.0 or higher._
  687. */
  688. export declare type AutoEncryptionExtraOptions = NonNullable<AutoEncryptionOptions['extraOptions']>;
  689. /** @public */
  690. export declare const AutoEncryptionLoggerLevel: Readonly<{
  691. readonly FatalError: 0;
  692. readonly Error: 1;
  693. readonly Warning: 2;
  694. readonly Info: 3;
  695. readonly Trace: 4;
  696. }>;
  697. /**
  698. * @public
  699. * The level of severity of the log message
  700. *
  701. * | Value | Level |
  702. * |-------|-------|
  703. * | 0 | Fatal Error |
  704. * | 1 | Error |
  705. * | 2 | Warning |
  706. * | 3 | Info |
  707. * | 4 | Trace |
  708. */
  709. export declare type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel];
  710. /** @public */
  711. export declare interface AutoEncryptionOptions {
  712. /* Excluded from this release type: metadataClient */
  713. /** A `MongoClient` used to fetch keys from a key vault */
  714. keyVaultClient?: MongoClient;
  715. /** The namespace where keys are stored in the key vault */
  716. keyVaultNamespace?: string;
  717. /** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */
  718. kmsProviders?: KMSProviders;
  719. /** Configuration options for custom credential providers. */
  720. credentialProviders?: CredentialProviders;
  721. /**
  722. * A map of namespaces to a local JSON schema for encryption
  723. *
  724. * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.
  725. * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.
  726. * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.
  727. * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
  728. */
  729. schemaMap?: Document;
  730. /** Supply a schema for the encrypted fields in the document */
  731. encryptedFieldsMap?: Document;
  732. /** Allows the user to bypass auto encryption, maintaining implicit decryption */
  733. bypassAutoEncryption?: boolean;
  734. /** Allows users to bypass query analysis */
  735. bypassQueryAnalysis?: boolean;
  736. /**
  737. * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
  738. */
  739. keyExpirationMS?: number;
  740. options?: {
  741. /** An optional hook to catch logging messages from the underlying encryption engine */
  742. logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
  743. };
  744. extraOptions?: {
  745. /**
  746. * A local process the driver communicates with to determine how to encrypt values in a command.
  747. * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise
  748. */
  749. mongocryptdURI?: string;
  750. /** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */
  751. mongocryptdBypassSpawn?: boolean;
  752. /** The path to the mongocryptd executable on the system */
  753. mongocryptdSpawnPath?: `${string}mongocryptd${'.exe' | ''}`;
  754. /** Command line arguments to use when auto-spawning a mongocryptd */
  755. mongocryptdSpawnArgs?: string[];
  756. /**
  757. * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd).
  758. *
  759. * This needs to be the path to the file itself, not a directory.
  760. * It can be an absolute or relative path. If the path is relative and
  761. * its first component is `$ORIGIN`, it will be replaced by the directory
  762. * containing the mongodb-client-encryption native addon file. Otherwise,
  763. * the path will be interpreted relative to the current working directory.
  764. *
  765. * Currently, loading different MongoDB Crypt shared library files from different
  766. * MongoClients in the same process is not supported.
  767. *
  768. * If this option is provided and no MongoDB Crypt shared library could be loaded
  769. * from the specified location, creating the MongoClient will fail.
  770. *
  771. * If this option is not provided and `cryptSharedLibRequired` is not specified,
  772. * the AutoEncrypter will attempt to spawn and/or use mongocryptd according
  773. * to the mongocryptd-specific `extraOptions` options.
  774. *
  775. * Specifying a path prevents mongocryptd from being used as a fallback.
  776. *
  777. * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
  778. */
  779. cryptSharedLibPath?: `${string}mongo_crypt_v${number}.${'so' | 'dll' | 'dylib'}`;
  780. /**
  781. * If specified, never use mongocryptd and instead fail when the MongoDB Crypt
  782. * shared library could not be loaded.
  783. *
  784. * This is always true when `cryptSharedLibPath` is specified.
  785. *
  786. * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
  787. */
  788. cryptSharedLibRequired?: boolean;
  789. /* Excluded from this release type: cryptSharedLibSearchPaths */
  790. };
  791. proxyOptions?: ProxyOptions;
  792. /** The TLS options to use connecting to the KMS provider */
  793. tlsOptions?: CSFLEKMSTlsOptions;
  794. }
  795. /** @public **/
  796. export declare type AWSCredentialProvider = () => Promise<AWSCredentials>;
  797. /**
  798. * @public
  799. * Copy of the AwsCredentialIdentityProvider interface from [`smithy/types`](https://socket.dev/npm/package/\@smithy/types/files/1.1.1/dist-types/identity/awsCredentialIdentity.d.ts),
  800. * the return type of the aws-sdk's `fromNodeProviderChain().provider()`.
  801. */
  802. export declare interface AWSCredentials {
  803. accessKeyId: string;
  804. secretAccessKey: string;
  805. sessionToken?: string;
  806. expiration?: Date;
  807. }
  808. /**
  809. * @public
  810. * Configuration options for making an AWS encryption key
  811. */
  812. export declare interface AWSEncryptionKeyOptions {
  813. /**
  814. * The AWS region of the KMS
  815. */
  816. region: string;
  817. /**
  818. * The Amazon Resource Name (ARN) to the AWS customer master key (CMK)
  819. */
  820. key: string;
  821. /**
  822. * An alternate host to send KMS requests to. May include port number.
  823. */
  824. endpoint?: string | undefined;
  825. }
  826. /** @public */
  827. export declare interface AWSKMSProviderConfiguration {
  828. /**
  829. * The access key used for the AWS KMS provider
  830. */
  831. accessKeyId: string;
  832. /**
  833. * The secret access key used for the AWS KMS provider
  834. */
  835. secretAccessKey: string;
  836. /**
  837. * An optional AWS session token that will be used as the
  838. * X-Amz-Security-Token header for AWS requests.
  839. */
  840. sessionToken?: string;
  841. }
  842. /**
  843. * @public
  844. * Configuration options for making an Azure encryption key
  845. */
  846. export declare interface AzureEncryptionKeyOptions {
  847. /**
  848. * Key name
  849. */
  850. keyName: string;
  851. /**
  852. * Key vault URL, typically `<name>.vault.azure.net`
  853. */
  854. keyVaultEndpoint: string;
  855. /**
  856. * Key version
  857. */
  858. keyVersion?: string | undefined;
  859. }
  860. /** @public */
  861. export declare type AzureKMSProviderConfiguration = {
  862. /**
  863. * The tenant ID identifies the organization for the account
  864. */
  865. tenantId: string;
  866. /**
  867. * The client ID to authenticate a registered application
  868. */
  869. clientId: string;
  870. /**
  871. * The client secret to authenticate a registered application
  872. */
  873. clientSecret: string;
  874. /**
  875. * If present, a host with optional port. E.g. "example.com" or "example.com:443".
  876. * This is optional, and only needed if customer is using a non-commercial Azure instance
  877. * (e.g. a government or China account, which use different URLs).
  878. * Defaults to "login.microsoftonline.com"
  879. */
  880. identityPlatformEndpoint?: string | undefined;
  881. } | {
  882. /**
  883. * If present, an access token to authenticate with Azure.
  884. */
  885. accessToken: string;
  886. };
  887. /**
  888. * Keeps the state of a unordered batch so we can rewrite the results
  889. * correctly after command execution
  890. *
  891. * @public
  892. */
  893. export declare class Batch<T = Document> {
  894. originalZeroIndex: number;
  895. currentIndex: number;
  896. originalIndexes: number[];
  897. batchType: BatchType;
  898. operations: T[];
  899. size: number;
  900. sizeBytes: number;
  901. constructor(batchType: BatchType, originalZeroIndex: number);
  902. }
  903. /** @public */
  904. export declare const BatchType: Readonly<{
  905. readonly INSERT: 1;
  906. readonly UPDATE: 2;
  907. readonly DELETE: 3;
  908. }>;
  909. /** @public */
  910. export declare type BatchType = (typeof BatchType)[keyof typeof BatchType];
  911. export { Binary }
  912. /** @public */
  913. export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray<number>;
  914. export { BSON }
  915. /* Excluded from this release type: BSONElement */
  916. export { BSONRegExp }
  917. /**
  918. * BSON Serialization options.
  919. * @public
  920. */
  921. export declare interface BSONSerializeOptions extends Omit<SerializeOptions, 'index'>, Omit<DeserializeOptions, 'evalFunctions' | 'cacheFunctions' | 'cacheFunctionsCrc32' | 'allowObjectSmallerThanBufferSize' | 'index' | 'validation'> {
  922. /**
  923. * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html)
  924. * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize).
  925. * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe)
  926. * for more detail about what "unsafe" refers to in this context.
  927. * 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
  928. * your own buffer and clone the contents:
  929. *
  930. * @example
  931. * ```ts
  932. * const raw = await collection.findOne({}, { raw: true });
  933. * const myBuffer = Buffer.alloc(raw.byteLength);
  934. * myBuffer.set(raw, 0);
  935. * // Only save and use `myBuffer` beyond this point
  936. * ```
  937. *
  938. * @remarks
  939. * 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)).
  940. * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work.
  941. */
  942. raw?: boolean;
  943. /** Enable utf8 validation when deserializing BSON documents. Defaults to true. */
  944. enableUtf8Validation?: boolean;
  945. }
  946. export { BSONSymbol }
  947. export { BSONType }
  948. /** @public */
  949. export declare type BSONTypeAlias = keyof typeof BSONType;
  950. /* Excluded from this release type: BufferPool */
  951. /** @public */
  952. export declare abstract class BulkOperationBase {
  953. isOrdered: boolean;
  954. /* Excluded from this release type: s */
  955. operationId?: number;
  956. private collection;
  957. /* Excluded from this release type: retryWrites */
  958. /* Excluded from this release type: __constructor */
  959. /**
  960. * Add a single insert document to the bulk operation
  961. *
  962. * @example
  963. * ```ts
  964. * const bulkOp = collection.initializeOrderedBulkOp();
  965. *
  966. * // Adds three inserts to the bulkOp.
  967. * bulkOp
  968. * .insert({ a: 1 })
  969. * .insert({ b: 2 })
  970. * .insert({ c: 3 });
  971. * await bulkOp.execute();
  972. * ```
  973. */
  974. insert(document: Document): BulkOperationBase;
  975. /**
  976. * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
  977. * Returns a builder object used to complete the definition of the operation.
  978. *
  979. * @example
  980. * ```ts
  981. * const bulkOp = collection.initializeOrderedBulkOp();
  982. *
  983. * // Add an updateOne to the bulkOp
  984. * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
  985. *
  986. * // Add an updateMany to the bulkOp
  987. * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
  988. *
  989. * // Add an upsert
  990. * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
  991. *
  992. * // Add a deletion
  993. * bulkOp.find({ g: 7 }).deleteOne();
  994. *
  995. * // Add a multi deletion
  996. * bulkOp.find({ h: 8 }).delete();
  997. *
  998. * // Add a replaceOne
  999. * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
  1000. *
  1001. * // Update using a pipeline (requires Mongodb 4.2 or higher)
  1002. * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
  1003. * { $set: { total: { $sum: [ '$y', '$z' ] } } }
  1004. * ]);
  1005. *
  1006. * // All of the ops will now be executed
  1007. * await bulkOp.execute();
  1008. * ```
  1009. */
  1010. find(selector: Document): FindOperators;
  1011. /** Specifies a raw operation to perform in the bulk write. */
  1012. raw(op: AnyBulkWriteOperation): this;
  1013. get length(): number;
  1014. get bsonOptions(): BSONSerializeOptions;
  1015. get writeConcern(): WriteConcern | undefined;
  1016. get batches(): Batch[];
  1017. execute(options?: BulkWriteOptions): Promise<BulkWriteResult>;
  1018. /* Excluded from this release type: handleWriteError */
  1019. abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
  1020. private shouldForceServerObjectId;
  1021. }
  1022. /* Excluded from this release type: BulkOperationPrivate */
  1023. /* Excluded from this release type: BulkResult */
  1024. /** @public */
  1025. export declare interface BulkWriteOperationError {
  1026. index: number;
  1027. code: number;
  1028. errmsg: string;
  1029. errInfo: Document;
  1030. op: Document | UpdateStatement | DeleteStatement;
  1031. }
  1032. /** @public */
  1033. export declare interface BulkWriteOptions extends CommandOperationOptions {
  1034. /**
  1035. * Allow driver to bypass schema validation.
  1036. * @defaultValue `false` - documents will be validated by default
  1037. **/
  1038. bypassDocumentValidation?: boolean;
  1039. /**
  1040. * If true, when an insert fails, don't execute the remaining writes.
  1041. * If false, continue with remaining inserts when one fails.
  1042. * @defaultValue `true` - inserts are ordered by default
  1043. */
  1044. ordered?: boolean;
  1045. /**
  1046. * Force server to assign _id values instead of driver.
  1047. * @defaultValue `false` - the driver generates `_id` fields by default
  1048. **/
  1049. forceServerObjectId?: boolean;
  1050. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  1051. let?: Document;
  1052. /* Excluded from this release type: timeoutContext */
  1053. }
  1054. /**
  1055. * @public
  1056. * The result of a bulk write.
  1057. */
  1058. export declare class BulkWriteResult {
  1059. private readonly result;
  1060. /** Number of documents inserted. */
  1061. readonly insertedCount: number;
  1062. /** Number of documents matched for update. */
  1063. readonly matchedCount: number;
  1064. /** Number of documents modified. */
  1065. readonly modifiedCount: number;
  1066. /** Number of documents deleted. */
  1067. readonly deletedCount: number;
  1068. /** Number of documents upserted. */
  1069. readonly upsertedCount: number;
  1070. /** Upserted document generated Id's, hash key is the index of the originating operation */
  1071. readonly upsertedIds: {
  1072. [key: number]: any;
  1073. };
  1074. /** Inserted document generated Id's, hash key is the index of the originating operation */
  1075. readonly insertedIds: {
  1076. [key: number]: any;
  1077. };
  1078. private static generateIdMap;
  1079. /* Excluded from this release type: __constructor */
  1080. /** Evaluates to true if the bulk operation correctly executes */
  1081. get ok(): number;
  1082. /* Excluded from this release type: getSuccessfullyInsertedIds */
  1083. /** Returns the upserted id at the given index */
  1084. getUpsertedIdAt(index: number): Document | undefined;
  1085. /** Returns raw internal result */
  1086. getRawResponse(): Document;
  1087. /** Returns true if the bulk operation contains a write error */
  1088. hasWriteErrors(): boolean;
  1089. /** Returns the number of write errors from the bulk operation */
  1090. getWriteErrorCount(): number;
  1091. /** Returns a specific write error object */
  1092. getWriteErrorAt(index: number): WriteError | undefined;
  1093. /** Retrieve all write errors */
  1094. getWriteErrors(): WriteError[];
  1095. /** Retrieve the write concern error if one exists */
  1096. getWriteConcernError(): WriteConcernError | undefined;
  1097. toString(): string;
  1098. isOk(): boolean;
  1099. }
  1100. /**
  1101. * MongoDB Driver style callback
  1102. * @public
  1103. */
  1104. export declare type Callback<T = any> = (error?: AnyError, result?: T) => void;
  1105. /* Excluded from this release type: CancellationToken */
  1106. /**
  1107. * Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
  1108. * @public
  1109. */
  1110. export declare class ChangeStream<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> implements AsyncDisposable {
  1111. /**
  1112. * @experimental
  1113. * An alias for {@link ChangeStream.close|ChangeStream.close()}.
  1114. */
  1115. [Symbol.asyncDispose](): Promise<void>;
  1116. pipeline: Document[];
  1117. /**
  1118. * @remarks WriteConcern can still be present on the options because
  1119. * we inherit options from the client/db/collection. The
  1120. * key must be present on the options in order to delete it.
  1121. * This allows typescript to delete the key but will
  1122. * not allow a writeConcern to be assigned as a property on options.
  1123. */
  1124. options: ChangeStreamOptions & {
  1125. writeConcern?: never;
  1126. };
  1127. parent: MongoClient | Db | Collection;
  1128. namespace: MongoDBNamespace;
  1129. type: symbol;
  1130. /* Excluded from this release type: cursor */
  1131. /* Excluded from this release type: cursorStream */
  1132. /* Excluded from this release type: isClosed */
  1133. /* Excluded from this release type: mode */
  1134. /** @event */
  1135. static readonly RESPONSE: "response";
  1136. /** @event */
  1137. static readonly MORE: "more";
  1138. /** @event */
  1139. static readonly INIT: "init";
  1140. /** @event */
  1141. static readonly CLOSE: "close";
  1142. /**
  1143. * Fired for each new matching change in the specified namespace. Attaching a `change`
  1144. * event listener to a Change Stream will switch the stream into flowing mode. Data will
  1145. * then be passed as soon as it is available.
  1146. * @event
  1147. */
  1148. static readonly CHANGE: "change";
  1149. /** @event */
  1150. static readonly END: "end";
  1151. /** @event */
  1152. static readonly ERROR: "error";
  1153. /**
  1154. * Emitted each time the change stream stores a new resume token.
  1155. * @event
  1156. */
  1157. static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged";
  1158. private timeoutContext?;
  1159. /**
  1160. * Note that this property is here to uniquely identify a ChangeStream instance as the owner of
  1161. * the {@link CursorTimeoutContext} instance (see {@link ChangeStream._createChangeStreamCursor}) to ensure
  1162. * that {@link AbstractCursor.close} does not mutate the timeoutContext.
  1163. */
  1164. private contextOwner;
  1165. /* Excluded from this release type: __constructor */
  1166. /** The cached resume token that is used to resume after the most recently returned change. */
  1167. get resumeToken(): ResumeToken;
  1168. /** Check if there is any document still available in the Change Stream */
  1169. hasNext(): Promise<boolean>;
  1170. /** Get the next available document from the Change Stream. */
  1171. next(): Promise<TChange>;
  1172. /**
  1173. * Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned
  1174. */
  1175. tryNext(): Promise<TChange | null>;
  1176. [Symbol.asyncIterator](): AsyncGenerator<TChange, void, void>;
  1177. /** Is the cursor closed */
  1178. get closed(): boolean;
  1179. /**
  1180. * Frees the internal resources used by the change stream.
  1181. */
  1182. close(): Promise<void>;
  1183. /**
  1184. * Return a modified Readable stream including a possible transform method.
  1185. *
  1186. * NOTE: When using a Stream to process change stream events, the stream will
  1187. * NOT automatically resume in the case a resumable error is encountered.
  1188. *
  1189. * @throws MongoChangeStreamError if the underlying cursor or the change stream is closed
  1190. */
  1191. stream(): Readable & AsyncIterable<TChange>;
  1192. /* Excluded from this release type: _setIsEmitter */
  1193. /* Excluded from this release type: _setIsIterator */
  1194. /* Excluded from this release type: _createChangeStreamCursor */
  1195. /* Excluded from this release type: _closeEmitterModeWithError */
  1196. /* Excluded from this release type: _streamEvents */
  1197. /* Excluded from this release type: _endStream */
  1198. /* Excluded from this release type: _processChange */
  1199. /* Excluded from this release type: _processErrorStreamMode */
  1200. /* Excluded from this release type: _processErrorIteratorMode */
  1201. private _resume;
  1202. }
  1203. /**
  1204. * Only present when the `showExpandedEvents` flag is enabled.
  1205. * @public
  1206. * @see https://www.mongodb.com/docs/manual/reference/change-events/modify/#mongodb-data-modify
  1207. */
  1208. export declare interface ChangeStreamCollModDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1209. /** Describes the type of operation represented in this change notification */
  1210. operationType: 'modify';
  1211. }
  1212. /**
  1213. * @public
  1214. * @see https://www.mongodb.com/docs/manual/reference/change-events/create/#mongodb-data-create
  1215. */
  1216. export declare interface ChangeStreamCreateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1217. /** Describes the type of operation represented in this change notification */
  1218. operationType: 'create';
  1219. /**
  1220. * The type of the newly created object.
  1221. *
  1222. * @sinceServerVersion 8.1.0
  1223. */
  1224. nsType?: 'collection' | 'timeseries' | 'view';
  1225. }
  1226. /**
  1227. * Only present when the `showExpandedEvents` flag is enabled.
  1228. * @public
  1229. * @see https://www.mongodb.com/docs/manual/reference/change-events/createIndexes/#mongodb-data-createIndexes
  1230. */
  1231. export declare interface ChangeStreamCreateIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription, ChangeStreamDocumentWallTime {
  1232. /** Describes the type of operation represented in this change notification */
  1233. operationType: 'createIndexes';
  1234. }
  1235. /* Excluded from this release type: ChangeStreamCursor */
  1236. /* Excluded from this release type: ChangeStreamCursorOptions */
  1237. /**
  1238. * @public
  1239. * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event
  1240. */
  1241. export declare interface ChangeStreamDeleteDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1242. /** Describes the type of operation represented in this change notification */
  1243. operationType: 'delete';
  1244. /** Namespace the delete event occurred on */
  1245. ns: ChangeStreamNameSpace;
  1246. /**
  1247. * Contains the pre-image of the modified or deleted document if the
  1248. * pre-image is available for the change event and either 'required' or
  1249. * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
  1250. * when creating the change stream. If 'whenAvailable' was specified but the
  1251. * pre-image is unavailable, this will be explicitly set to null.
  1252. */
  1253. fullDocumentBeforeChange?: TSchema;
  1254. }
  1255. /** @public */
  1256. 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;
  1257. /** @public */
  1258. export declare interface ChangeStreamDocumentCollectionUUID {
  1259. /**
  1260. * The UUID (Binary subtype 4) of the collection that the operation was performed on.
  1261. *
  1262. * Only present when the `showExpandedEvents` flag is enabled.
  1263. *
  1264. * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers
  1265. * flag is enabled.
  1266. *
  1267. * @sinceServerVersion 6.1.0
  1268. */
  1269. collectionUUID: Binary;
  1270. }
  1271. /** @public */
  1272. export declare interface ChangeStreamDocumentCommon {
  1273. /**
  1274. * The id functions as an opaque token for use when resuming an interrupted
  1275. * change stream.
  1276. */
  1277. _id: ResumeToken;
  1278. /**
  1279. * The timestamp from the oplog entry associated with the event.
  1280. * For events that happened as part of a multi-document transaction, the associated change stream
  1281. * notifications will have the same clusterTime value, namely the time when the transaction was committed.
  1282. * On a sharded cluster, events that occur on different shards can have the same clusterTime but be
  1283. * associated with different transactions or even not be associated with any transaction.
  1284. * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
  1285. */
  1286. clusterTime?: Timestamp;
  1287. /**
  1288. * The transaction number.
  1289. * Only present if the operation is part of a multi-document transaction.
  1290. *
  1291. * **NOTE:** txnNumber can be a Long if promoteLongs is set to false
  1292. */
  1293. txnNumber?: number;
  1294. /**
  1295. * The identifier for the session associated with the transaction.
  1296. * Only present if the operation is part of a multi-document transaction.
  1297. */
  1298. lsid?: ServerSessionId;
  1299. /**
  1300. * When the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent
  1301. * stage, events larger than 16MB will be split into multiple events and contain the
  1302. * following information about which fragment the current event is.
  1303. */
  1304. splitEvent?: ChangeStreamSplitEvent;
  1305. }
  1306. /** @public */
  1307. export declare interface ChangeStreamDocumentKey<TSchema extends Document = Document> {
  1308. /**
  1309. * For unsharded collections this contains a single field `_id`.
  1310. * For sharded collections, this will contain all the components of the shard key
  1311. */
  1312. documentKey: {
  1313. _id: InferIdType<TSchema>;
  1314. [shardKey: string]: any;
  1315. };
  1316. }
  1317. /** @public */
  1318. export declare interface ChangeStreamDocumentOperationDescription {
  1319. /**
  1320. * An description of the operation.
  1321. *
  1322. * Only present when the `showExpandedEvents` flag is enabled.
  1323. *
  1324. * @sinceServerVersion 6.1.0
  1325. */
  1326. operationDescription?: Document;
  1327. }
  1328. /** @public */
  1329. export declare interface ChangeStreamDocumentWallTime {
  1330. /**
  1331. * The server date and time of the database operation.
  1332. * wallTime differs from clusterTime in that clusterTime is a timestamp taken from the oplog entry associated with the database operation event.
  1333. * @sinceServerVersion 6.0.0
  1334. */
  1335. wallTime?: Date;
  1336. }
  1337. /**
  1338. * @public
  1339. * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event
  1340. */
  1341. export declare interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentWallTime {
  1342. /** Describes the type of operation represented in this change notification */
  1343. operationType: 'dropDatabase';
  1344. /** The database dropped */
  1345. ns: {
  1346. db: string;
  1347. };
  1348. }
  1349. /**
  1350. * @public
  1351. * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event
  1352. */
  1353. export declare interface ChangeStreamDropDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1354. /** Describes the type of operation represented in this change notification */
  1355. operationType: 'drop';
  1356. /** Namespace the drop event occurred on */
  1357. ns: ChangeStreamNameSpace;
  1358. }
  1359. /**
  1360. * Only present when the `showExpandedEvents` flag is enabled.
  1361. * @public
  1362. * @see https://www.mongodb.com/docs/manual/reference/change-events/dropIndexes/#mongodb-data-dropIndexes
  1363. */
  1364. export declare interface ChangeStreamDropIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription, ChangeStreamDocumentWallTime {
  1365. /** Describes the type of operation represented in this change notification */
  1366. operationType: 'dropIndexes';
  1367. }
  1368. /** @public */
  1369. export declare type ChangeStreamEvents<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> = {
  1370. resumeTokenChanged(token: ResumeToken): void;
  1371. init(response: any): void;
  1372. more(response?: any): void;
  1373. response(): void;
  1374. end(): void;
  1375. error(error: Error): void;
  1376. change(change: TChange): void;
  1377. /**
  1378. * @remarks Note that the `close` event is currently emitted whenever the internal `ChangeStreamCursor`
  1379. * instance is closed, which can occur multiple times for a given `ChangeStream` instance.
  1380. *
  1381. * TODO(NODE-6434): address this issue in NODE-6434
  1382. */
  1383. close(): void;
  1384. };
  1385. /**
  1386. * @public
  1387. * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event
  1388. */
  1389. export declare interface ChangeStreamInsertDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1390. /** Describes the type of operation represented in this change notification */
  1391. operationType: 'insert';
  1392. /** This key will contain the document being inserted */
  1393. fullDocument: TSchema;
  1394. /** Namespace the insert event occurred on */
  1395. ns: ChangeStreamNameSpace;
  1396. }
  1397. /**
  1398. * @public
  1399. * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event
  1400. */
  1401. export declare interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentWallTime {
  1402. /** Describes the type of operation represented in this change notification */
  1403. operationType: 'invalidate';
  1404. }
  1405. /** @public */
  1406. export declare interface ChangeStreamNameSpace {
  1407. db: string;
  1408. coll: string;
  1409. }
  1410. /**
  1411. * 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.
  1412. * @public
  1413. */
  1414. export declare interface ChangeStreamOptions extends Omit<AggregateOptions, 'writeConcern'> {
  1415. /**
  1416. * Allowed values: 'updateLookup', 'whenAvailable', 'required'.
  1417. *
  1418. * When set to 'updateLookup', the change notification for partial updates
  1419. * will include both a delta describing the changes to the document as well
  1420. * as a copy of the entire document that was changed from some time after
  1421. * the change occurred.
  1422. *
  1423. * When set to 'whenAvailable', configures the change stream to return the
  1424. * post-image of the modified document for replace and update change events
  1425. * if the post-image for this event is available.
  1426. *
  1427. * When set to 'required', the same behavior as 'whenAvailable' except that
  1428. * an error is raised if the post-image is not available.
  1429. */
  1430. fullDocument?: string;
  1431. /**
  1432. * Allowed values: 'whenAvailable', 'required', 'off'.
  1433. *
  1434. * The default is to not send a value, which is equivalent to 'off'.
  1435. *
  1436. * When set to 'whenAvailable', configures the change stream to return the
  1437. * pre-image of the modified document for replace, update, and delete change
  1438. * events if it is available.
  1439. *
  1440. * When set to 'required', the same behavior as 'whenAvailable' except that
  1441. * an error is raised if the pre-image is not available.
  1442. */
  1443. fullDocumentBeforeChange?: string;
  1444. /** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */
  1445. maxAwaitTimeMS?: number;
  1446. /**
  1447. * Allows you to start a changeStream after a specified event.
  1448. * @see https://www.mongodb.com/docs/manual/changeStreams/#resumeafter-for-change-streams
  1449. */
  1450. resumeAfter?: ResumeToken;
  1451. /**
  1452. * Similar to resumeAfter, but will allow you to start after an invalidated event.
  1453. * @see https://www.mongodb.com/docs/manual/changeStreams/#startafter-for-change-streams
  1454. */
  1455. startAfter?: ResumeToken;
  1456. /** Will start the changeStream after the specified operationTime. */
  1457. startAtOperationTime?: OperationTime;
  1458. /**
  1459. * The number of documents to return per batch.
  1460. * @see https://www.mongodb.com/docs/manual/reference/command/aggregate
  1461. */
  1462. batchSize?: number;
  1463. /**
  1464. * When enabled, configures the change stream to include extra change events.
  1465. *
  1466. * - createIndexes
  1467. * - dropIndexes
  1468. * - modify
  1469. * - create
  1470. * - shardCollection
  1471. * - reshardCollection
  1472. * - refineCollectionShardKey
  1473. */
  1474. showExpandedEvents?: boolean;
  1475. }
  1476. /**
  1477. * @public
  1478. * @see https://www.mongodb.com/docs/manual/reference/change-events/refineCollectionShardKey/#mongodb-data-refineCollectionShardKey
  1479. */
  1480. export declare interface ChangeStreamRefineCollectionShardKeyDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1481. /** Describes the type of operation represented in this change notification */
  1482. operationType: 'refineCollectionShardKey';
  1483. }
  1484. /**
  1485. * @public
  1486. * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event
  1487. */
  1488. export declare interface ChangeStreamRenameDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1489. /** Describes the type of operation represented in this change notification */
  1490. operationType: 'rename';
  1491. /** The new name for the `ns.coll` collection */
  1492. to: {
  1493. db: string;
  1494. coll: string;
  1495. };
  1496. /** The "from" namespace that the rename occurred on */
  1497. ns: ChangeStreamNameSpace;
  1498. }
  1499. /**
  1500. * @public
  1501. * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event
  1502. */
  1503. export declare interface ChangeStreamReplaceDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentWallTime {
  1504. /** Describes the type of operation represented in this change notification */
  1505. operationType: 'replace';
  1506. /** The fullDocument of a replace event represents the document after the insert of the replacement document */
  1507. fullDocument: TSchema;
  1508. /** Namespace the replace event occurred on */
  1509. ns: ChangeStreamNameSpace;
  1510. /**
  1511. * Contains the pre-image of the modified or deleted document if the
  1512. * pre-image is available for the change event and either 'required' or
  1513. * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
  1514. * when creating the change stream. If 'whenAvailable' was specified but the
  1515. * pre-image is unavailable, this will be explicitly set to null.
  1516. */
  1517. fullDocumentBeforeChange?: TSchema;
  1518. }
  1519. /**
  1520. * @public
  1521. * @see https://www.mongodb.com/docs/manual/reference/change-events/reshardCollection/#mongodb-data-reshardCollection
  1522. */
  1523. export declare interface ChangeStreamReshardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
  1524. /** Describes the type of operation represented in this change notification */
  1525. operationType: 'reshardCollection';
  1526. }
  1527. /**
  1528. * @public
  1529. * @see https://www.mongodb.com/docs/manual/reference/change-events/shardCollection/#mongodb-data-shardCollection
  1530. */
  1531. export declare interface ChangeStreamShardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription, ChangeStreamDocumentWallTime {
  1532. /** Describes the type of operation represented in this change notification */
  1533. operationType: 'shardCollection';
  1534. }
  1535. /** @public */
  1536. export declare interface ChangeStreamSplitEvent {
  1537. /** Which fragment of the change this is. */
  1538. fragment: number;
  1539. /** The total number of fragments. */
  1540. of: number;
  1541. }
  1542. /**
  1543. * @public
  1544. * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event
  1545. */
  1546. export declare interface ChangeStreamUpdateDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
  1547. /** Describes the type of operation represented in this change notification */
  1548. operationType: 'update';
  1549. /**
  1550. * This is only set if `fullDocument` is set to `'updateLookup'`
  1551. * Contains the point-in-time post-image of the modified document if the
  1552. * post-image is available and either 'required' or 'whenAvailable' was
  1553. * specified for the 'fullDocument' option when creating the change stream.
  1554. */
  1555. fullDocument?: TSchema;
  1556. /** Contains a description of updated and removed fields in this operation */
  1557. updateDescription: UpdateDescription<TSchema>;
  1558. /** Namespace the update event occurred on */
  1559. ns: ChangeStreamNameSpace;
  1560. /**
  1561. * Contains the pre-image of the modified or deleted document if the
  1562. * pre-image is available for the change event and either 'required' or
  1563. * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
  1564. * when creating the change stream. If 'whenAvailable' was specified but the
  1565. * pre-image is unavailable, this will be explicitly set to null.
  1566. */
  1567. fullDocumentBeforeChange?: TSchema;
  1568. }
  1569. /** @public */
  1570. export declare interface ClientBulkWriteError {
  1571. code: number;
  1572. message: string;
  1573. }
  1574. /**
  1575. * A mapping of namespace strings to collections schemas.
  1576. * @public
  1577. *
  1578. * @example
  1579. * ```ts
  1580. * type MongoDBSchemas = {
  1581. * 'db.books': Book;
  1582. * 'db.authors': Author;
  1583. * }
  1584. *
  1585. * const model: ClientBulkWriteModel<MongoDBSchemas> = {
  1586. * namespace: 'db.books'
  1587. * name: 'insertOne',
  1588. * document: { title: 'Practical MongoDB Aggregations', authorName: 3 } // error `authorName` cannot be number
  1589. * };
  1590. * ```
  1591. *
  1592. * The type of the `namespace` field narrows other parts of the BulkWriteModel to use the correct schema for type assertions.
  1593. *
  1594. */
  1595. export declare type ClientBulkWriteModel<SchemaMap extends Record<string, Document> = Record<string, Document>> = {
  1596. [Namespace in keyof SchemaMap]: AnyClientBulkWriteModel<SchemaMap[Namespace]> & {
  1597. namespace: Namespace;
  1598. };
  1599. }[keyof SchemaMap];
  1600. /** @public */
  1601. export declare interface ClientBulkWriteOptions extends CommandOperationOptions {
  1602. /**
  1603. * If true, when an insert fails, don't execute the remaining writes.
  1604. * If false, continue with remaining inserts when one fails.
  1605. * @defaultValue `true` - inserts are ordered by default
  1606. */
  1607. ordered?: boolean;
  1608. /**
  1609. * Allow driver to bypass schema validation.
  1610. * @defaultValue `false` - documents will be validated by default
  1611. **/
  1612. bypassDocumentValidation?: boolean;
  1613. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  1614. let?: Document;
  1615. /**
  1616. * Whether detailed results for each successful operation should be included in the returned
  1617. * BulkWriteResult.
  1618. */
  1619. verboseResults?: boolean;
  1620. }
  1621. /** @public */
  1622. export declare interface ClientBulkWriteResult {
  1623. /**
  1624. * Whether the bulk write was acknowledged.
  1625. */
  1626. readonly acknowledged: boolean;
  1627. /**
  1628. * The total number of documents inserted across all insert operations.
  1629. */
  1630. readonly insertedCount: number;
  1631. /**
  1632. * The total number of documents upserted across all update operations.
  1633. */
  1634. readonly upsertedCount: number;
  1635. /**
  1636. * The total number of documents matched across all update operations.
  1637. */
  1638. readonly matchedCount: number;
  1639. /**
  1640. * The total number of documents modified across all update operations.
  1641. */
  1642. readonly modifiedCount: number;
  1643. /**
  1644. * The total number of documents deleted across all delete operations.
  1645. */
  1646. readonly deletedCount: number;
  1647. /**
  1648. * The results of each individual insert operation that was successfully performed.
  1649. */
  1650. readonly insertResults?: ReadonlyMap<number, ClientInsertOneResult>;
  1651. /**
  1652. * The results of each individual update operation that was successfully performed.
  1653. */
  1654. readonly updateResults?: ReadonlyMap<number, ClientUpdateResult>;
  1655. /**
  1656. * The results of each individual delete operation that was successfully performed.
  1657. */
  1658. readonly deleteResults?: ReadonlyMap<number, ClientDeleteResult>;
  1659. }
  1660. /** @public */
  1661. export declare interface ClientDeleteManyModel<TSchema> extends ClientWriteModel {
  1662. name: 'deleteMany';
  1663. /**
  1664. * The filter used to determine if a document should be deleted.
  1665. * For a deleteMany operation, all matches are removed.
  1666. */
  1667. filter: Filter<TSchema>;
  1668. /** Specifies a collation. */
  1669. collation?: CollationOptions;
  1670. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  1671. hint?: Hint;
  1672. }
  1673. /** @public */
  1674. export declare interface ClientDeleteOneModel<TSchema> extends ClientWriteModel {
  1675. name: 'deleteOne';
  1676. /**
  1677. * The filter used to determine if a document should be deleted.
  1678. * For a deleteOne operation, the first match is removed.
  1679. */
  1680. filter: Filter<TSchema>;
  1681. /** Specifies a collation. */
  1682. collation?: CollationOptions;
  1683. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  1684. hint?: Hint;
  1685. }
  1686. /** @public */
  1687. export declare interface ClientDeleteResult {
  1688. /**
  1689. * The number of documents that were deleted.
  1690. */
  1691. deletedCount: number;
  1692. }
  1693. /**
  1694. * @public
  1695. * The public interface for explicit in-use encryption
  1696. */
  1697. export declare class ClientEncryption {
  1698. /* Excluded from this release type: _client */
  1699. /* Excluded from this release type: _keyVaultNamespace */
  1700. /* Excluded from this release type: _keyVaultClient */
  1701. /* Excluded from this release type: _proxyOptions */
  1702. /* Excluded from this release type: _tlsOptions */
  1703. /* Excluded from this release type: _kmsProviders */
  1704. /* Excluded from this release type: _timeoutMS */
  1705. /* Excluded from this release type: _mongoCrypt */
  1706. /* Excluded from this release type: _credentialProviders */
  1707. /* Excluded from this release type: getMongoCrypt */
  1708. /**
  1709. * Create a new encryption instance
  1710. *
  1711. * @example
  1712. * ```ts
  1713. * new ClientEncryption(mongoClient, {
  1714. * keyVaultNamespace: 'client.encryption',
  1715. * kmsProviders: {
  1716. * local: {
  1717. * key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
  1718. * }
  1719. * }
  1720. * });
  1721. * ```
  1722. *
  1723. * @example
  1724. * ```ts
  1725. * new ClientEncryption(mongoClient, {
  1726. * keyVaultNamespace: 'client.encryption',
  1727. * kmsProviders: {
  1728. * aws: {
  1729. * accessKeyId: AWS_ACCESS_KEY,
  1730. * secretAccessKey: AWS_SECRET_KEY
  1731. * }
  1732. * }
  1733. * });
  1734. * ```
  1735. */
  1736. constructor(client: MongoClient, options: ClientEncryptionOptions);
  1737. /**
  1738. * Creates a data key used for explicit encryption and inserts it into the key vault namespace
  1739. *
  1740. * @example
  1741. * ```ts
  1742. * // Using async/await to create a local key
  1743. * const dataKeyId = await clientEncryption.createDataKey('local');
  1744. * ```
  1745. *
  1746. * @example
  1747. * ```ts
  1748. * // Using async/await to create an aws key
  1749. * const dataKeyId = await clientEncryption.createDataKey('aws', {
  1750. * masterKey: {
  1751. * region: 'us-east-1',
  1752. * key: 'xxxxxxxxxxxxxx' // CMK ARN here
  1753. * }
  1754. * });
  1755. * ```
  1756. *
  1757. * @example
  1758. * ```ts
  1759. * // Using async/await to create an aws key with a keyAltName
  1760. * const dataKeyId = await clientEncryption.createDataKey('aws', {
  1761. * masterKey: {
  1762. * region: 'us-east-1',
  1763. * key: 'xxxxxxxxxxxxxx' // CMK ARN here
  1764. * },
  1765. * keyAltNames: [ 'mySpecialKey' ]
  1766. * });
  1767. * ```
  1768. */
  1769. createDataKey(provider: ClientEncryptionDataKeyProvider, options?: ClientEncryptionCreateDataKeyProviderOptions): Promise<UUID>;
  1770. /**
  1771. * Searches the keyvault for any data keys matching the provided filter. If there are matches, rewrapManyDataKey then attempts to re-wrap the data keys using the provided options.
  1772. *
  1773. * If no matches are found, then no bulk write is performed.
  1774. *
  1775. * @example
  1776. * ```ts
  1777. * // rewrapping all data data keys (using a filter that matches all documents)
  1778. * const filter = {};
  1779. *
  1780. * const result = await clientEncryption.rewrapManyDataKey(filter);
  1781. * if (result.bulkWriteResult != null) {
  1782. * // keys were re-wrapped, results will be available in the bulkWrite object.
  1783. * }
  1784. * ```
  1785. *
  1786. * @example
  1787. * ```ts
  1788. * // attempting to rewrap all data keys with no matches
  1789. * const filter = { _id: new Binary() } // assume _id matches no documents in the database
  1790. * const result = await clientEncryption.rewrapManyDataKey(filter);
  1791. *
  1792. * if (result.bulkWriteResult == null) {
  1793. * // no keys matched, `bulkWriteResult` does not exist on the result object
  1794. * }
  1795. * ```
  1796. */
  1797. rewrapManyDataKey(filter: Filter<DataKey>, options?: ClientEncryptionRewrapManyDataKeyProviderOptions): Promise<{
  1798. bulkWriteResult?: BulkWriteResult;
  1799. }>;
  1800. /**
  1801. * Deletes the key with the provided id from the keyvault, if it exists.
  1802. *
  1803. * @example
  1804. * ```ts
  1805. * // delete a key by _id
  1806. * const id = new Binary(); // id is a bson binary subtype 4 object
  1807. * const { deletedCount } = await clientEncryption.deleteKey(id);
  1808. *
  1809. * if (deletedCount != null && deletedCount > 0) {
  1810. * // successful deletion
  1811. * }
  1812. * ```
  1813. *
  1814. */
  1815. deleteKey(_id: Binary): Promise<DeleteResult>;
  1816. /**
  1817. * Finds all the keys currently stored in the keyvault.
  1818. *
  1819. * This method will not throw.
  1820. *
  1821. * @returns a FindCursor over all keys in the keyvault.
  1822. * @example
  1823. * ```ts
  1824. * // fetching all keys
  1825. * const keys = await clientEncryption.getKeys().toArray();
  1826. * ```
  1827. */
  1828. getKeys(): FindCursor<DataKey>;
  1829. /**
  1830. * Finds a key in the keyvault with the specified _id.
  1831. *
  1832. * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
  1833. * match the id. The promise rejects with an error if an error is thrown.
  1834. * @example
  1835. * ```ts
  1836. * // getting a key by id
  1837. * const id = new Binary(); // id is a bson binary subtype 4 object
  1838. * const key = await clientEncryption.getKey(id);
  1839. * if (!key) {
  1840. * // key is null if there was no matching key
  1841. * }
  1842. * ```
  1843. */
  1844. getKey(_id: Binary): Promise<DataKey | null>;
  1845. /**
  1846. * Finds a key in the keyvault which has the specified keyAltName.
  1847. *
  1848. * @param keyAltName - a keyAltName to search for a key
  1849. * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
  1850. * match the keyAltName. The promise rejects with an error if an error is thrown.
  1851. * @example
  1852. * ```ts
  1853. * // get a key by alt name
  1854. * const keyAltName = 'keyAltName';
  1855. * const key = await clientEncryption.getKeyByAltName(keyAltName);
  1856. * if (!key) {
  1857. * // key is null if there is no matching key
  1858. * }
  1859. * ```
  1860. */
  1861. getKeyByAltName(keyAltName: string): Promise<WithId<DataKey> | null>;
  1862. /**
  1863. * Adds a keyAltName to a key identified by the provided _id.
  1864. *
  1865. * This method resolves to/returns the *old* key value (prior to adding the new altKeyName).
  1866. *
  1867. * @param _id - The id of the document to update.
  1868. * @param keyAltName - a keyAltName to search for a key
  1869. * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
  1870. * match the id. The promise rejects with an error if an error is thrown.
  1871. * @example
  1872. * ```ts
  1873. * // adding an keyAltName to a data key
  1874. * const id = new Binary(); // id is a bson binary subtype 4 object
  1875. * const keyAltName = 'keyAltName';
  1876. * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName);
  1877. * if (!oldKey) {
  1878. * // null is returned if there is no matching document with an id matching the supplied id
  1879. * }
  1880. * ```
  1881. */
  1882. addKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null>;
  1883. /**
  1884. * Adds a keyAltName to a key identified by the provided _id.
  1885. *
  1886. * This method resolves to/returns the *old* key value (prior to removing the new altKeyName).
  1887. *
  1888. * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document.
  1889. *
  1890. * @param _id - The id of the document to update.
  1891. * @param keyAltName - a keyAltName to search for a key
  1892. * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
  1893. * match the id. The promise rejects with an error if an error is thrown.
  1894. * @example
  1895. * ```ts
  1896. * // removing a key alt name from a data key
  1897. * const id = new Binary(); // id is a bson binary subtype 4 object
  1898. * const keyAltName = 'keyAltName';
  1899. * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName);
  1900. *
  1901. * if (!oldKey) {
  1902. * // null is returned if there is no matching document with an id matching the supplied id
  1903. * }
  1904. * ```
  1905. */
  1906. removeKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null>;
  1907. /**
  1908. * A convenience method for creating an encrypted collection.
  1909. * This method will create data keys for any encryptedFields that do not have a `keyId` defined
  1910. * and then create a new collection with the full set of encryptedFields.
  1911. *
  1912. * @param db - A Node.js driver Db object with which to create the collection
  1913. * @param name - The name of the collection to be created
  1914. * @param options - Options for createDataKey and for createCollection
  1915. * @returns created collection and generated encryptedFields
  1916. * @throws MongoCryptCreateDataKeyError - If part way through the process a createDataKey invocation fails, an error will be rejected that has the partial `encryptedFields` that were created.
  1917. * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created.
  1918. */
  1919. createEncryptedCollection<TSchema extends Document = Document>(db: Db, name: string, options: {
  1920. provider: ClientEncryptionDataKeyProvider;
  1921. createCollectionOptions: Omit<CreateCollectionOptions, 'encryptedFields'> & {
  1922. encryptedFields: Document;
  1923. };
  1924. masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions;
  1925. }): Promise<{
  1926. collection: Collection<TSchema>;
  1927. encryptedFields: Document;
  1928. }>;
  1929. /**
  1930. * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
  1931. * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
  1932. *
  1933. * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON
  1934. * @param options -
  1935. * @returns a Promise that either resolves with the encrypted value, or rejects with an error.
  1936. *
  1937. * @example
  1938. * ```ts
  1939. * // Encryption with async/await api
  1940. * async function encryptMyData(value) {
  1941. * const keyId = await clientEncryption.createDataKey('local');
  1942. * return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
  1943. * }
  1944. * ```
  1945. *
  1946. * @example
  1947. * ```ts
  1948. * // Encryption using a keyAltName
  1949. * async function encryptMyData(value) {
  1950. * await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
  1951. * return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
  1952. * }
  1953. * ```
  1954. */
  1955. encrypt(value: unknown, options: ClientEncryptionEncryptOptions): Promise<Binary>;
  1956. /**
  1957. * Encrypts a Match Expression or Aggregate Expression to query a range index.
  1958. *
  1959. * Only supported when queryType is "range" and algorithm is "Range".
  1960. *
  1961. * @param expression - a BSON document of one of the following forms:
  1962. * 1. A Match Expression of this form:
  1963. * `{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}`
  1964. * 2. An Aggregate Expression of this form:
  1965. * `{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}`
  1966. *
  1967. * `$gt` may also be `$gte`. `$lt` may also be `$lte`.
  1968. *
  1969. * @param options -
  1970. * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error.
  1971. */
  1972. encryptExpression(expression: Document, options: ClientEncryptionEncryptOptions): Promise<Binary>;
  1973. /**
  1974. * Explicitly decrypt a provided encrypted value
  1975. *
  1976. * @param value - An encrypted value
  1977. * @returns a Promise that either resolves with the decrypted value, or rejects with an error
  1978. *
  1979. * @example
  1980. * ```ts
  1981. * // Decrypting value with async/await API
  1982. * async function decryptMyValue(value) {
  1983. * return clientEncryption.decrypt(value);
  1984. * }
  1985. * ```
  1986. */
  1987. decrypt<T = any>(value: Binary): Promise<T>;
  1988. /* Excluded from this release type: askForKMSCredentials */
  1989. static get libmongocryptVersion(): string;
  1990. /* Excluded from this release type: _encrypt */
  1991. }
  1992. /**
  1993. * @public
  1994. * Options to provide when creating a new data key.
  1995. */
  1996. export declare interface ClientEncryptionCreateDataKeyProviderOptions {
  1997. /**
  1998. * Identifies a new KMS-specific key used to encrypt the new data key
  1999. */
  2000. masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | KMIPEncryptionKeyOptions | undefined;
  2001. /**
  2002. * An optional list of string alternate names used to reference a key.
  2003. * If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id.
  2004. */
  2005. keyAltNames?: string[] | undefined;
  2006. /** @experimental */
  2007. keyMaterial?: Buffer | Binary;
  2008. /* Excluded from this release type: timeoutContext */
  2009. }
  2010. /**
  2011. * @public
  2012. *
  2013. * A data key provider. Allowed values:
  2014. *
  2015. * - aws, gcp, local, kmip or azure
  2016. * - (`mongodb-client-encryption>=6.0.1` only) a named key, in the form of:
  2017. * `aws:<name>`, `gcp:<name>`, `local:<name>`, `kmip:<name>`, `azure:<name>`
  2018. * where `name` is an alphanumeric string, underscores allowed.
  2019. */
  2020. export declare type ClientEncryptionDataKeyProvider = keyof KMSProviders;
  2021. /**
  2022. * @public
  2023. * Options to provide when encrypting data.
  2024. */
  2025. export declare interface ClientEncryptionEncryptOptions {
  2026. /**
  2027. * The algorithm to use for encryption.
  2028. */
  2029. algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' | 'AEAD_AES_256_CBC_HMAC_SHA_512-Random' | 'Indexed' | 'Unindexed' | 'Range' | 'TextPreview';
  2030. /**
  2031. * The id of the Binary dataKey to use for encryption
  2032. */
  2033. keyId?: Binary;
  2034. /**
  2035. * A unique string name corresponding to an already existing dataKey.
  2036. */
  2037. keyAltName?: string;
  2038. /** The contention factor. */
  2039. contentionFactor?: bigint | number;
  2040. /**
  2041. * The query type.
  2042. */
  2043. queryType?: 'equality' | 'range' | 'prefixPreview' | 'suffixPreview' | 'substringPreview';
  2044. /** The index options for a Queryable Encryption field supporting "range" queries.*/
  2045. rangeOptions?: RangeOptions;
  2046. /**
  2047. * Options for a Queryable Encryption field supporting text queries. Only valid when `algorithm` is `TextPreview`.
  2048. *
  2049. * @experimental Public Technical Preview: `textPreview` is an experimental feature and may break at any time.
  2050. */
  2051. textOptions?: TextQueryOptions;
  2052. }
  2053. /**
  2054. * @public
  2055. * Additional settings to provide when creating a new `ClientEncryption` instance.
  2056. */
  2057. export declare interface ClientEncryptionOptions {
  2058. /**
  2059. * The namespace of the key vault, used to store encryption keys
  2060. */
  2061. keyVaultNamespace: string;
  2062. /**
  2063. * A MongoClient used to fetch keys from a key vault. Defaults to client.
  2064. */
  2065. keyVaultClient?: MongoClient | undefined;
  2066. /**
  2067. * Options for specific KMS providers to use
  2068. */
  2069. kmsProviders?: KMSProviders;
  2070. /**
  2071. * Options for user provided custom credential providers.
  2072. */
  2073. credentialProviders?: CredentialProviders;
  2074. /**
  2075. * Options for specifying a Socks5 proxy to use for connecting to the KMS.
  2076. */
  2077. proxyOptions?: ProxyOptions;
  2078. /**
  2079. * TLS options for kms providers to use.
  2080. */
  2081. tlsOptions?: CSFLEKMSTlsOptions;
  2082. /**
  2083. * Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
  2084. */
  2085. keyExpirationMS?: number;
  2086. /**
  2087. * @experimental
  2088. *
  2089. * The timeout setting to be used for all the operations on ClientEncryption.
  2090. *
  2091. * When provided, `timeoutMS` is used as the timeout for each operation executed on
  2092. * the ClientEncryption object. For example:
  2093. *
  2094. * ```typescript
  2095. * const clientEncryption = new ClientEncryption(client, {
  2096. * timeoutMS: 1_000
  2097. * kmsProviders: { local: { key: '<KEY>' } }
  2098. * });
  2099. *
  2100. * // `1_000` is used as the timeout for createDataKey call
  2101. * await clientEncryption.createDataKey('local');
  2102. * ```
  2103. *
  2104. * If `timeoutMS` is configured on the provided client, the client's `timeoutMS` value
  2105. * will be used unless `timeoutMS` is also provided as a client encryption option.
  2106. *
  2107. * ```typescript
  2108. * const client = new MongoClient('<uri>', { timeoutMS: 2_000 });
  2109. *
  2110. * // timeoutMS is set to 1_000 on clientEncryption
  2111. * const clientEncryption = new ClientEncryption(client, {
  2112. * timeoutMS: 1_000
  2113. * kmsProviders: { local: { key: '<KEY>' } }
  2114. * });
  2115. * ```
  2116. */
  2117. timeoutMS?: number;
  2118. }
  2119. /**
  2120. * @public
  2121. * @experimental
  2122. */
  2123. export declare interface ClientEncryptionRewrapManyDataKeyProviderOptions {
  2124. provider: ClientEncryptionDataKeyProvider;
  2125. masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | KMIPEncryptionKeyOptions | undefined;
  2126. }
  2127. /**
  2128. * @public
  2129. * @experimental
  2130. */
  2131. export declare interface ClientEncryptionRewrapManyDataKeyResult {
  2132. /** The result of rewrapping data keys. If unset, no keys matched the filter. */
  2133. bulkWriteResult?: BulkWriteResult;
  2134. }
  2135. /**
  2136. * @public
  2137. *
  2138. * Socket options to use for KMS requests.
  2139. */
  2140. export declare type ClientEncryptionSocketOptions = Pick<MongoClientOptions, 'autoSelectFamily' | 'autoSelectFamilyAttemptTimeout'>;
  2141. /**
  2142. * @public
  2143. *
  2144. * TLS options to use when connecting. The spec specifically calls out which insecure
  2145. * tls options are not allowed:
  2146. *
  2147. * - tlsAllowInvalidCertificates
  2148. * - tlsAllowInvalidHostnames
  2149. * - tlsInsecure
  2150. *
  2151. * These options are not included in the type, and are ignored if provided.
  2152. */
  2153. export declare type ClientEncryptionTlsOptions = Pick<MongoClientOptions, 'tlsCAFile' | 'tlsCertificateKeyFile' | 'tlsCertificateKeyFilePassword' | 'secureContext'>;
  2154. /** @public */
  2155. export declare interface ClientInsertOneModel<TSchema> extends ClientWriteModel {
  2156. name: 'insertOne';
  2157. /** The document to insert. */
  2158. document: OptionalId<TSchema>;
  2159. }
  2160. /** @public */
  2161. export declare interface ClientInsertOneResult {
  2162. /**
  2163. * The _id of the inserted document.
  2164. */
  2165. insertedId: any;
  2166. }
  2167. /* Excluded from this release type: ClientMetadata */
  2168. /** @public */
  2169. export declare interface ClientReplaceOneModel<TSchema> extends ClientWriteModel {
  2170. name: 'replaceOne';
  2171. /**
  2172. * The filter used to determine if a document should be replaced.
  2173. * For a replaceOne operation, the first match is replaced.
  2174. */
  2175. filter: Filter<TSchema>;
  2176. /** The document with which to replace the matched document. */
  2177. replacement: WithoutId<TSchema>;
  2178. /** Specifies a collation. */
  2179. collation?: CollationOptions;
  2180. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  2181. hint?: Hint;
  2182. /** When true, creates a new document if no document matches the query. */
  2183. upsert?: boolean;
  2184. /** Specifies the sort order for the documents matched by the filter. */
  2185. sort?: Sort;
  2186. }
  2187. /**
  2188. * A class representing a client session on the server
  2189. *
  2190. * NOTE: not meant to be instantiated directly.
  2191. * @public
  2192. */
  2193. export declare class ClientSession extends TypedEventEmitter<ClientSessionEvents> implements AsyncDisposable {
  2194. /* Excluded from this release type: client */
  2195. /* Excluded from this release type: sessionPool */
  2196. hasEnded: boolean;
  2197. clientOptions: MongoOptions;
  2198. supports: {
  2199. causalConsistency: boolean;
  2200. };
  2201. clusterTime?: ClusterTime;
  2202. operationTime?: Timestamp;
  2203. explicit: boolean;
  2204. /* Excluded from this release type: owner */
  2205. defaultTransactionOptions: TransactionOptions;
  2206. /* Excluded from this release type: transaction */
  2207. /* Excluded from this release type: commitAttempted */
  2208. readonly snapshotEnabled: boolean;
  2209. /* Excluded from this release type: _serverSession */
  2210. /* Excluded from this release type: snapshotTime */
  2211. /* Excluded from this release type: pinnedConnection */
  2212. /* Excluded from this release type: txnNumberIncrement */
  2213. /**
  2214. * @experimental
  2215. * Specifies the time an operation in a given `ClientSession` will run until it throws a timeout error
  2216. */
  2217. timeoutMS?: number;
  2218. /* Excluded from this release type: timeoutContext */
  2219. /* Excluded from this release type: __constructor */
  2220. /** The server id associated with this session */
  2221. get id(): ServerSessionId | undefined;
  2222. get serverSession(): ServerSession;
  2223. get loadBalanced(): boolean;
  2224. /* Excluded from this release type: pin */
  2225. /* Excluded from this release type: unpin */
  2226. get isPinned(): boolean;
  2227. /**
  2228. * Frees any client-side resources held by the current session. If a session is in a transaction,
  2229. * the transaction is aborted.
  2230. *
  2231. * Does not end the session on the server.
  2232. *
  2233. * @param options - Optional settings. Currently reserved for future use
  2234. */
  2235. endSession(options?: EndSessionOptions): Promise<void>;
  2236. /**
  2237. * @experimental
  2238. * An alias for {@link ClientSession.endSession|ClientSession.endSession()}.
  2239. */
  2240. [Symbol.asyncDispose](): Promise<void>;
  2241. /**
  2242. * Advances the operationTime for a ClientSession.
  2243. *
  2244. * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
  2245. */
  2246. advanceOperationTime(operationTime: Timestamp): void;
  2247. /**
  2248. * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
  2249. *
  2250. * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature
  2251. */
  2252. advanceClusterTime(clusterTime: ClusterTime): void;
  2253. /**
  2254. * Used to determine if this session equals another
  2255. *
  2256. * @param session - The session to compare to
  2257. */
  2258. equals(session: ClientSession): boolean;
  2259. /**
  2260. * Increment the transaction number on the internal ServerSession
  2261. *
  2262. * @privateRemarks
  2263. * This helper increments a value stored on the client session that will be
  2264. * added to the serverSession's txnNumber upon applying it to a command.
  2265. * This is because the serverSession is lazily acquired after a connection is obtained
  2266. */
  2267. incrementTransactionNumber(): void;
  2268. /** @returns whether this session is currently in a transaction or not */
  2269. inTransaction(): boolean;
  2270. /**
  2271. * Starts a new transaction with the given options.
  2272. *
  2273. * @remarks
  2274. * **IMPORTANT**: Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
  2275. * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
  2276. * undefined behaviour.
  2277. *
  2278. * @param options - Options for the transaction
  2279. */
  2280. startTransaction(options?: TransactionOptions): void;
  2281. /**
  2282. * Commits the currently active transaction in this session.
  2283. *
  2284. * @param options - Optional options, can be used to override `defaultTimeoutMS`.
  2285. */
  2286. commitTransaction(options?: {
  2287. timeoutMS?: number;
  2288. }): Promise<void>;
  2289. /**
  2290. * Aborts the currently active transaction in this session.
  2291. *
  2292. * @param options - Optional options, can be used to override `defaultTimeoutMS`.
  2293. */
  2294. abortTransaction(options?: {
  2295. timeoutMS?: number;
  2296. }): Promise<void>;
  2297. /* Excluded from this release type: abortTransaction */
  2298. /**
  2299. * This is here to ensure that ClientSession is never serialized to BSON.
  2300. */
  2301. toBSON(): never;
  2302. /**
  2303. * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed.
  2304. *
  2305. * **IMPORTANT:** This method requires the function passed in to return a Promise. That promise must be made by `await`-ing all operations in such a way that rejections are propagated to the returned promise.
  2306. *
  2307. * **IMPORTANT:** Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
  2308. * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
  2309. * undefined behaviour.
  2310. *
  2311. * **IMPORTANT:** When running an operation inside a `withTransaction` callback, if it is not
  2312. * provided the explicit session in its options, it will not be part of the transaction and it will not respect timeoutMS.
  2313. *
  2314. *
  2315. * @remarks
  2316. * - If all operations successfully complete and the `commitTransaction` operation is successful, then the provided function will return the result of the provided function.
  2317. * - If the transaction is unable to complete or an error is thrown from within the provided function, then the provided function will throw an error.
  2318. * - If the transaction is manually aborted within the provided function it will not throw.
  2319. * - If the driver needs to attempt to retry the operations, the provided function may be called multiple times.
  2320. *
  2321. * Checkout a descriptive example here:
  2322. * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
  2323. *
  2324. * If a command inside withTransaction fails:
  2325. * - It may cause the transaction on the server to be aborted.
  2326. * - This situation is normally handled transparently by the driver.
  2327. * - However, if the application catches such an error and does not rethrow it, the driver will not be able to determine whether the transaction was aborted or not.
  2328. * - The driver will then retry the transaction indefinitely.
  2329. *
  2330. * To avoid this situation, the application must not silently handle errors within the provided function.
  2331. * If the application needs to handle errors within, it must await all operations such that if an operation is rejected it becomes the rejection of the callback function passed into withTransaction.
  2332. *
  2333. * @param fn - callback to run within a transaction
  2334. * @param options - optional settings for the transaction
  2335. * @returns A raw command response or undefined
  2336. */
  2337. withTransaction<T = any>(fn: WithTransactionCallback<T>, options?: TransactionOptions & {
  2338. /**
  2339. * Configures a timeoutMS expiry for the entire withTransactionCallback.
  2340. *
  2341. * @remarks
  2342. * - The remaining timeout will not be applied to callback operations that do not use the ClientSession.
  2343. * - Overriding timeoutMS for operations executed using the explicit session inside the provided callback will result in a client-side error.
  2344. */
  2345. timeoutMS?: number;
  2346. }): Promise<T>;
  2347. }
  2348. /** @public */
  2349. export declare type ClientSessionEvents = {
  2350. ended(session: ClientSession): void;
  2351. };
  2352. /** @public */
  2353. export declare interface ClientSessionOptions {
  2354. /** Whether causal consistency should be enabled on this session */
  2355. causalConsistency?: boolean;
  2356. /** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */
  2357. snapshot?: boolean;
  2358. /** The default TransactionOptions to use for transactions started on this session. */
  2359. defaultTransactionOptions?: TransactionOptions;
  2360. /**
  2361. * @public
  2362. * @experimental
  2363. * An overriding timeoutMS value to use for a client-side timeout.
  2364. * If not provided the session uses the timeoutMS specified on the MongoClient.
  2365. */
  2366. defaultTimeoutMS?: number;
  2367. /* Excluded from this release type: owner */
  2368. /* Excluded from this release type: explicit */
  2369. /* Excluded from this release type: initialClusterTime */
  2370. }
  2371. /** @public */
  2372. export declare interface ClientUpdateManyModel<TSchema> extends ClientWriteModel {
  2373. name: 'updateMany';
  2374. /**
  2375. * The filter used to determine if a document should be updated.
  2376. * For an updateMany operation, all matches are updated.
  2377. */
  2378. filter: Filter<TSchema>;
  2379. /**
  2380. * The modifications to apply. The value can be either:
  2381. * UpdateFilter<Document> - A document that contains update operator expressions,
  2382. * Document[] - an aggregation pipeline.
  2383. */
  2384. update: UpdateFilter<TSchema> | Document[];
  2385. /** A set of filters specifying to which array elements an update should apply. */
  2386. arrayFilters?: Document[];
  2387. /** Specifies a collation. */
  2388. collation?: CollationOptions;
  2389. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  2390. hint?: Hint;
  2391. /** When true, creates a new document if no document matches the query. */
  2392. upsert?: boolean;
  2393. }
  2394. /** @public */
  2395. export declare interface ClientUpdateOneModel<TSchema> extends ClientWriteModel {
  2396. name: 'updateOne';
  2397. /**
  2398. * The filter used to determine if a document should be updated.
  2399. * For an updateOne operation, the first match is updated.
  2400. */
  2401. filter: Filter<TSchema>;
  2402. /**
  2403. * The modifications to apply. The value can be either:
  2404. * UpdateFilter<Document> - A document that contains update operator expressions,
  2405. * Document[] - an aggregation pipeline.
  2406. */
  2407. update: UpdateFilter<TSchema> | Document[];
  2408. /** A set of filters specifying to which array elements an update should apply. */
  2409. arrayFilters?: Document[];
  2410. /** Specifies a collation. */
  2411. collation?: CollationOptions;
  2412. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  2413. hint?: Hint;
  2414. /** When true, creates a new document if no document matches the query. */
  2415. upsert?: boolean;
  2416. /** Specifies the sort order for the documents matched by the filter. */
  2417. sort?: Sort;
  2418. }
  2419. /** @public */
  2420. export declare interface ClientUpdateResult {
  2421. /**
  2422. * The number of documents that matched the filter.
  2423. */
  2424. matchedCount: number;
  2425. /**
  2426. * The number of documents that were modified.
  2427. */
  2428. modifiedCount: number;
  2429. /**
  2430. * The _id field of the upserted document if an upsert occurred.
  2431. *
  2432. * It MUST be possible to discern between a BSON Null upserted ID value and this field being
  2433. * unset. If necessary, drivers MAY add a didUpsert boolean field to differentiate between
  2434. * these two cases.
  2435. */
  2436. upsertedId?: any;
  2437. /**
  2438. * Determines if the upsert did include an _id, which includes the case of the _id being null.
  2439. */
  2440. didUpsert: boolean;
  2441. }
  2442. /** @public */
  2443. export declare interface ClientWriteModel {
  2444. /**
  2445. * The namespace for the write.
  2446. *
  2447. * A namespace is a combination of the database name and the name of the collection: `<database-name>.<collection>`.
  2448. * All documents belong to a namespace.
  2449. *
  2450. * @see https://www.mongodb.com/docs/manual/reference/limits/#std-label-faq-dev-namespace
  2451. */
  2452. namespace: string;
  2453. }
  2454. /** @public
  2455. * Configuration options for clustered collections
  2456. * @see https://www.mongodb.com/docs/manual/core/clustered-collections/
  2457. */
  2458. export declare interface ClusteredCollectionOptions extends Document {
  2459. name?: string;
  2460. key: Document;
  2461. unique: boolean;
  2462. }
  2463. /**
  2464. * @public
  2465. * Gossiped in component for the cluster time tracking the state of user databases
  2466. * across the cluster. It may optionally include a signature identifying the process that
  2467. * generated such a value.
  2468. */
  2469. export declare interface ClusterTime {
  2470. clusterTime: Timestamp;
  2471. /** Used to validate the identity of a request or response's ClusterTime. */
  2472. signature?: {
  2473. hash: Binary;
  2474. keyId: Long;
  2475. };
  2476. }
  2477. export { Code }
  2478. /** @public */
  2479. export declare interface CollationOptions {
  2480. locale: string;
  2481. caseLevel?: boolean;
  2482. caseFirst?: string;
  2483. strength?: number;
  2484. numericOrdering?: boolean;
  2485. alternate?: string;
  2486. maxVariable?: string;
  2487. backwards?: boolean;
  2488. normalization?: boolean;
  2489. }
  2490. /**
  2491. * The **Collection** class is an internal class that embodies a MongoDB collection
  2492. * allowing for insert/find/update/delete and other command operation on that MongoDB collection.
  2493. *
  2494. * **COLLECTION Cannot directly be instantiated**
  2495. * @public
  2496. *
  2497. * @example
  2498. * ```ts
  2499. * import { MongoClient } from 'mongodb';
  2500. *
  2501. * interface Pet {
  2502. * name: string;
  2503. * kind: 'dog' | 'cat' | 'fish';
  2504. * }
  2505. *
  2506. * const client = new MongoClient('mongodb://localhost:27017');
  2507. * const pets = client.db().collection<Pet>('pets');
  2508. *
  2509. * const petCursor = pets.find();
  2510. *
  2511. * for await (const pet of petCursor) {
  2512. * console.log(`${pet.name} is a ${pet.kind}!`);
  2513. * }
  2514. * ```
  2515. */
  2516. export declare class Collection<TSchema extends Document = Document> {
  2517. /* Excluded from this release type: s */
  2518. /* Excluded from this release type: client */
  2519. /**
  2520. * Get the database object for the collection.
  2521. */
  2522. readonly db: Db;
  2523. /* Excluded from this release type: __constructor */
  2524. /**
  2525. * The name of the database this collection belongs to
  2526. */
  2527. get dbName(): string;
  2528. /**
  2529. * The name of this collection
  2530. */
  2531. get collectionName(): string;
  2532. /**
  2533. * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
  2534. */
  2535. get namespace(): string;
  2536. /* Excluded from this release type: fullNamespace */
  2537. /**
  2538. * The current readConcern of the collection. If not explicitly defined for
  2539. * this collection, will be inherited from the parent DB
  2540. */
  2541. get readConcern(): ReadConcern | undefined;
  2542. /**
  2543. * The current readPreference of the collection. If not explicitly defined for
  2544. * this collection, will be inherited from the parent DB
  2545. */
  2546. get readPreference(): ReadPreference | undefined;
  2547. get bsonOptions(): BSONSerializeOptions;
  2548. /**
  2549. * The current writeConcern of the collection. If not explicitly defined for
  2550. * this collection, will be inherited from the parent DB
  2551. */
  2552. get writeConcern(): WriteConcern | undefined;
  2553. /** The current index hint for the collection */
  2554. get hint(): Hint | undefined;
  2555. set hint(v: Hint | undefined);
  2556. get timeoutMS(): number | undefined;
  2557. /**
  2558. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  2559. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  2560. * can be overridden by setting the **forceServerObjectId** flag.
  2561. *
  2562. * @param doc - The document to insert
  2563. * @param options - Optional settings for the command
  2564. */
  2565. insertOne(doc: OptionalUnlessRequiredId<TSchema>, options?: InsertOneOptions): Promise<InsertOneResult<TSchema>>;
  2566. /**
  2567. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  2568. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  2569. * can be overridden by setting the **forceServerObjectId** flag.
  2570. *
  2571. * @param docs - The documents to insert
  2572. * @param options - Optional settings for the command
  2573. */
  2574. insertMany(docs: ReadonlyArray<OptionalUnlessRequiredId<TSchema>>, options?: BulkWriteOptions): Promise<InsertManyResult<TSchema>>;
  2575. /**
  2576. * Perform a bulkWrite operation without a fluent API
  2577. *
  2578. * Legal operation types are
  2579. * - `insertOne`
  2580. * - `replaceOne`
  2581. * - `updateOne`
  2582. * - `updateMany`
  2583. * - `deleteOne`
  2584. * - `deleteMany`
  2585. *
  2586. * If documents passed in do not contain the **_id** field,
  2587. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  2588. * can be overridden by setting the **forceServerObjectId** flag.
  2589. *
  2590. * @param operations - Bulk operations to perform
  2591. * @param options - Optional settings for the command
  2592. * @throws MongoDriverError if operations is not an array
  2593. */
  2594. bulkWrite(operations: ReadonlyArray<AnyBulkWriteOperation<TSchema>>, options?: BulkWriteOptions): Promise<BulkWriteResult>;
  2595. /**
  2596. * Update a single document in a collection
  2597. *
  2598. * The value of `update` can be either:
  2599. * - UpdateFilter<TSchema> - A document that contains update operator expressions,
  2600. * - Document[] - an aggregation pipeline.
  2601. *
  2602. * @param filter - The filter used to select the document to update
  2603. * @param update - The modifications to apply
  2604. * @param options - Optional settings for the command
  2605. */
  2606. updateOne(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions & {
  2607. sort?: Sort;
  2608. }): Promise<UpdateResult<TSchema>>;
  2609. /**
  2610. * Replace a document in a collection with another document
  2611. *
  2612. * @param filter - The filter used to select the document to replace
  2613. * @param replacement - The Document that replaces the matching document
  2614. * @param options - Optional settings for the command
  2615. */
  2616. replaceOne(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options?: ReplaceOptions): Promise<UpdateResult<TSchema>>;
  2617. /**
  2618. * Update multiple documents in a collection
  2619. *
  2620. * The value of `update` can be either:
  2621. * - UpdateFilter<TSchema> - A document that contains update operator expressions,
  2622. * - Document[] - an aggregation pipeline.
  2623. *
  2624. * @param filter - The filter used to select the document to update
  2625. * @param update - The modifications to apply
  2626. * @param options - Optional settings for the command
  2627. */
  2628. updateMany(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions): Promise<UpdateResult<TSchema>>;
  2629. /**
  2630. * Delete a document from a collection
  2631. *
  2632. * @param filter - The filter used to select the document to remove
  2633. * @param options - Optional settings for the command
  2634. */
  2635. deleteOne(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>;
  2636. /**
  2637. * Delete multiple documents from a collection
  2638. *
  2639. * @param filter - The filter used to select the documents to remove
  2640. * @param options - Optional settings for the command
  2641. */
  2642. deleteMany(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>;
  2643. /**
  2644. * Rename the collection.
  2645. *
  2646. * @remarks
  2647. * This operation does not inherit options from the Db or MongoClient.
  2648. *
  2649. * @param newName - New name of of the collection.
  2650. * @param options - Optional settings for the command
  2651. */
  2652. rename(newName: string, options?: RenameOptions): Promise<Collection>;
  2653. /**
  2654. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  2655. *
  2656. * @param options - Optional settings for the command
  2657. */
  2658. drop(options?: DropCollectionOptions): Promise<boolean>;
  2659. /**
  2660. * Fetches the first document that matches the filter
  2661. *
  2662. * @param filter - Query for find Operation
  2663. * @param options - Optional settings for the command
  2664. */
  2665. findOne(): Promise<WithId<TSchema> | null>;
  2666. findOne(filter: Filter<TSchema>): Promise<WithId<TSchema> | null>;
  2667. findOne(filter: Filter<TSchema>, options: Omit<FindOneOptions, 'timeoutMode'> & Abortable): Promise<WithId<TSchema> | null>;
  2668. findOne<T = TSchema>(): Promise<T | null>;
  2669. findOne<T = TSchema>(filter: Filter<TSchema>): Promise<T | null>;
  2670. findOne<T = TSchema>(filter: Filter<TSchema>, options?: Omit<FindOneOptions, 'timeoutMode'> & Abortable): Promise<T | null>;
  2671. /**
  2672. * Creates a cursor for a filter that can be used to iterate over results from MongoDB
  2673. *
  2674. * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate
  2675. */
  2676. find(): FindCursor<WithId<TSchema>>;
  2677. find(filter: Filter<TSchema>, options?: FindOptions & Abortable): FindCursor<WithId<TSchema>>;
  2678. find<T extends Document>(filter: Filter<TSchema>, options?: FindOptions & Abortable): FindCursor<T>;
  2679. /**
  2680. * Returns the options of the collection.
  2681. *
  2682. * @param options - Optional settings for the command
  2683. */
  2684. options(options?: OperationOptions): Promise<Document>;
  2685. /**
  2686. * Returns if the collection is a capped collection
  2687. *
  2688. * @param options - Optional settings for the command
  2689. */
  2690. isCapped(options?: OperationOptions): Promise<boolean>;
  2691. /**
  2692. * Creates an index on the db and collection collection.
  2693. *
  2694. * @param indexSpec - The field name or index specification to create an index for
  2695. * @param options - Optional settings for the command
  2696. *
  2697. * @example
  2698. * ```ts
  2699. * const collection = client.db('foo').collection('bar');
  2700. *
  2701. * await collection.createIndex({ a: 1, b: -1 });
  2702. *
  2703. * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
  2704. * await collection.createIndex([ [c, 1], [d, -1] ]);
  2705. *
  2706. * // Equivalent to { e: 1 }
  2707. * await collection.createIndex('e');
  2708. *
  2709. * // Equivalent to { f: 1, g: 1 }
  2710. * await collection.createIndex(['f', 'g'])
  2711. *
  2712. * // Equivalent to { h: 1, i: -1 }
  2713. * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
  2714. *
  2715. * // Equivalent to { j: 1, k: -1, l: 2d }
  2716. * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
  2717. * ```
  2718. */
  2719. createIndex(indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
  2720. /**
  2721. * Creates multiple indexes in the collection, this method is only supported for
  2722. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  2723. * error.
  2724. *
  2725. * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications.
  2726. * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}.
  2727. *
  2728. * @param indexSpecs - An array of index specifications to be created
  2729. * @param options - Optional settings for the command
  2730. *
  2731. * @example
  2732. * ```ts
  2733. * const collection = client.db('foo').collection('bar');
  2734. * await collection.createIndexes([
  2735. * // Simple index on field fizz
  2736. * {
  2737. * key: { fizz: 1 },
  2738. * }
  2739. * // wildcard index
  2740. * {
  2741. * key: { '$**': 1 }
  2742. * },
  2743. * // named index on darmok and jalad
  2744. * {
  2745. * key: { darmok: 1, jalad: -1 }
  2746. * name: 'tanagra'
  2747. * }
  2748. * ]);
  2749. * ```
  2750. */
  2751. createIndexes(indexSpecs: IndexDescription[], options?: CreateIndexesOptions): Promise<string[]>;
  2752. /**
  2753. * Drops an index from this collection.
  2754. *
  2755. * @param indexName - Name of the index to drop.
  2756. * @param options - Optional settings for the command
  2757. */
  2758. dropIndex(indexName: string, options?: DropIndexesOptions): Promise<Document>;
  2759. /**
  2760. * Drops all indexes from this collection.
  2761. *
  2762. * @param options - Optional settings for the command
  2763. */
  2764. dropIndexes(options?: DropIndexesOptions): Promise<boolean>;
  2765. /**
  2766. * Get the list of all indexes information for the collection.
  2767. *
  2768. * @param options - Optional settings for the command
  2769. */
  2770. listIndexes(options?: ListIndexesOptions): ListIndexesCursor;
  2771. /**
  2772. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  2773. *
  2774. * @param indexes - One or more index names to check.
  2775. * @param options - Optional settings for the command
  2776. */
  2777. indexExists(indexes: string | string[], options?: ListIndexesOptions): Promise<boolean>;
  2778. /**
  2779. * Retrieves this collections index info.
  2780. *
  2781. * @param options - Optional settings for the command
  2782. */
  2783. indexInformation(options: IndexInformationOptions & {
  2784. full: true;
  2785. }): Promise<IndexDescriptionInfo[]>;
  2786. indexInformation(options: IndexInformationOptions & {
  2787. full?: false;
  2788. }): Promise<IndexDescriptionCompact>;
  2789. indexInformation(options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
  2790. indexInformation(): Promise<IndexDescriptionCompact>;
  2791. /**
  2792. * Gets an estimate of the count of documents in a collection using collection metadata.
  2793. * This will always run a count command on all server versions.
  2794. *
  2795. * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command,
  2796. * which estimatedDocumentCount uses in its implementation, was not included in v1 of
  2797. * the Stable API, and so users of the Stable API with estimatedDocumentCount are
  2798. * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid
  2799. * encountering errors.
  2800. *
  2801. * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior}
  2802. * @param options - Optional settings for the command
  2803. */
  2804. estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise<number>;
  2805. /**
  2806. * Gets the number of documents matching the filter.
  2807. * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  2808. *
  2809. * Due to countDocuments using the $match aggregation pipeline stage, certain query operators cannot be used in countDocuments. This includes the $where and $near query operators, among others. Details can be found in the documentation for the $match aggregation pipeline stage.
  2810. *
  2811. * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments}
  2812. * the following query operators must be replaced:
  2813. *
  2814. * | Operator | Replacement |
  2815. * | -------- | ----------- |
  2816. * | `$where` | [`$expr`][1] |
  2817. * | `$near` | [`$geoWithin`][2] with [`$center`][3] |
  2818. * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
  2819. *
  2820. * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  2821. * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  2822. * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  2823. * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  2824. *
  2825. * @param filter - The filter for the count
  2826. * @param options - Optional settings for the command
  2827. *
  2828. * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/
  2829. * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
  2830. * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
  2831. * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
  2832. */
  2833. countDocuments(filter?: Filter<TSchema>, options?: CountDocumentsOptions & Abortable): Promise<number>;
  2834. /**
  2835. * The distinct command returns a list of distinct values for the given key across a collection.
  2836. *
  2837. * @param key - Field of the document to find distinct values for
  2838. * @param filter - The filter for filtering the set of documents to which we apply the distinct filter.
  2839. * @param options - Optional settings for the command
  2840. */
  2841. distinct<Key extends keyof WithId<TSchema>>(key: Key): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
  2842. distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
  2843. distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>, options: DistinctOptions): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
  2844. distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>, options: DistinctOptions & {
  2845. explain: ExplainVerbosityLike | ExplainCommandOptions;
  2846. }): Promise<Document>;
  2847. distinct(key: string): Promise<any[]>;
  2848. distinct(key: string, filter: Filter<TSchema>): Promise<any[]>;
  2849. distinct(key: string, filter: Filter<TSchema>, options: DistinctOptions): Promise<any[]>;
  2850. /**
  2851. * Retrieve all the indexes on the collection.
  2852. *
  2853. * @param options - Optional settings for the command
  2854. */
  2855. indexes(options: IndexInformationOptions & {
  2856. full?: true;
  2857. }): Promise<IndexDescriptionInfo[]>;
  2858. indexes(options: IndexInformationOptions & {
  2859. full: false;
  2860. }): Promise<IndexDescriptionCompact>;
  2861. indexes(options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
  2862. indexes(options?: ListIndexesOptions): Promise<IndexDescriptionInfo[]>;
  2863. /**
  2864. * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
  2865. *
  2866. * @param filter - The filter used to select the document to remove
  2867. * @param options - Optional settings for the command
  2868. */
  2869. findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions & {
  2870. includeResultMetadata: true;
  2871. }): Promise<ModifyResult<TSchema>>;
  2872. findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions & {
  2873. includeResultMetadata: false;
  2874. }): Promise<WithId<TSchema> | null>;
  2875. findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions): Promise<WithId<TSchema> | null>;
  2876. findOneAndDelete(filter: Filter<TSchema>): Promise<WithId<TSchema> | null>;
  2877. /**
  2878. * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
  2879. *
  2880. * @param filter - The filter used to select the document to replace
  2881. * @param replacement - The Document that replaces the matching document
  2882. * @param options - Optional settings for the command
  2883. */
  2884. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions & {
  2885. includeResultMetadata: true;
  2886. }): Promise<ModifyResult<TSchema>>;
  2887. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions & {
  2888. includeResultMetadata: false;
  2889. }): Promise<WithId<TSchema> | null>;
  2890. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions): Promise<WithId<TSchema> | null>;
  2891. findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>): Promise<WithId<TSchema> | null>;
  2892. /**
  2893. * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
  2894. *
  2895. * The value of `update` can be either:
  2896. * - UpdateFilter<TSchema> - A document that contains update operator expressions,
  2897. * - Document[] - an aggregation pipeline consisting of the following stages:
  2898. * - $addFields and its alias $set
  2899. * - $project and its alias $unset
  2900. * - $replaceRoot and its alias $replaceWith.
  2901. * See the [findAndModify command documentation](https://www.mongodb.com/docs/manual/reference/command/findAndModify) for details.
  2902. *
  2903. * @param filter - The filter used to select the document to update
  2904. * @param update - The modifications to apply
  2905. * @param options - Optional settings for the command
  2906. */
  2907. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options: FindOneAndUpdateOptions & {
  2908. includeResultMetadata: true;
  2909. }): Promise<ModifyResult<TSchema>>;
  2910. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options: FindOneAndUpdateOptions & {
  2911. includeResultMetadata: false;
  2912. }): Promise<WithId<TSchema> | null>;
  2913. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options: FindOneAndUpdateOptions): Promise<WithId<TSchema> | null>;
  2914. findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[]): Promise<WithId<TSchema> | null>;
  2915. /**
  2916. * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2
  2917. *
  2918. * @param pipeline - An array of aggregation pipelines to execute
  2919. * @param options - Optional settings for the command
  2920. */
  2921. aggregate<T extends Document = Document>(pipeline?: Document[], options?: AggregateOptions & Abortable): AggregationCursor<T>;
  2922. /**
  2923. * Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
  2924. *
  2925. * @remarks
  2926. * watch() accepts two generic arguments for distinct use cases:
  2927. * - The first is to override the schema that may be defined for this specific collection
  2928. * - 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
  2929. * @example
  2930. * By just providing the first argument I can type the change to be `ChangeStreamDocument<{ _id: number }>`
  2931. * ```ts
  2932. * collection.watch<{ _id: number }>()
  2933. * .on('change', change => console.log(change._id.toFixed(4)));
  2934. * ```
  2935. *
  2936. * @example
  2937. * Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline.
  2938. * Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment.
  2939. * No need start from scratch on the ChangeStreamInsertDocument type!
  2940. * By using an intersection we can save time and ensure defaults remain the same type!
  2941. * ```ts
  2942. * collection
  2943. * .watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([
  2944. * { $addFields: { comment: 'big changes' } },
  2945. * { $match: { operationType: 'insert' } }
  2946. * ])
  2947. * .on('change', change => {
  2948. * change.comment.startsWith('big');
  2949. * change.operationType === 'insert';
  2950. * // No need to narrow in code because the generics did that for us!
  2951. * expectType<Schema>(change.fullDocument);
  2952. * });
  2953. * ```
  2954. *
  2955. * @remarks
  2956. * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
  2957. * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
  2958. * stream will time out if it does not receive a change event within `timeoutMS` of the last change
  2959. * event.
  2960. *
  2961. * Note that if a change stream is consistently timing out when watching a collection, database or
  2962. * client that is being changed, then this may be due to the server timing out before it can finish
  2963. * processing the existing oplog. To address this, restart the change stream with a higher
  2964. * `timeoutMS`.
  2965. *
  2966. * If the change stream times out the initial aggregate operation to establish the change stream on
  2967. * the server, then the client will close the change stream. If the getMore calls to the server
  2968. * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
  2969. * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
  2970. * emitter mode.
  2971. *
  2972. * To determine whether or not the change stream is still open following a timeout, check the
  2973. * {@link ChangeStream.closed} getter.
  2974. *
  2975. * @example
  2976. * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
  2977. * The next call can just be retried after this succeeds.
  2978. * ```ts
  2979. * const changeStream = collection.watch([], { timeoutMS: 100 });
  2980. * try {
  2981. * await changeStream.next();
  2982. * } catch (e) {
  2983. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  2984. * await changeStream.next();
  2985. * }
  2986. * throw e;
  2987. * }
  2988. * ```
  2989. *
  2990. * @example
  2991. * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
  2992. * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
  2993. * stream unless the resume attempt fails. There is no need to re-establish change listeners as
  2994. * this will automatically continue emitting change events once the resume attempt completes.
  2995. *
  2996. * ```ts
  2997. * const changeStream = collection.watch([], { timeoutMS: 100 });
  2998. * changeStream.on('change', console.log);
  2999. * changeStream.on('error', e => {
  3000. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  3001. * // do nothing
  3002. * } else {
  3003. * changeStream.close();
  3004. * }
  3005. * });
  3006. * ```
  3007. *
  3008. * @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.
  3009. * @param options - Optional settings for the command
  3010. * @typeParam TLocal - Type of the data being detected by the change stream
  3011. * @typeParam TChange - Type of the whole change stream document emitted
  3012. */
  3013. watch<TLocal extends Document = TSchema, TChange extends Document = ChangeStreamDocument<TLocal>>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream<TLocal, TChange>;
  3014. /**
  3015. * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  3016. *
  3017. * @throws MongoNotConnectedError
  3018. * @remarks
  3019. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  3020. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  3021. */
  3022. initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation;
  3023. /**
  3024. * 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.
  3025. *
  3026. * @throws MongoNotConnectedError
  3027. * @remarks
  3028. * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
  3029. * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
  3030. */
  3031. initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation;
  3032. /**
  3033. * An estimated count of matching documents in the db to a filter.
  3034. *
  3035. * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
  3036. * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}.
  3037. * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
  3038. *
  3039. * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead
  3040. *
  3041. * @param filter - The filter for the count.
  3042. * @param options - Optional settings for the command
  3043. */
  3044. count(filter?: Filter<TSchema>, options?: CountOptions): Promise<number>;
  3045. /**
  3046. * Returns all search indexes for the current collection.
  3047. *
  3048. * @param options - The options for the list indexes operation.
  3049. *
  3050. * @remarks Only available when used against a 7.0+ Atlas cluster.
  3051. */
  3052. listSearchIndexes(options?: ListSearchIndexesOptions): ListSearchIndexesCursor;
  3053. /**
  3054. * Returns all search indexes for the current collection.
  3055. *
  3056. * @param name - The name of the index to search for. Only indexes with matching index names will be returned.
  3057. * @param options - The options for the list indexes operation.
  3058. *
  3059. * @remarks Only available when used against a 7.0+ Atlas cluster.
  3060. */
  3061. listSearchIndexes(name: string, options?: ListSearchIndexesOptions): ListSearchIndexesCursor;
  3062. /**
  3063. * Creates a single search index for the collection.
  3064. *
  3065. * @param description - The index description for the new search index.
  3066. * @returns A promise that resolves to the name of the new search index.
  3067. *
  3068. * @remarks Only available when used against a 7.0+ Atlas cluster.
  3069. */
  3070. createSearchIndex(description: SearchIndexDescription): Promise<string>;
  3071. /**
  3072. * Creates multiple search indexes for the current collection.
  3073. *
  3074. * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes.
  3075. * @returns A promise that resolves to an array of the newly created search index names.
  3076. *
  3077. * @remarks Only available when used against a 7.0+ Atlas cluster.
  3078. * @returns
  3079. */
  3080. createSearchIndexes(descriptions: SearchIndexDescription[]): Promise<string[]>;
  3081. /**
  3082. * Deletes a search index by index name.
  3083. *
  3084. * @param name - The name of the search index to be deleted.
  3085. *
  3086. * @remarks Only available when used against a 7.0+ Atlas cluster.
  3087. */
  3088. dropSearchIndex(name: string): Promise<void>;
  3089. /**
  3090. * Updates a search index by replacing the existing index definition with the provided definition.
  3091. *
  3092. * @param name - The name of the search index to update.
  3093. * @param definition - The new search index definition.
  3094. *
  3095. * @remarks Only available when used against a 7.0+ Atlas cluster.
  3096. */
  3097. updateSearchIndex(name: string, definition: Document): Promise<void>;
  3098. }
  3099. /** @public */
  3100. export declare interface CollectionInfo extends Document {
  3101. name: string;
  3102. type?: string;
  3103. options?: Document;
  3104. info?: {
  3105. readOnly?: false;
  3106. uuid?: Binary;
  3107. };
  3108. idIndex?: Document;
  3109. }
  3110. /** @public */
  3111. export declare interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions {
  3112. /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */
  3113. readConcern?: ReadConcernLike;
  3114. /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */
  3115. readPreference?: ReadPreferenceLike;
  3116. /**
  3117. * @experimental
  3118. * Specifies the time an operation will run until it throws a timeout error
  3119. */
  3120. timeoutMS?: number;
  3121. }
  3122. /* Excluded from this release type: CollectionPrivate */
  3123. /* Excluded from this release type: COMMAND_FAILED */
  3124. /* Excluded from this release type: COMMAND_STARTED */
  3125. /* Excluded from this release type: COMMAND_SUCCEEDED */
  3126. /**
  3127. * An event indicating the failure of a given command
  3128. * @public
  3129. * @category Event
  3130. */
  3131. export declare class CommandFailedEvent {
  3132. address: string;
  3133. /** Driver generated connection id */
  3134. connectionId?: string | number;
  3135. /**
  3136. * Server generated connection id
  3137. * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
  3138. */
  3139. serverConnectionId: bigint | null;
  3140. requestId: number;
  3141. duration: number;
  3142. commandName: string;
  3143. failure: Error;
  3144. serviceId?: ObjectId;
  3145. databaseName: string;
  3146. /* Excluded from this release type: name */
  3147. /* Excluded from this release type: __constructor */
  3148. get hasServiceId(): boolean;
  3149. }
  3150. /* Excluded from this release type: CommandOperation */
  3151. /** @public */
  3152. export declare interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions {
  3153. /** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */
  3154. readConcern?: ReadConcernLike;
  3155. /** Collation */
  3156. collation?: CollationOptions;
  3157. /**
  3158. * maxTimeMS is a server-side time limit in milliseconds for processing an operation.
  3159. */
  3160. maxTimeMS?: number;
  3161. /**
  3162. * Comment to apply to the operation.
  3163. *
  3164. * In server versions pre-4.4, 'comment' must be string. A server
  3165. * error will be thrown if any other type is provided.
  3166. *
  3167. * In server versions 4.4 and above, 'comment' can be any valid BSON type.
  3168. */
  3169. comment?: unknown;
  3170. dbName?: string;
  3171. authdb?: string;
  3172. /* Excluded from this release type: rawData */
  3173. }
  3174. /* Excluded from this release type: CommandOptions */
  3175. /**
  3176. * An event indicating the start of a given command
  3177. * @public
  3178. * @category Event
  3179. */
  3180. export declare class CommandStartedEvent {
  3181. commandObj?: Document;
  3182. requestId: number;
  3183. databaseName: string;
  3184. commandName: string;
  3185. command: Document;
  3186. address: string;
  3187. /** Driver generated connection id */
  3188. connectionId?: string | number;
  3189. /**
  3190. * Server generated connection id
  3191. * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId"
  3192. * from the server on 4.2+.
  3193. */
  3194. serverConnectionId: bigint | null;
  3195. serviceId?: ObjectId;
  3196. /* Excluded from this release type: name */
  3197. /* Excluded from this release type: __constructor */
  3198. get hasServiceId(): boolean;
  3199. }
  3200. /**
  3201. * An event indicating the success of a given command
  3202. * @public
  3203. * @category Event
  3204. */
  3205. export declare class CommandSucceededEvent {
  3206. address: string;
  3207. /** Driver generated connection id */
  3208. connectionId?: string | number;
  3209. /**
  3210. * Server generated connection id
  3211. * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
  3212. */
  3213. serverConnectionId: bigint | null;
  3214. requestId: number;
  3215. duration: number;
  3216. commandName: string;
  3217. reply: unknown;
  3218. serviceId?: ObjectId;
  3219. databaseName: string;
  3220. /* Excluded from this release type: name */
  3221. /* Excluded from this release type: __constructor */
  3222. get hasServiceId(): boolean;
  3223. }
  3224. /** @public */
  3225. export declare type CommonEvents = 'newListener' | 'removeListener';
  3226. /** @public */
  3227. export declare const Compressor: Readonly<{
  3228. readonly none: 0;
  3229. readonly snappy: 1;
  3230. readonly zlib: 2;
  3231. readonly zstd: 3;
  3232. }>;
  3233. /** @public */
  3234. export declare type Compressor = (typeof Compressor)[CompressorName];
  3235. /** @public */
  3236. export declare type CompressorName = keyof typeof Compressor;
  3237. /** @public */
  3238. export declare type Condition<T> = AlternativeType<T> | FilterOperators<AlternativeType<T>>;
  3239. /* Excluded from this release type: Connection */
  3240. /* Excluded from this release type: CONNECTION_CHECK_OUT_FAILED */
  3241. /* Excluded from this release type: CONNECTION_CHECK_OUT_STARTED */
  3242. /* Excluded from this release type: CONNECTION_CHECKED_IN */
  3243. /* Excluded from this release type: CONNECTION_CHECKED_OUT */
  3244. /* Excluded from this release type: CONNECTION_CLOSED */
  3245. /* Excluded from this release type: CONNECTION_CREATED */
  3246. /* Excluded from this release type: CONNECTION_POOL_CLEARED */
  3247. /* Excluded from this release type: CONNECTION_POOL_CLOSED */
  3248. /* Excluded from this release type: CONNECTION_POOL_CREATED */
  3249. /* Excluded from this release type: CONNECTION_POOL_READY */
  3250. /* Excluded from this release type: CONNECTION_READY */
  3251. /**
  3252. * An event published when a connection is checked into the connection pool
  3253. * @public
  3254. * @category Event
  3255. */
  3256. export declare class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {
  3257. /** The id of the connection */
  3258. connectionId: number | '<monitor>';
  3259. /* Excluded from this release type: name */
  3260. /* Excluded from this release type: __constructor */
  3261. }
  3262. /**
  3263. * An event published when a connection is checked out of the connection pool
  3264. * @public
  3265. * @category Event
  3266. */
  3267. export declare class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {
  3268. /** The id of the connection */
  3269. connectionId: number | '<monitor>';
  3270. /* Excluded from this release type: name */
  3271. /**
  3272. * The time it took to check out the connection.
  3273. * More specifically, the time elapsed between
  3274. * emitting a `ConnectionCheckOutStartedEvent`
  3275. * and emitting this event as part of the same checking out.
  3276. *
  3277. */
  3278. durationMS: number;
  3279. /* Excluded from this release type: __constructor */
  3280. }
  3281. /**
  3282. * An event published when a request to check a connection out fails
  3283. * @public
  3284. * @category Event
  3285. */
  3286. export declare class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {
  3287. /** The reason the attempt to check out failed */
  3288. reason: string;
  3289. /* Excluded from this release type: error */
  3290. /* Excluded from this release type: name */
  3291. /**
  3292. * The time it took to check out the connection.
  3293. * More specifically, the time elapsed between
  3294. * emitting a `ConnectionCheckOutStartedEvent`
  3295. * and emitting this event as part of the same check out.
  3296. */
  3297. durationMS: number;
  3298. /* Excluded from this release type: __constructor */
  3299. }
  3300. /**
  3301. * An event published when a request to check a connection out begins
  3302. * @public
  3303. * @category Event
  3304. */
  3305. export declare class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {
  3306. /* Excluded from this release type: name */
  3307. /* Excluded from this release type: __constructor */
  3308. }
  3309. /**
  3310. * An event published when a connection is closed
  3311. * @public
  3312. * @category Event
  3313. */
  3314. export declare class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {
  3315. /** The id of the connection */
  3316. connectionId: number | '<monitor>';
  3317. /** The reason the connection was closed */
  3318. reason: string;
  3319. serviceId?: ObjectId;
  3320. /* Excluded from this release type: name */
  3321. /* Excluded from this release type: error */
  3322. /* Excluded from this release type: __constructor */
  3323. }
  3324. /**
  3325. * An event published when a connection pool creates a new connection
  3326. * @public
  3327. * @category Event
  3328. */
  3329. export declare class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {
  3330. /** A monotonically increasing, per-pool id for the newly created connection */
  3331. connectionId: number | '<monitor>';
  3332. /* Excluded from this release type: name */
  3333. /* Excluded from this release type: __constructor */
  3334. }
  3335. /** @public */
  3336. export declare type ConnectionEvents = {
  3337. commandStarted(event: CommandStartedEvent): void;
  3338. commandSucceeded(event: CommandSucceededEvent): void;
  3339. commandFailed(event: CommandFailedEvent): void;
  3340. clusterTimeReceived(clusterTime: Document): void;
  3341. close(): void;
  3342. pinned(pinType: string): void;
  3343. unpinned(pinType: string): void;
  3344. };
  3345. /** @public */
  3346. export declare interface ConnectionOptions extends SupportedNodeConnectionOptions, StreamDescriptionOptions, ProxyOptions {
  3347. id: number | '<monitor>';
  3348. generation: number;
  3349. hostAddress: HostAddress;
  3350. /* Excluded from this release type: autoEncrypter */
  3351. serverApi?: ServerApi;
  3352. monitorCommands: boolean;
  3353. /* Excluded from this release type: connectionType */
  3354. credentials?: MongoCredentials;
  3355. /* Excluded from this release type: authProviders */
  3356. connectTimeoutMS?: number;
  3357. tls: boolean;
  3358. noDelay?: boolean;
  3359. socketTimeoutMS?: number;
  3360. /* Excluded from this release type: cancellationToken */
  3361. /* Excluded from this release type: metadata */
  3362. /* Excluded from this release type: mongoLogger */
  3363. }
  3364. /* Excluded from this release type: ConnectionPool */
  3365. /**
  3366. * An event published when a connection pool is cleared
  3367. * @public
  3368. * @category Event
  3369. */
  3370. export declare class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {
  3371. /* Excluded from this release type: serviceId */
  3372. interruptInUseConnections?: boolean;
  3373. /* Excluded from this release type: name */
  3374. /* Excluded from this release type: __constructor */
  3375. }
  3376. /**
  3377. * An event published when a connection pool is closed
  3378. * @public
  3379. * @category Event
  3380. */
  3381. export declare class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {
  3382. /* Excluded from this release type: name */
  3383. /* Excluded from this release type: __constructor */
  3384. }
  3385. /**
  3386. * An event published when a connection pool is created
  3387. * @public
  3388. * @category Event
  3389. */
  3390. export declare class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {
  3391. /** The options used to create this connection pool */
  3392. options: Pick<ConnectionPoolOptions, 'maxPoolSize' | 'minPoolSize' | 'maxConnecting' | 'maxIdleTimeMS' | 'waitQueueTimeoutMS'>;
  3393. /* Excluded from this release type: name */
  3394. /* Excluded from this release type: __constructor */
  3395. }
  3396. /** @public */
  3397. export declare type ConnectionPoolEvents = {
  3398. connectionPoolCreated(event: ConnectionPoolCreatedEvent): void;
  3399. connectionPoolReady(event: ConnectionPoolReadyEvent): void;
  3400. connectionPoolClosed(event: ConnectionPoolClosedEvent): void;
  3401. connectionPoolCleared(event: ConnectionPoolClearedEvent): void;
  3402. connectionCreated(event: ConnectionCreatedEvent): void;
  3403. connectionReady(event: ConnectionReadyEvent): void;
  3404. connectionClosed(event: ConnectionClosedEvent): void;
  3405. connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void;
  3406. connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void;
  3407. connectionCheckedOut(event: ConnectionCheckedOutEvent): void;
  3408. connectionCheckedIn(event: ConnectionCheckedInEvent): void;
  3409. } & Omit<ConnectionEvents, 'close' | 'message'>;
  3410. /* Excluded from this release type: ConnectionPoolMetrics */
  3411. /**
  3412. * The base export class for all monitoring events published from the connection pool
  3413. * @public
  3414. * @category Event
  3415. */
  3416. export declare abstract class ConnectionPoolMonitoringEvent {
  3417. /** A timestamp when the event was created */
  3418. time: Date;
  3419. /** The address (host/port pair) of the pool */
  3420. address: string;
  3421. /* Excluded from this release type: name */
  3422. /* Excluded from this release type: __constructor */
  3423. }
  3424. /** @public */
  3425. export declare interface ConnectionPoolOptions extends Omit<ConnectionOptions, 'id' | 'generation'> {
  3426. /** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */
  3427. maxPoolSize: number;
  3428. /** The minimum number of connections that MUST exist at any moment in a single connection pool. */
  3429. minPoolSize: number;
  3430. /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
  3431. maxConnecting: number;
  3432. /** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */
  3433. maxIdleTimeMS: number;
  3434. /** 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. */
  3435. waitQueueTimeoutMS: number;
  3436. /** If we are in load balancer mode. */
  3437. loadBalanced: boolean;
  3438. /* Excluded from this release type: minPoolSizeCheckFrequencyMS */
  3439. }
  3440. /**
  3441. * An event published when a connection pool is ready
  3442. * @public
  3443. * @category Event
  3444. */
  3445. export declare class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent {
  3446. /* Excluded from this release type: name */
  3447. /* Excluded from this release type: __constructor */
  3448. }
  3449. /**
  3450. * An event published when a connection is ready for use
  3451. * @public
  3452. * @category Event
  3453. */
  3454. export declare class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {
  3455. /** The id of the connection */
  3456. connectionId: number | '<monitor>';
  3457. /**
  3458. * The time it took to establish the connection.
  3459. * In accordance with the definition of establishment of a connection
  3460. * specified by `ConnectionPoolOptions.maxConnecting`,
  3461. * it is the time elapsed between emitting a `ConnectionCreatedEvent`
  3462. * and emitting this event as part of the same checking out.
  3463. *
  3464. * Naturally, when establishing a connection is part of checking out,
  3465. * this duration is not greater than
  3466. * `ConnectionCheckedOutEvent.duration`.
  3467. */
  3468. durationMS: number;
  3469. /* Excluded from this release type: name */
  3470. /* Excluded from this release type: __constructor */
  3471. }
  3472. /** @public */
  3473. export declare interface ConnectOptions {
  3474. readPreference?: ReadPreference;
  3475. }
  3476. /** @public */
  3477. export declare interface CountDocumentsOptions extends AggregateOptions {
  3478. /** The number of documents to skip. */
  3479. skip?: number;
  3480. /** The maximum amount of documents to consider. */
  3481. limit?: number;
  3482. }
  3483. /** @public */
  3484. export declare interface CountOptions extends CommandOperationOptions {
  3485. /** The number of documents to skip. */
  3486. skip?: number;
  3487. /** The maximum amounts to count before aborting. */
  3488. limit?: number;
  3489. /**
  3490. * Number of milliseconds to wait before aborting the query.
  3491. */
  3492. maxTimeMS?: number;
  3493. /** An index name hint for the query. */
  3494. hint?: string | Document;
  3495. }
  3496. /** @public */
  3497. export declare interface CreateCollectionOptions extends Omit<CommandOperationOptions, 'rawData'> {
  3498. /** Create a capped collection */
  3499. capped?: boolean;
  3500. /** The size of the capped collection in bytes */
  3501. size?: number;
  3502. /** The maximum number of documents in the capped collection */
  3503. max?: number;
  3504. /** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */
  3505. flags?: number;
  3506. /** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection */
  3507. storageEngine?: Document;
  3508. /** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */
  3509. validator?: Document;
  3510. /** Determines how strictly MongoDB applies the validation rules to existing documents during an update */
  3511. validationLevel?: string;
  3512. /** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */
  3513. validationAction?: string;
  3514. /** Allows users to specify a default configuration for indexes when creating a collection */
  3515. indexOptionDefaults?: Document;
  3516. /** 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) */
  3517. viewOn?: string;
  3518. /** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view */
  3519. pipeline?: Document[];
  3520. /** A primary key factory function for generation of custom _id keys. */
  3521. pkFactory?: PkFactory;
  3522. /** A document specifying configuration options for timeseries collections. */
  3523. timeseries?: TimeSeriesCollectionOptions;
  3524. /** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */
  3525. clusteredIndex?: ClusteredCollectionOptions;
  3526. /** The number of seconds after which a document in a timeseries or clustered collection expires. */
  3527. expireAfterSeconds?: number;
  3528. /** @experimental */
  3529. encryptedFields?: Document;
  3530. /**
  3531. * If set, enables pre-update and post-update document events to be included for any
  3532. * change streams that listen on this collection.
  3533. */
  3534. changeStreamPreAndPostImages?: {
  3535. enabled: boolean;
  3536. };
  3537. }
  3538. /** @public */
  3539. export declare interface CreateIndexesOptions extends Omit<CommandOperationOptions, 'writeConcern'> {
  3540. /** Creates the index in the background, yielding whenever possible. */
  3541. background?: boolean;
  3542. /** Creates an unique index. */
  3543. unique?: boolean;
  3544. /** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */
  3545. name?: string;
  3546. /** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */
  3547. partialFilterExpression?: Document;
  3548. /** Creates a sparse index. */
  3549. sparse?: boolean;
  3550. /** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */
  3551. expireAfterSeconds?: number;
  3552. /** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */
  3553. storageEngine?: Document;
  3554. /** (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. */
  3555. commitQuorum?: number | string;
  3556. /** Specifies the index version number, either 0 or 1. */
  3557. version?: number;
  3558. weights?: Document;
  3559. default_language?: string;
  3560. language_override?: string;
  3561. textIndexVersion?: number;
  3562. '2dsphereIndexVersion'?: number;
  3563. bits?: number;
  3564. /** For geospatial indexes set the lower bound for the co-ordinates. */
  3565. min?: number;
  3566. /** For geospatial indexes set the high bound for the co-ordinates. */
  3567. max?: number;
  3568. bucketSize?: number;
  3569. wildcardProjection?: Document;
  3570. /** 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) */
  3571. hidden?: boolean;
  3572. }
  3573. /**
  3574. * @public
  3575. * Configuration options for custom credential providers for KMS requests.
  3576. */
  3577. export declare interface CredentialProviders {
  3578. aws?: AWSCredentialProvider;
  3579. }
  3580. /** @public */
  3581. export declare type CSFLEKMSTlsOptions = {
  3582. aws?: ClientEncryptionTlsOptions;
  3583. gcp?: ClientEncryptionTlsOptions;
  3584. kmip?: ClientEncryptionTlsOptions;
  3585. local?: ClientEncryptionTlsOptions;
  3586. azure?: ClientEncryptionTlsOptions;
  3587. [key: string]: ClientEncryptionTlsOptions | undefined;
  3588. };
  3589. /* Excluded from this release type: CSOTTimeoutContext */
  3590. /* Excluded from this release type: CSOTTimeoutContextOptions */
  3591. /** @public */
  3592. export declare const CURSOR_FLAGS: readonly ["tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial"];
  3593. /** @public */
  3594. export declare type CursorFlag = (typeof CURSOR_FLAGS)[number];
  3595. /* Excluded from this release type: CursorResponse */
  3596. /* Excluded from this release type: CursorTimeoutContext */
  3597. /**
  3598. * @public
  3599. * @experimental
  3600. * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
  3601. * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
  3602. * `cursor.next()`.
  3603. * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
  3604. *
  3605. * Depending on the type of cursor being used, this option has different default values.
  3606. * For non-tailable cursors, this value defaults to `'cursorLifetime'`
  3607. * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
  3608. * definition can have an arbitrarily long lifetime.
  3609. *
  3610. * @example
  3611. * ```ts
  3612. * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
  3613. * for await (const doc of cursor) {
  3614. * // process doc
  3615. * // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
  3616. * // will continue to iterate successfully otherwise, regardless of the number of batches.
  3617. * }
  3618. * ```
  3619. *
  3620. * @example
  3621. * ```ts
  3622. * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
  3623. * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
  3624. * ```
  3625. */
  3626. export declare const CursorTimeoutMode: Readonly<{
  3627. readonly ITERATION: "iteration";
  3628. readonly LIFETIME: "cursorLifetime";
  3629. }>;
  3630. /**
  3631. * @public
  3632. * @experimental
  3633. */
  3634. export declare type CursorTimeoutMode = (typeof CursorTimeoutMode)[keyof typeof CursorTimeoutMode];
  3635. /**
  3636. * @public
  3637. * The schema for a DataKey in the key vault collection.
  3638. */
  3639. export declare interface DataKey {
  3640. _id: UUID;
  3641. version?: number;
  3642. keyAltNames?: string[];
  3643. keyMaterial: Binary;
  3644. creationDate: Date;
  3645. updateDate: Date;
  3646. status: number;
  3647. masterKey: Document;
  3648. }
  3649. /**
  3650. * The **Db** class is a class that represents a MongoDB Database.
  3651. * @public
  3652. *
  3653. * @example
  3654. * ```ts
  3655. * import { MongoClient } from 'mongodb';
  3656. *
  3657. * interface Pet {
  3658. * name: string;
  3659. * kind: 'dog' | 'cat' | 'fish';
  3660. * }
  3661. *
  3662. * const client = new MongoClient('mongodb://localhost:27017');
  3663. * const db = client.db();
  3664. *
  3665. * // Create a collection that validates our union
  3666. * await db.createCollection<Pet>('pets', {
  3667. * validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }
  3668. * })
  3669. * ```
  3670. */
  3671. export declare class Db {
  3672. /* Excluded from this release type: s */
  3673. /**
  3674. * Gets the MongoClient associated with the Db.
  3675. * @public
  3676. */
  3677. readonly client: MongoClient;
  3678. static SYSTEM_NAMESPACE_COLLECTION: string;
  3679. static SYSTEM_INDEX_COLLECTION: string;
  3680. static SYSTEM_PROFILE_COLLECTION: string;
  3681. static SYSTEM_USER_COLLECTION: string;
  3682. static SYSTEM_COMMAND_COLLECTION: string;
  3683. static SYSTEM_JS_COLLECTION: string;
  3684. /**
  3685. * Creates a new Db instance.
  3686. *
  3687. * Db name cannot contain a dot, the server may apply more restrictions when an operation is run.
  3688. *
  3689. * @param client - The MongoClient for the database.
  3690. * @param databaseName - The name of the database this instance represents.
  3691. * @param options - Optional settings for Db construction.
  3692. */
  3693. constructor(client: MongoClient, databaseName: string, options?: DbOptions);
  3694. get databaseName(): string;
  3695. get options(): DbOptions | undefined;
  3696. /**
  3697. * Check if a secondary can be used (because the read preference is *not* set to primary)
  3698. */
  3699. get secondaryOk(): boolean;
  3700. get readConcern(): ReadConcern | undefined;
  3701. /**
  3702. * The current readPreference of the Db. If not explicitly defined for
  3703. * this Db, will be inherited from the parent MongoClient
  3704. */
  3705. get readPreference(): ReadPreference;
  3706. get bsonOptions(): BSONSerializeOptions;
  3707. get writeConcern(): WriteConcern | undefined;
  3708. get namespace(): string;
  3709. get timeoutMS(): number | undefined;
  3710. /**
  3711. * Create a new collection on a server with the specified options. Use this to create capped collections.
  3712. * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
  3713. *
  3714. * Collection namespace validation is performed server-side.
  3715. *
  3716. * @param name - The name of the collection to create
  3717. * @param options - Optional settings for the command
  3718. */
  3719. createCollection<TSchema extends Document = Document>(name: string, options?: CreateCollectionOptions): Promise<Collection<TSchema>>;
  3720. /**
  3721. * Execute a command
  3722. *
  3723. * @remarks
  3724. * This command does not inherit options from the MongoClient.
  3725. *
  3726. * The driver will ensure the following fields are attached to the command sent to the server:
  3727. * - `lsid` - sourced from an implicit session or options.session
  3728. * - `$readPreference` - defaults to primary or can be configured by options.readPreference
  3729. * - `$db` - sourced from the name of this database
  3730. *
  3731. * If the client has a serverApi setting:
  3732. * - `apiVersion`
  3733. * - `apiStrict`
  3734. * - `apiDeprecationErrors`
  3735. *
  3736. * When in a transaction:
  3737. * - `readConcern` - sourced from readConcern set on the TransactionOptions
  3738. * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
  3739. *
  3740. * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
  3741. *
  3742. * @param command - The command to run
  3743. * @param options - Optional settings for the command
  3744. */
  3745. command(command: Document, options?: RunCommandOptions & Abortable): Promise<Document>;
  3746. /**
  3747. * Execute an aggregation framework pipeline against the database.
  3748. *
  3749. * @param pipeline - An array of aggregation stages to be executed
  3750. * @param options - Optional settings for the command
  3751. */
  3752. aggregate<T extends Document = Document>(pipeline?: Document[], options?: AggregateOptions): AggregationCursor<T>;
  3753. /** Return the Admin db instance */
  3754. admin(): Admin;
  3755. /**
  3756. * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
  3757. *
  3758. * Collection namespace validation is performed server-side.
  3759. *
  3760. * @param name - the collection name we wish to access.
  3761. * @returns return the new Collection instance
  3762. */
  3763. collection<TSchema extends Document = Document>(name: string, options?: CollectionOptions): Collection<TSchema>;
  3764. /**
  3765. * Get all the db statistics.
  3766. *
  3767. * @param options - Optional settings for the command
  3768. */
  3769. stats(options?: DbStatsOptions): Promise<Document>;
  3770. /**
  3771. * List all collections of this database with optional filter
  3772. *
  3773. * @param filter - Query to filter collections by
  3774. * @param options - Optional settings for the command
  3775. */
  3776. listCollections(filter: Document, options: Exclude<ListCollectionsOptions, 'nameOnly'> & {
  3777. nameOnly: true;
  3778. } & Abortable): ListCollectionsCursor<Pick<CollectionInfo, 'name' | 'type'>>;
  3779. listCollections(filter: Document, options: Exclude<ListCollectionsOptions, 'nameOnly'> & {
  3780. nameOnly: false;
  3781. } & Abortable): ListCollectionsCursor<CollectionInfo>;
  3782. listCollections<T extends Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo = Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions & Abortable): ListCollectionsCursor<T>;
  3783. /**
  3784. * Rename a collection.
  3785. *
  3786. * @remarks
  3787. * This operation does not inherit options from the MongoClient.
  3788. *
  3789. * @param fromCollection - Name of current collection to rename
  3790. * @param toCollection - New name of of the collection
  3791. * @param options - Optional settings for the command
  3792. */
  3793. renameCollection<TSchema extends Document = Document>(fromCollection: string, toCollection: string, options?: RenameOptions): Promise<Collection<TSchema>>;
  3794. /**
  3795. * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
  3796. *
  3797. * @param name - Name of collection to drop
  3798. * @param options - Optional settings for the command
  3799. */
  3800. dropCollection(name: string, options?: DropCollectionOptions): Promise<boolean>;
  3801. /**
  3802. * Drop a database, removing it permanently from the server.
  3803. *
  3804. * @param options - Optional settings for the command
  3805. */
  3806. dropDatabase(options?: DropDatabaseOptions): Promise<boolean>;
  3807. /**
  3808. * Fetch all collections for the current db.
  3809. *
  3810. * @param options - Optional settings for the command
  3811. */
  3812. collections(options?: ListCollectionsOptions): Promise<Collection[]>;
  3813. /**
  3814. * Creates an index on the db and collection.
  3815. *
  3816. * @param name - Name of the collection to create the index on.
  3817. * @param indexSpec - Specify the field to index, or an index specification
  3818. * @param options - Optional settings for the command
  3819. */
  3820. createIndex(name: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
  3821. /**
  3822. * Remove a user from a database
  3823. *
  3824. * @param username - The username to remove
  3825. * @param options - Optional settings for the command
  3826. */
  3827. removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
  3828. /**
  3829. * Set the current profiling level of MongoDB
  3830. *
  3831. * @param level - The new profiling level (off, slow_only, all).
  3832. * @param options - Optional settings for the command
  3833. */
  3834. setProfilingLevel(level: ProfilingLevel, options?: SetProfilingLevelOptions): Promise<ProfilingLevel>;
  3835. /**
  3836. * Retrieve the current profiling Level for MongoDB
  3837. *
  3838. * @param options - Optional settings for the command
  3839. */
  3840. profilingLevel(options?: ProfilingLevelOptions): Promise<string>;
  3841. /**
  3842. * Retrieves this collections index info.
  3843. *
  3844. * @param name - The name of the collection.
  3845. * @param options - Optional settings for the command
  3846. */
  3847. indexInformation(name: string, options: IndexInformationOptions & {
  3848. full: true;
  3849. }): Promise<IndexDescriptionInfo[]>;
  3850. indexInformation(name: string, options: IndexInformationOptions & {
  3851. full?: false;
  3852. }): Promise<IndexDescriptionCompact>;
  3853. indexInformation(name: string, options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
  3854. indexInformation(name: string): Promise<IndexDescriptionCompact>;
  3855. /**
  3856. * Create a new Change Stream, watching for new changes (insertions, updates,
  3857. * replacements, deletions, and invalidations) in this database. Will ignore all
  3858. * changes to system collections.
  3859. *
  3860. * @remarks
  3861. * watch() accepts two generic arguments for distinct use cases:
  3862. * - The first is to provide the schema that may be defined for all the collections within this database
  3863. * - 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
  3864. *
  3865. * @remarks
  3866. * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
  3867. * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
  3868. * stream will time out if it does not receive a change event within `timeoutMS` of the last change
  3869. * event.
  3870. *
  3871. * Note that if a change stream is consistently timing out when watching a collection, database or
  3872. * client that is being changed, then this may be due to the server timing out before it can finish
  3873. * processing the existing oplog. To address this, restart the change stream with a higher
  3874. * `timeoutMS`.
  3875. *
  3876. * If the change stream times out the initial aggregate operation to establish the change stream on
  3877. * the server, then the client will close the change stream. If the getMore calls to the server
  3878. * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
  3879. * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
  3880. * emitter mode.
  3881. *
  3882. * To determine whether or not the change stream is still open following a timeout, check the
  3883. * {@link ChangeStream.closed} getter.
  3884. *
  3885. * @example
  3886. * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
  3887. * The next call can just be retried after this succeeds.
  3888. * ```ts
  3889. * const changeStream = collection.watch([], { timeoutMS: 100 });
  3890. * try {
  3891. * await changeStream.next();
  3892. * } catch (e) {
  3893. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  3894. * await changeStream.next();
  3895. * }
  3896. * throw e;
  3897. * }
  3898. * ```
  3899. *
  3900. * @example
  3901. * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
  3902. * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
  3903. * stream unless the resume attempt fails. There is no need to re-establish change listeners as
  3904. * this will automatically continue emitting change events once the resume attempt completes.
  3905. *
  3906. * ```ts
  3907. * const changeStream = collection.watch([], { timeoutMS: 100 });
  3908. * changeStream.on('change', console.log);
  3909. * changeStream.on('error', e => {
  3910. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  3911. * // do nothing
  3912. * } else {
  3913. * changeStream.close();
  3914. * }
  3915. * });
  3916. * ```
  3917. * @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.
  3918. * @param options - Optional settings for the command
  3919. * @typeParam TSchema - Type of the data being detected by the change stream
  3920. * @typeParam TChange - Type of the whole change stream document emitted
  3921. */
  3922. watch<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream<TSchema, TChange>;
  3923. /**
  3924. * A low level cursor API providing basic driver functionality:
  3925. * - ClientSession management
  3926. * - ReadPreference for server selection
  3927. * - Running getMores automatically when a local batch is exhausted
  3928. *
  3929. * @param command - The command that will start a cursor on the server.
  3930. * @param options - Configurations for running the command, bson options will apply to getMores
  3931. */
  3932. runCursorCommand(command: Document, options?: RunCursorCommandOptions): RunCommandCursor;
  3933. }
  3934. /* Excluded from this release type: DB_AGGREGATE_COLLECTION */
  3935. /** @public */
  3936. export declare interface DbOptions extends BSONSerializeOptions, WriteConcernOptions {
  3937. /** If the database authentication is dependent on another databaseName. */
  3938. authSource?: string;
  3939. /** Force server to assign _id values instead of driver. */
  3940. forceServerObjectId?: boolean;
  3941. /** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */
  3942. readPreference?: ReadPreferenceLike;
  3943. /** A primary key factory object for generation of custom _id keys. */
  3944. pkFactory?: PkFactory;
  3945. /** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */
  3946. readConcern?: ReadConcern;
  3947. /** Should retry failed writes */
  3948. retryWrites?: boolean;
  3949. /**
  3950. * @experimental
  3951. * Specifies the time an operation will run until it throws a timeout error
  3952. */
  3953. timeoutMS?: number;
  3954. }
  3955. /* Excluded from this release type: DbPrivate */
  3956. export { DBRef }
  3957. /** @public */
  3958. export declare interface DbStatsOptions extends Omit<CommandOperationOptions, 'rawData'> {
  3959. /** Divide the returned sizes by scale value. */
  3960. scale?: number;
  3961. }
  3962. export { Decimal128 }
  3963. /** @public */
  3964. export declare interface DeleteManyModel<TSchema extends Document = Document> {
  3965. /** The filter to limit the deleted documents. */
  3966. filter: Filter<TSchema>;
  3967. /** Specifies a collation. */
  3968. collation?: CollationOptions;
  3969. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  3970. hint?: Hint;
  3971. }
  3972. /** @public */
  3973. export declare interface DeleteOneModel<TSchema extends Document = Document> {
  3974. /** The filter to limit the deleted documents. */
  3975. filter: Filter<TSchema>;
  3976. /** Specifies a collation. */
  3977. collation?: CollationOptions;
  3978. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  3979. hint?: Hint;
  3980. }
  3981. /** @public */
  3982. export declare interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions {
  3983. /** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */
  3984. ordered?: boolean;
  3985. /** Specifies the collation to use for the operation */
  3986. collation?: CollationOptions;
  3987. /** Specify that the update query should only consider plans using the hinted index */
  3988. hint?: string | Document;
  3989. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  3990. let?: Document;
  3991. }
  3992. /** @public */
  3993. export declare interface DeleteResult {
  3994. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */
  3995. acknowledged: boolean;
  3996. /** The number of documents that were deleted */
  3997. deletedCount: number;
  3998. }
  3999. /** @public */
  4000. export declare interface DeleteStatement {
  4001. /** The query that matches documents to delete. */
  4002. q: Document;
  4003. /** The number of matching documents to delete. */
  4004. limit: number;
  4005. /** Specifies the collation to use for the operation. */
  4006. collation?: CollationOptions;
  4007. /** A document or string that specifies the index to use to support the query predicate. */
  4008. hint?: Hint;
  4009. }
  4010. export { deserialize }
  4011. /** @public */
  4012. export declare type DistinctOptions = CommandOperationOptions & {
  4013. /**
  4014. * @sinceServerVersion 7.1
  4015. *
  4016. * The index to use. Specify either the index name as a string or the index key pattern.
  4017. * If specified, then the query system will only consider plans using the hinted index.
  4018. *
  4019. * If provided as a string, `hint` must be index name for an index on the collection.
  4020. * If provided as an object, `hint` must be an index description for an index defined on the collection.
  4021. *
  4022. * See https://www.mongodb.com/docs/manual/reference/command/distinct/#command-fields.
  4023. */
  4024. hint?: Document | string;
  4025. };
  4026. export { Document }
  4027. export { Double }
  4028. /** @public */
  4029. export declare interface DriverInfo {
  4030. name?: string;
  4031. version?: string;
  4032. platform?: string;
  4033. }
  4034. /** @public */
  4035. export declare interface DropCollectionOptions extends Omit<CommandOperationOptions, 'rawData'> {
  4036. /** @experimental */
  4037. encryptedFields?: Document;
  4038. }
  4039. /** @public */
  4040. export declare type DropDatabaseOptions = CommandOperationOptions;
  4041. /** @public */
  4042. export declare type DropIndexesOptions = CommandOperationOptions;
  4043. /* Excluded from this release type: Encrypter */
  4044. /* Excluded from this release type: EncrypterOptions */
  4045. /** @public */
  4046. export declare interface EndSessionOptions {
  4047. /* Excluded from this release type: error */
  4048. force?: boolean;
  4049. forceClear?: boolean;
  4050. /** Specifies the time an operation will run until it throws a timeout error */
  4051. timeoutMS?: number;
  4052. }
  4053. /** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */
  4054. export declare type EnhancedOmit<TRecordOrUnion, KeyUnion> = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>> : never;
  4055. /** @public */
  4056. export declare interface ErrorDescription extends Document {
  4057. message?: string;
  4058. errmsg?: string;
  4059. $err?: string;
  4060. errorLabels?: string[];
  4061. errInfo?: Document;
  4062. }
  4063. /** @public */
  4064. export declare interface EstimatedDocumentCountOptions extends CommandOperationOptions {
  4065. /**
  4066. * The maximum amount of time to allow the operation to run.
  4067. *
  4068. * This option is sent only if the caller explicitly provides a value. The default is to not send a value.
  4069. */
  4070. maxTimeMS?: number;
  4071. }
  4072. /** @public */
  4073. export declare type EventEmitterWithState = {
  4074. /* Excluded from this release type: stateChanged */
  4075. };
  4076. /**
  4077. * Event description type
  4078. * @public
  4079. */
  4080. export declare type EventsDescription = Record<string, GenericListener>;
  4081. /* Excluded from this release type: Explain */
  4082. /**
  4083. * @public
  4084. *
  4085. * A base class for any cursors that have `explain()` methods.
  4086. */
  4087. export declare abstract class ExplainableCursor<TSchema> extends AbstractCursor<TSchema> {
  4088. /** Execute the explain for the cursor */
  4089. abstract explain(): Promise<Document>;
  4090. abstract explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;
  4091. abstract explain(options: {
  4092. timeoutMS?: number;
  4093. }): Promise<Document>;
  4094. abstract explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions, options: {
  4095. timeoutMS?: number;
  4096. }): Promise<Document>;
  4097. abstract explain(verbosity?: ExplainVerbosityLike | ExplainCommandOptions | {
  4098. timeoutMS?: number;
  4099. }, options?: {
  4100. timeoutMS?: number;
  4101. }): Promise<Document>;
  4102. protected resolveExplainTimeoutOptions(verbosity?: ExplainVerbosityLike | ExplainCommandOptions | {
  4103. timeoutMS?: number;
  4104. }, options?: {
  4105. timeoutMS?: number;
  4106. }): {
  4107. timeout?: {
  4108. timeoutMS?: number;
  4109. };
  4110. explain?: ExplainVerbosityLike | ExplainCommandOptions;
  4111. };
  4112. }
  4113. /** @public */
  4114. export declare interface ExplainCommandOptions {
  4115. /** The explain verbosity for the command. */
  4116. verbosity: ExplainVerbosity;
  4117. /** The maxTimeMS setting for the command. */
  4118. maxTimeMS?: number;
  4119. }
  4120. /**
  4121. * @public
  4122. *
  4123. * When set, this configures an explain command. Valid values are boolean (for legacy compatibility,
  4124. * see {@link ExplainVerbosityLike}), a string containing the explain verbosity, or an object containing the verbosity and
  4125. * an optional maxTimeMS.
  4126. *
  4127. * Examples of valid usage:
  4128. *
  4129. * ```typescript
  4130. * collection.find({ name: 'john doe' }, { explain: true });
  4131. * collection.find({ name: 'john doe' }, { explain: false });
  4132. * collection.find({ name: 'john doe' }, { explain: 'queryPlanner' });
  4133. * collection.find({ name: 'john doe' }, { explain: { verbosity: 'queryPlanner' } });
  4134. * ```
  4135. *
  4136. * maxTimeMS can be configured to limit the amount of time the server
  4137. * spends executing an explain by providing an object:
  4138. *
  4139. * ```typescript
  4140. * // limits the `explain` command to no more than 2 seconds
  4141. * collection.find({ name: 'john doe' }, {
  4142. * explain: {
  4143. * verbosity: 'queryPlanner',
  4144. * maxTimeMS: 2000
  4145. * }
  4146. * });
  4147. * ```
  4148. */
  4149. export declare interface ExplainOptions {
  4150. /** Specifies the verbosity mode for the explain output. */
  4151. explain?: ExplainVerbosityLike | ExplainCommandOptions;
  4152. }
  4153. /** @public */
  4154. export declare const ExplainVerbosity: Readonly<{
  4155. readonly queryPlanner: "queryPlanner";
  4156. readonly queryPlannerExtended: "queryPlannerExtended";
  4157. readonly executionStats: "executionStats";
  4158. readonly allPlansExecution: "allPlansExecution";
  4159. }>;
  4160. /** @public */
  4161. export declare type ExplainVerbosity = string;
  4162. /**
  4163. * For backwards compatibility, true is interpreted as "allPlansExecution"
  4164. * and false as "queryPlanner".
  4165. * @public
  4166. */
  4167. export declare type ExplainVerbosityLike = ExplainVerbosity | boolean;
  4168. /** A MongoDB filter can be some portion of the schema or a set of operators @public */
  4169. export declare type Filter<TSchema> = {
  4170. [P in keyof WithId<TSchema>]?: Condition<WithId<TSchema>[P]>;
  4171. } & RootFilterOperators<WithId<TSchema>>;
  4172. /** @public */
  4173. export declare type FilterOperations<T> = T extends Record<string, any> ? {
  4174. [key in keyof T]?: FilterOperators<T[key]>;
  4175. } : FilterOperators<T>;
  4176. /** @public */
  4177. export declare interface FilterOperators<TValue> extends NonObjectIdLikeDocument {
  4178. $eq?: TValue;
  4179. $gt?: TValue;
  4180. $gte?: TValue;
  4181. $in?: ReadonlyArray<TValue>;
  4182. $lt?: TValue;
  4183. $lte?: TValue;
  4184. $ne?: TValue;
  4185. $nin?: ReadonlyArray<TValue>;
  4186. $not?: TValue extends string ? FilterOperators<TValue> | RegExp : FilterOperators<TValue>;
  4187. /**
  4188. * When `true`, `$exists` matches the documents that contain the field,
  4189. * including documents where the field value is null.
  4190. */
  4191. $exists?: boolean;
  4192. $type?: BSONType | BSONTypeAlias;
  4193. $expr?: Record<string, any>;
  4194. $jsonSchema?: Record<string, any>;
  4195. $mod?: TValue extends number ? [number, number] : never;
  4196. $regex?: TValue extends string ? RegExp | BSONRegExp | string : never;
  4197. $options?: TValue extends string ? string : never;
  4198. $geoIntersects?: {
  4199. $geometry: Document;
  4200. };
  4201. $geoWithin?: Document;
  4202. $near?: Document;
  4203. $nearSphere?: Document;
  4204. $maxDistance?: number;
  4205. $all?: ReadonlyArray<any>;
  4206. $elemMatch?: Document;
  4207. $size?: TValue extends ReadonlyArray<any> ? number : never;
  4208. $bitsAllClear?: BitwiseFilter;
  4209. $bitsAllSet?: BitwiseFilter;
  4210. $bitsAnyClear?: BitwiseFilter;
  4211. $bitsAnySet?: BitwiseFilter;
  4212. $rand?: Record<string, never>;
  4213. }
  4214. /** @public */
  4215. export declare class FindCursor<TSchema = any> extends ExplainableCursor<TSchema> {
  4216. /* Excluded from this release type: cursorFilter */
  4217. /* Excluded from this release type: numReturned */
  4218. /* Excluded from this release type: findOptions */
  4219. /* Excluded from this release type: __constructor */
  4220. clone(): FindCursor<TSchema>;
  4221. map<T>(transform: (doc: TSchema) => T): FindCursor<T>;
  4222. /* Excluded from this release type: _initialize */
  4223. /* Excluded from this release type: getMore */
  4224. /**
  4225. * Get the count of documents for this cursor
  4226. * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead
  4227. */
  4228. count(options?: CountOptions): Promise<number>;
  4229. /** Execute the explain for the cursor */
  4230. explain(): Promise<Document>;
  4231. explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;
  4232. explain(options: {
  4233. timeoutMS?: number;
  4234. }): Promise<Document>;
  4235. explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions, options: {
  4236. timeoutMS?: number;
  4237. }): Promise<Document>;
  4238. /** Set the cursor query */
  4239. filter(filter: Document): this;
  4240. /**
  4241. * Set the cursor hint
  4242. *
  4243. * @param hint - If specified, then the query system will only consider plans using the hinted index.
  4244. */
  4245. hint(hint: Hint): this;
  4246. /**
  4247. * Set the cursor min
  4248. *
  4249. * @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.
  4250. */
  4251. min(min: Document): this;
  4252. /**
  4253. * Set the cursor max
  4254. *
  4255. * @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.
  4256. */
  4257. max(max: Document): this;
  4258. /**
  4259. * Set the cursor returnKey.
  4260. * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents.
  4261. * 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.
  4262. *
  4263. * @param value - the returnKey value.
  4264. */
  4265. returnKey(value: boolean): this;
  4266. /**
  4267. * 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.
  4268. *
  4269. * @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.
  4270. */
  4271. showRecordId(value: boolean): this;
  4272. /**
  4273. * Add a query modifier to the cursor query
  4274. *
  4275. * @param name - The query modifier (must start with $, such as $orderby etc)
  4276. * @param value - The modifier value.
  4277. */
  4278. addQueryModifier(name: string, value: string | boolean | number | Document): this;
  4279. /**
  4280. * Add a comment to the cursor query allowing for tracking the comment in the log.
  4281. *
  4282. * @param value - The comment attached to this query.
  4283. */
  4284. comment(value: string): this;
  4285. /**
  4286. * 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)
  4287. *
  4288. * @param value - Number of milliseconds to wait before aborting the tailed query.
  4289. */
  4290. maxAwaitTimeMS(value: number): this;
  4291. /**
  4292. * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
  4293. *
  4294. * @param value - Number of milliseconds to wait before aborting the query.
  4295. */
  4296. maxTimeMS(value: number): this;
  4297. /**
  4298. * Add a project stage to the aggregation pipeline
  4299. *
  4300. * @remarks
  4301. * In order to strictly type this function you must provide an interface
  4302. * that represents the effect of your projection on the result documents.
  4303. *
  4304. * By default chaining a projection to your cursor changes the returned type to the generic
  4305. * {@link Document} type.
  4306. * You should specify a parameterized type to have assertions on your final results.
  4307. *
  4308. * @example
  4309. * ```typescript
  4310. * // Best way
  4311. * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
  4312. * // Flexible way
  4313. * const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
  4314. * ```
  4315. *
  4316. * @remarks
  4317. *
  4318. * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
  4319. * it **does not** return a new instance of a cursor. This means when calling project,
  4320. * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
  4321. * Take note of the following example:
  4322. *
  4323. * @example
  4324. * ```typescript
  4325. * const cursor: FindCursor<{ a: number; b: string }> = coll.find();
  4326. * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
  4327. * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
  4328. *
  4329. * // or always use chaining and save the final cursor
  4330. *
  4331. * const cursor = coll.find().project<{ a: string }>({
  4332. * _id: 0,
  4333. * a: { $convert: { input: '$a', to: 'string' }
  4334. * }});
  4335. * ```
  4336. */
  4337. project<T extends Document = Document>(value: Document): FindCursor<T>;
  4338. /**
  4339. * Sets the sort order of the cursor query.
  4340. *
  4341. * @param sort - The key or keys set for the sort.
  4342. * @param direction - The direction of the sorting (1 or -1).
  4343. */
  4344. sort(sort: Sort | string, direction?: SortDirection): this;
  4345. /**
  4346. * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher)
  4347. *
  4348. * @remarks
  4349. * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation}
  4350. */
  4351. allowDiskUse(allow?: boolean): this;
  4352. /**
  4353. * Set the collation options for the cursor.
  4354. *
  4355. * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  4356. */
  4357. collation(value: CollationOptions): this;
  4358. /**
  4359. * Set the limit for the cursor.
  4360. *
  4361. * @param value - The limit for the cursor query.
  4362. */
  4363. limit(value: number): this;
  4364. /**
  4365. * Set the skip for the cursor.
  4366. *
  4367. * @param value - The skip for the cursor query.
  4368. */
  4369. skip(value: number): this;
  4370. }
  4371. /** @public */
  4372. export declare interface FindOneAndDeleteOptions extends CommandOperationOptions {
  4373. /** 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.*/
  4374. hint?: Document;
  4375. /** Limits the fields to return for all matching documents. */
  4376. projection?: Document;
  4377. /** Determines which document the operation modifies if the query selects multiple documents. */
  4378. sort?: Sort;
  4379. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  4380. let?: Document;
  4381. /**
  4382. * Return the ModifyResult instead of the modified document. Defaults to false
  4383. */
  4384. includeResultMetadata?: boolean;
  4385. }
  4386. /** @public */
  4387. export declare interface FindOneAndReplaceOptions extends CommandOperationOptions {
  4388. /** Allow driver to bypass schema validation. */
  4389. bypassDocumentValidation?: boolean;
  4390. /** 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.*/
  4391. hint?: Document;
  4392. /** Limits the fields to return for all matching documents. */
  4393. projection?: Document;
  4394. /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */
  4395. returnDocument?: ReturnDocument;
  4396. /** Determines which document the operation modifies if the query selects multiple documents. */
  4397. sort?: Sort;
  4398. /** Upsert the document if it does not exist. */
  4399. upsert?: boolean;
  4400. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  4401. let?: Document;
  4402. /**
  4403. * Return the ModifyResult instead of the modified document. Defaults to false
  4404. */
  4405. includeResultMetadata?: boolean;
  4406. }
  4407. /** @public */
  4408. export declare interface FindOneAndUpdateOptions extends CommandOperationOptions {
  4409. /** Optional list of array filters referenced in filtered positional operators */
  4410. arrayFilters?: Document[];
  4411. /** Allow driver to bypass schema validation. */
  4412. bypassDocumentValidation?: boolean;
  4413. /** 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.*/
  4414. hint?: Document;
  4415. /** Limits the fields to return for all matching documents. */
  4416. projection?: Document;
  4417. /** When set to 'after', returns the updated document rather than the original. The default is 'before'. */
  4418. returnDocument?: ReturnDocument;
  4419. /** Determines which document the operation modifies if the query selects multiple documents. */
  4420. sort?: Sort;
  4421. /** Upsert the document if it does not exist. */
  4422. upsert?: boolean;
  4423. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  4424. let?: Document;
  4425. /**
  4426. * Return the ModifyResult instead of the modified document. Defaults to false
  4427. */
  4428. includeResultMetadata?: boolean;
  4429. }
  4430. /** @public */
  4431. export declare type FindOneOptions = Omit<FindOptions, 'batchSize' | 'limit' | 'noCursorTimeout'>;
  4432. /**
  4433. * A builder object that is returned from {@link BulkOperationBase#find}.
  4434. * Is used to build a write operation that involves a query filter.
  4435. *
  4436. * @public
  4437. */
  4438. export declare class FindOperators {
  4439. bulkOperation: BulkOperationBase;
  4440. /* Excluded from this release type: __constructor */
  4441. /** Add a multiple update operation to the bulk operation */
  4442. update(updateDocument: Document | Document[]): BulkOperationBase;
  4443. /** Add a single update operation to the bulk operation */
  4444. updateOne(updateDocument: Document | Document[]): BulkOperationBase;
  4445. /** Add a replace one operation to the bulk operation */
  4446. replaceOne(replacement: Document): BulkOperationBase;
  4447. /** Add a delete one operation to the bulk operation */
  4448. deleteOne(): BulkOperationBase;
  4449. /** Add a delete many operation to the bulk operation */
  4450. delete(): BulkOperationBase;
  4451. /** Upsert modifier for update bulk operation, noting that this operation is an upsert. */
  4452. upsert(): this;
  4453. /** Specifies the collation for the query condition. */
  4454. collation(collation: CollationOptions): this;
  4455. /** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */
  4456. arrayFilters(arrayFilters: Document[]): this;
  4457. /** Specifies hint for the bulk operation. */
  4458. hint(hint: Hint): this;
  4459. }
  4460. /**
  4461. * @public
  4462. */
  4463. export declare interface FindOptions extends Omit<CommandOperationOptions, 'writeConcern' | 'explain'>, AbstractCursorOptions {
  4464. /** Sets the limit of documents returned in the query. */
  4465. limit?: number;
  4466. /** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */
  4467. sort?: Sort;
  4468. /** 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}` */
  4469. projection?: Document;
  4470. /** Set to skip N documents ahead in your query (useful for pagination). */
  4471. skip?: number;
  4472. /** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */
  4473. hint?: Hint;
  4474. /** Specify if the cursor can timeout. */
  4475. timeout?: boolean;
  4476. /** Specify if the cursor is tailable. */
  4477. tailable?: boolean;
  4478. /** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */
  4479. awaitData?: boolean;
  4480. /** Set the batchSize for the getMoreCommand when iterating over the query results. */
  4481. batchSize?: number;
  4482. /** If true, returns only the index keys in the resulting documents. */
  4483. returnKey?: boolean;
  4484. /** The inclusive lower bound for a specific index */
  4485. min?: Document;
  4486. /** The exclusive upper bound for a specific index */
  4487. max?: Document;
  4488. /** Number of milliseconds to wait before aborting the query. */
  4489. maxTimeMS?: number;
  4490. /** 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 */
  4491. maxAwaitTimeMS?: number;
  4492. /** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */
  4493. noCursorTimeout?: boolean;
  4494. /** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */
  4495. collation?: CollationOptions;
  4496. /** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */
  4497. allowDiskUse?: boolean;
  4498. /** Determines whether to close the cursor after the first batch. Defaults to false. */
  4499. singleBatch?: boolean;
  4500. /** 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. */
  4501. allowPartialResults?: boolean;
  4502. /** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */
  4503. showRecordId?: boolean;
  4504. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  4505. let?: Document;
  4506. /**
  4507. * 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.
  4508. * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored.
  4509. */
  4510. oplogReplay?: boolean;
  4511. /**
  4512. * Specifies the verbosity mode for the explain output.
  4513. * @deprecated This API is deprecated in favor of `collection.find().explain()`.
  4514. */
  4515. explain?: ExplainOptions['explain'];
  4516. /* Excluded from this release type: timeoutMode */
  4517. }
  4518. /** @public */
  4519. export declare type Flatten<Type> = Type extends ReadonlyArray<infer Item> ? Item : Type;
  4520. /**
  4521. * @public
  4522. * Configuration options for making an AWS encryption key
  4523. */
  4524. export declare interface GCPEncryptionKeyOptions {
  4525. /**
  4526. * GCP project ID
  4527. */
  4528. projectId: string;
  4529. /**
  4530. * Location name (e.g. "global")
  4531. */
  4532. location: string;
  4533. /**
  4534. * Key ring name
  4535. */
  4536. keyRing: string;
  4537. /**
  4538. * Key name
  4539. */
  4540. keyName: string;
  4541. /**
  4542. * Key version
  4543. */
  4544. keyVersion?: string | undefined;
  4545. /**
  4546. * KMS URL, defaults to `https://www.googleapis.com/auth/cloudkms`
  4547. */
  4548. endpoint?: string | undefined;
  4549. }
  4550. /** @public */
  4551. export declare type GCPKMSProviderConfiguration = {
  4552. /**
  4553. * The service account email to authenticate
  4554. */
  4555. email: string;
  4556. /**
  4557. * A PKCS#8 encrypted key. This can either be a base64 string or a binary representation
  4558. */
  4559. privateKey: string | Buffer;
  4560. /**
  4561. * If present, a host with optional port. E.g. "example.com" or "example.com:443".
  4562. * Defaults to "oauth2.googleapis.com"
  4563. */
  4564. endpoint?: string | undefined;
  4565. } | {
  4566. /**
  4567. * If present, an access token to authenticate with GCP.
  4568. */
  4569. accessToken: string;
  4570. };
  4571. /** @public */
  4572. export declare type GenericListener = (...args: any[]) => void;
  4573. /**
  4574. * Constructor for a streaming GridFS interface
  4575. * @public
  4576. */
  4577. export declare class GridFSBucket extends TypedEventEmitter<GridFSBucketEvents> {
  4578. /* Excluded from this release type: s */
  4579. /**
  4580. * When the first call to openUploadStream is made, the upload stream will
  4581. * check to see if it needs to create the proper indexes on the chunks and
  4582. * files collections. This event is fired either when 1) it determines that
  4583. * no index creation is necessary, 2) when it successfully creates the
  4584. * necessary indexes.
  4585. * @event
  4586. */
  4587. static readonly INDEX: "index";
  4588. constructor(db: Db, options?: GridFSBucketOptions);
  4589. /**
  4590. * Returns a writable stream (GridFSBucketWriteStream) for writing
  4591. * buffers to GridFS. The stream's 'id' property contains the resulting
  4592. * file's id.
  4593. *
  4594. * @param filename - The value of the 'filename' key in the files doc
  4595. * @param options - Optional settings.
  4596. */
  4597. openUploadStream(filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream;
  4598. /**
  4599. * Returns a writable stream (GridFSBucketWriteStream) for writing
  4600. * buffers to GridFS for a custom file id. The stream's 'id' property contains the resulting
  4601. * file's id.
  4602. */
  4603. openUploadStreamWithId(id: ObjectId, filename: string, options?: GridFSBucketWriteStreamOptions): GridFSBucketWriteStream;
  4604. /** Returns a readable stream (GridFSBucketReadStream) for streaming file data from GridFS. */
  4605. openDownloadStream(id: ObjectId, options?: GridFSBucketReadStreamOptions): GridFSBucketReadStream;
  4606. /**
  4607. * Deletes a file with the given id
  4608. *
  4609. * @param id - The id of the file doc
  4610. */
  4611. delete(id: ObjectId, options?: {
  4612. timeoutMS: number;
  4613. }): Promise<void>;
  4614. /** Convenience wrapper around find on the files collection */
  4615. find(filter?: Filter<GridFSFile>, options?: FindOptions): FindCursor<GridFSFile>;
  4616. /**
  4617. * Returns a readable stream (GridFSBucketReadStream) for streaming the
  4618. * file with the given name from GridFS. If there are multiple files with
  4619. * the same name, this will stream the most recent file with the given name
  4620. * (as determined by the `uploadDate` field). You can set the `revision`
  4621. * option to change this behavior.
  4622. */
  4623. openDownloadStreamByName(filename: string, options?: GridFSBucketReadStreamOptionsWithRevision): GridFSBucketReadStream;
  4624. /**
  4625. * Renames the file with the given _id to the given string
  4626. *
  4627. * @param id - the id of the file to rename
  4628. * @param filename - new name for the file
  4629. */
  4630. rename(id: ObjectId, filename: string, options?: {
  4631. timeoutMS: number;
  4632. }): Promise<void>;
  4633. /** Removes this bucket's files collection, followed by its chunks collection. */
  4634. drop(options?: {
  4635. timeoutMS: number;
  4636. }): Promise<void>;
  4637. }
  4638. /** @public */
  4639. export declare type GridFSBucketEvents = {
  4640. index(): void;
  4641. };
  4642. /** @public */
  4643. export declare interface GridFSBucketOptions extends WriteConcernOptions {
  4644. /** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */
  4645. bucketName?: string;
  4646. /** Number of bytes stored in each chunk. Defaults to 255KB */
  4647. chunkSizeBytes?: number;
  4648. /** Read preference to be passed to read operations */
  4649. readPreference?: ReadPreference;
  4650. /**
  4651. * @experimental
  4652. * Specifies the lifetime duration of a gridFS stream. If any async operations are in progress
  4653. * when this timeout expires, the stream will throw a timeout error.
  4654. */
  4655. timeoutMS?: number;
  4656. }
  4657. /* Excluded from this release type: GridFSBucketPrivate */
  4658. /**
  4659. * A readable stream that enables you to read buffers from GridFS.
  4660. *
  4661. * Do not instantiate this class directly. Use `openDownloadStream()` instead.
  4662. * @public
  4663. */
  4664. export declare class GridFSBucketReadStream extends Readable {
  4665. /* Excluded from this release type: s */
  4666. /**
  4667. * Fires when the stream loaded the file document corresponding to the provided id.
  4668. * @event
  4669. */
  4670. static readonly FILE: "file";
  4671. /* Excluded from this release type: __constructor */
  4672. /* Excluded from this release type: _read */
  4673. /**
  4674. * Sets the 0-based offset in bytes to start streaming from. Throws
  4675. * an error if this stream has entered flowing mode
  4676. * (e.g. if you've already called `on('data')`)
  4677. *
  4678. * @param start - 0-based offset in bytes to start streaming from
  4679. */
  4680. start(start?: number): this;
  4681. /**
  4682. * Sets the 0-based offset in bytes to start streaming from. Throws
  4683. * an error if this stream has entered flowing mode
  4684. * (e.g. if you've already called `on('data')`)
  4685. *
  4686. * @param end - Offset in bytes to stop reading at
  4687. */
  4688. end(end?: number): this;
  4689. /**
  4690. * Marks this stream as aborted (will never push another `data` event)
  4691. * and kills the underlying cursor. Will emit the 'end' event, and then
  4692. * the 'close' event once the cursor is successfully killed.
  4693. */
  4694. abort(): Promise<void>;
  4695. }
  4696. /** @public */
  4697. export declare interface GridFSBucketReadStreamOptions {
  4698. sort?: Sort;
  4699. skip?: number;
  4700. /**
  4701. * 0-indexed non-negative byte offset from the beginning of the file
  4702. */
  4703. start?: number;
  4704. /**
  4705. * 0-indexed non-negative byte offset to the end of the file contents
  4706. * to be returned by the stream. `end` is non-inclusive
  4707. */
  4708. end?: number;
  4709. /**
  4710. * @experimental
  4711. * Specifies the time an operation will run until it throws a timeout error
  4712. */
  4713. timeoutMS?: number;
  4714. }
  4715. /** @public */
  4716. export declare interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions {
  4717. /** The revision number relative to the oldest file with the given filename. 0
  4718. * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the
  4719. * newest. */
  4720. revision?: number;
  4721. }
  4722. /* Excluded from this release type: GridFSBucketReadStreamPrivate */
  4723. /**
  4724. * A writable stream that enables you to write buffers to GridFS.
  4725. *
  4726. * Do not instantiate this class directly. Use `openUploadStream()` instead.
  4727. * @public
  4728. */
  4729. export declare class GridFSBucketWriteStream extends Writable {
  4730. bucket: GridFSBucket;
  4731. /** A Collection instance where the file's chunks are stored */
  4732. chunks: Collection<GridFSChunk>;
  4733. /** A Collection instance where the file's GridFSFile document is stored */
  4734. files: Collection<GridFSFile>;
  4735. /** The name of the file */
  4736. filename: string;
  4737. /** Options controlling the metadata inserted along with the file */
  4738. options: GridFSBucketWriteStreamOptions;
  4739. /** Indicates the stream is finished uploading */
  4740. done: boolean;
  4741. /** The ObjectId used for the `_id` field on the GridFSFile document */
  4742. id: ObjectId;
  4743. /** The number of bytes that each chunk will be limited to */
  4744. chunkSizeBytes: number;
  4745. /** Space used to store a chunk currently being inserted */
  4746. bufToStore: Buffer;
  4747. /** Accumulates the number of bytes inserted as the stream uploads chunks */
  4748. length: number;
  4749. /** Accumulates the number of chunks inserted as the stream uploads file contents */
  4750. n: number;
  4751. /** Tracks the current offset into the buffered bytes being uploaded */
  4752. pos: number;
  4753. /** Contains a number of properties indicating the current state of the stream */
  4754. state: {
  4755. /** If set the stream has ended */
  4756. streamEnd: boolean;
  4757. /** Indicates the number of chunks that still need to be inserted to exhaust the current buffered data */
  4758. outstandingRequests: number;
  4759. /** If set an error occurred during insertion */
  4760. errored: boolean;
  4761. /** If set the stream was intentionally aborted */
  4762. aborted: boolean;
  4763. };
  4764. /** The write concern setting to be used with every insert operation */
  4765. writeConcern?: WriteConcern;
  4766. /**
  4767. * The document containing information about the inserted file.
  4768. * This property is defined _after_ the finish event has been emitted.
  4769. * It will remain `null` if an error occurs.
  4770. *
  4771. * @example
  4772. * ```ts
  4773. * fs.createReadStream('file.txt')
  4774. * .pipe(bucket.openUploadStream('file.txt'))
  4775. * .on('finish', function () {
  4776. * console.log(this.gridFSFile)
  4777. * })
  4778. * ```
  4779. */
  4780. gridFSFile: GridFSFile | null;
  4781. /* Excluded from this release type: timeoutContext */
  4782. /* Excluded from this release type: __constructor */
  4783. /* Excluded from this release type: _construct */
  4784. /* Excluded from this release type: _write */
  4785. /* Excluded from this release type: _final */
  4786. /**
  4787. * Places this write stream into an aborted state (all future writes fail)
  4788. * and deletes all chunks that have already been written.
  4789. */
  4790. abort(): Promise<void>;
  4791. }
  4792. /** @public */
  4793. export declare interface GridFSBucketWriteStreamOptions extends WriteConcernOptions {
  4794. /** Overwrite this bucket's chunkSizeBytes for this file */
  4795. chunkSizeBytes?: number;
  4796. /** Custom file id for the GridFS file. */
  4797. id?: ObjectId;
  4798. /** Object to store in the file document's `metadata` field */
  4799. metadata?: Document;
  4800. /**
  4801. * @experimental
  4802. * Specifies the time an operation will run until it throws a timeout error
  4803. */
  4804. timeoutMS?: number;
  4805. }
  4806. /** @public */
  4807. export declare interface GridFSChunk {
  4808. _id: ObjectId;
  4809. files_id: ObjectId;
  4810. n: number;
  4811. data: Buffer | Uint8Array;
  4812. }
  4813. /** @public */
  4814. export declare interface GridFSFile {
  4815. _id: ObjectId;
  4816. length: number;
  4817. chunkSize: number;
  4818. filename: string;
  4819. metadata?: Document;
  4820. uploadDate: Date;
  4821. }
  4822. /** @public */
  4823. export declare const GSSAPICanonicalizationValue: Readonly<{
  4824. readonly on: true;
  4825. readonly off: false;
  4826. readonly none: "none";
  4827. readonly forward: "forward";
  4828. readonly forwardAndReverse: "forwardAndReverse";
  4829. }>;
  4830. /** @public */
  4831. export declare type GSSAPICanonicalizationValue = (typeof GSSAPICanonicalizationValue)[keyof typeof GSSAPICanonicalizationValue];
  4832. /* Excluded from this release type: HandshakeDocument */
  4833. /** @public */
  4834. export declare interface HedgeOptions {
  4835. /** Explicitly enable or disable hedged reads. */
  4836. enabled?: boolean;
  4837. }
  4838. /** @public */
  4839. export declare type Hint = string | Document;
  4840. /** @public */
  4841. export declare class HostAddress {
  4842. host: string | undefined;
  4843. port: number | undefined;
  4844. socketPath: string | undefined;
  4845. isIPv6: boolean;
  4846. constructor(hostString: string);
  4847. inspect(): string;
  4848. toString(): string;
  4849. static fromString(this: void, s: string): HostAddress;
  4850. static fromHostPort(host: string, port: number): HostAddress;
  4851. static fromSrvRecord({ name, port }: SrvRecord): HostAddress;
  4852. toHostPort(): {
  4853. host: string;
  4854. port: number;
  4855. };
  4856. }
  4857. /**
  4858. * The information returned by the server on the IDP server.
  4859. * @public
  4860. */
  4861. export declare interface IdPInfo {
  4862. /**
  4863. * A URL which describes the Authentication Server. This identifier should
  4864. * be the iss of provided access tokens, and be viable for RFC8414 metadata
  4865. * discovery and RFC9207 identification.
  4866. */
  4867. issuer: string;
  4868. /** A unique client ID for this OIDC client. */
  4869. clientId: string;
  4870. /** A list of additional scopes to request from IdP. */
  4871. requestScopes?: string[];
  4872. }
  4873. /**
  4874. * The response from the IdP server with the access token and
  4875. * optional expiration time and refresh token.
  4876. * @public
  4877. */
  4878. export declare interface IdPServerResponse {
  4879. /** The OIDC access token. */
  4880. accessToken: string;
  4881. /** The time when the access token expires. For future use. */
  4882. expiresInSeconds?: number;
  4883. /** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
  4884. refreshToken?: string;
  4885. }
  4886. /** @public */
  4887. 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'> {
  4888. collation?: CollationOptions;
  4889. name?: string;
  4890. key: {
  4891. [key: string]: IndexDirection;
  4892. } | Map<string, IndexDirection>;
  4893. }
  4894. /** @public */
  4895. export declare type IndexDescriptionCompact = Record<string, [name: string, direction: IndexDirection][]>;
  4896. /**
  4897. * @public
  4898. * The index information returned by the listIndexes command. https://www.mongodb.com/docs/manual/reference/command/listIndexes/#mongodb-dbcommand-dbcmd.listIndexes
  4899. */
  4900. export declare type IndexDescriptionInfo = Omit<IndexDescription, 'key' | 'version'> & {
  4901. key: {
  4902. [key: string]: IndexDirection;
  4903. };
  4904. v?: IndexDescription['version'];
  4905. } & Document;
  4906. /** @public */
  4907. export declare type IndexDirection = -1 | 1 | '2d' | '2dsphere' | 'text' | 'geoHaystack' | 'hashed' | number;
  4908. /** @public */
  4909. export declare interface IndexInformationOptions extends ListIndexesOptions {
  4910. /**
  4911. * When `true`, an array of index descriptions is returned.
  4912. * When `false`, the driver returns an object that with keys corresponding to index names with values
  4913. * corresponding to the entries of the indexes' key.
  4914. *
  4915. * For example, the given the following indexes:
  4916. * ```
  4917. * [ { name: 'a_1', key: { a: 1 } }, { name: 'b_1_c_1' , key: { b: 1, c: 1 } }]
  4918. * ```
  4919. *
  4920. * When `full` is `true`, the above array is returned. When `full` is `false`, the following is returned:
  4921. * ```
  4922. * {
  4923. * 'a_1': [['a', 1]],
  4924. * 'b_1_c_1': [['b', 1], ['c', 1]],
  4925. * }
  4926. * ```
  4927. */
  4928. full?: boolean;
  4929. }
  4930. /** @public */
  4931. export declare type IndexSpecification = OneOrMore<string | [string, IndexDirection] | {
  4932. [key: string]: IndexDirection;
  4933. } | Map<string, IndexDirection>>;
  4934. /** Given an object shaped type, return the type of the _id field or default to ObjectId @public */
  4935. export declare type InferIdType<TSchema> = TSchema extends {
  4936. _id: infer IdType;
  4937. } ? Record<any, never> extends IdType ? never : IdType : TSchema extends {
  4938. _id?: infer IdType;
  4939. } ? unknown extends IdType ? ObjectId : IdType : ObjectId;
  4940. /* Excluded from this release type: InitialCursorResponse */
  4941. /** @public */
  4942. export declare interface InsertManyResult<TSchema = Document> {
  4943. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  4944. acknowledged: boolean;
  4945. /** The number of inserted documents for this operations */
  4946. insertedCount: number;
  4947. /** Map of the index of the inserted document to the id of the inserted document */
  4948. insertedIds: {
  4949. [key: number]: InferIdType<TSchema>;
  4950. };
  4951. }
  4952. /** @public */
  4953. export declare interface InsertOneModel<TSchema extends Document = Document> {
  4954. /** The document to insert. */
  4955. document: OptionalId<TSchema>;
  4956. }
  4957. /** @public */
  4958. export declare interface InsertOneOptions extends CommandOperationOptions {
  4959. /** Allow driver to bypass schema validation. */
  4960. bypassDocumentValidation?: boolean;
  4961. /** Force server to assign _id values instead of driver. */
  4962. forceServerObjectId?: boolean;
  4963. }
  4964. /** @public */
  4965. export declare interface InsertOneResult<TSchema = Document> {
  4966. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  4967. acknowledged: boolean;
  4968. /** 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 */
  4969. insertedId: InferIdType<TSchema>;
  4970. }
  4971. export { Int32 }
  4972. /** @public */
  4973. export declare type IntegerType = number | Int32 | Long | bigint;
  4974. /* Excluded from this release type: InternalAbstractCursorOptions */
  4975. /** @public */
  4976. export declare type IsAny<Type, ResultIfAny, ResultIfNotAny> = true extends false & Type ? ResultIfAny : ResultIfNotAny;
  4977. /**
  4978. * Helper types for dot-notation filter attributes
  4979. */
  4980. /** @public */
  4981. 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;
  4982. /* Excluded from this release type: JSTypeOf */
  4983. /* Excluded from this release type: kDecorateResult */
  4984. /** @public */
  4985. export declare type KeysOfAType<TSchema, Type> = {
  4986. [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? key : never;
  4987. }[keyof TSchema];
  4988. /** @public */
  4989. export declare type KeysOfOtherType<TSchema, Type> = {
  4990. [key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? never : key;
  4991. }[keyof TSchema];
  4992. /**
  4993. * @public
  4994. * Configuration options for making a KMIP encryption key
  4995. */
  4996. export declare interface KMIPEncryptionKeyOptions {
  4997. /**
  4998. * keyId is the KMIP Unique Identifier to a 96 byte KMIP Secret Data managed object.
  4999. *
  5000. * If keyId is omitted, a random 96 byte KMIP Secret Data managed object will be created.
  5001. */
  5002. keyId?: string;
  5003. /**
  5004. * Host with optional port.
  5005. */
  5006. endpoint?: string;
  5007. /**
  5008. * If true, this key should be decrypted by the KMIP server.
  5009. *
  5010. * Requires `mongodb-client-encryption>=6.0.1`.
  5011. */
  5012. delegated?: boolean;
  5013. }
  5014. /** @public */
  5015. export declare interface KMIPKMSProviderConfiguration {
  5016. /**
  5017. * The output endpoint string.
  5018. * The endpoint consists of a hostname and port separated by a colon.
  5019. * E.g. "example.com:123". A port is always present.
  5020. */
  5021. endpoint?: string;
  5022. }
  5023. /**
  5024. * @public
  5025. * Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.
  5026. *
  5027. * Named KMS providers _are not supported_ for automatic KMS credential fetching.
  5028. */
  5029. export declare interface KMSProviders {
  5030. /**
  5031. * Configuration options for using 'aws' as your KMS provider
  5032. */
  5033. aws?: AWSKMSProviderConfiguration | Record<string, never>;
  5034. [key: `aws:${string}`]: AWSKMSProviderConfiguration;
  5035. /**
  5036. * Configuration options for using 'local' as your KMS provider
  5037. */
  5038. local?: LocalKMSProviderConfiguration;
  5039. [key: `local:${string}`]: LocalKMSProviderConfiguration;
  5040. /**
  5041. * Configuration options for using 'kmip' as your KMS provider
  5042. */
  5043. kmip?: KMIPKMSProviderConfiguration;
  5044. [key: `kmip:${string}`]: KMIPKMSProviderConfiguration;
  5045. /**
  5046. * Configuration options for using 'azure' as your KMS provider
  5047. */
  5048. azure?: AzureKMSProviderConfiguration | Record<string, never>;
  5049. [key: `azure:${string}`]: AzureKMSProviderConfiguration;
  5050. /**
  5051. * Configuration options for using 'gcp' as your KMS provider
  5052. */
  5053. gcp?: GCPKMSProviderConfiguration | Record<string, never>;
  5054. [key: `gcp:${string}`]: GCPKMSProviderConfiguration;
  5055. }
  5056. /* Excluded from this release type: LegacyTimeoutContext */
  5057. /* Excluded from this release type: LegacyTimeoutContextOptions */
  5058. /** @public */
  5059. export declare const LEGAL_TCP_SOCKET_OPTIONS: readonly ["autoSelectFamily", "autoSelectFamilyAttemptTimeout", "keepAliveInitialDelay", "family", "hints", "localAddress", "localPort", "lookup"];
  5060. /** @public */
  5061. export declare const LEGAL_TLS_SOCKET_OPTIONS: readonly ["allowPartialTrustChain", "ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"];
  5062. /* Excluded from this release type: List */
  5063. /** @public */
  5064. export declare class ListCollectionsCursor<T extends Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo = Pick<CollectionInfo, 'name' | 'type'> | CollectionInfo> extends AbstractCursor<T> {
  5065. parent: Db;
  5066. filter: Document;
  5067. options?: ListCollectionsOptions & Abortable;
  5068. constructor(db: Db, filter: Document, options?: ListCollectionsOptions & Abortable);
  5069. clone(): ListCollectionsCursor<T>;
  5070. /* Excluded from this release type: _initialize */
  5071. }
  5072. /** @public */
  5073. export declare interface ListCollectionsOptions extends Omit<CommandOperationOptions, 'writeConcern'>, Abortable {
  5074. /** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */
  5075. nameOnly?: boolean;
  5076. /** 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. */
  5077. authorizedCollections?: boolean;
  5078. /** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */
  5079. batchSize?: number;
  5080. /* Excluded from this release type: timeoutMode */
  5081. /* Excluded from this release type: timeoutContext */
  5082. }
  5083. /** @public */
  5084. export declare interface ListDatabasesOptions extends Omit<CommandOperationOptions, 'rawData'> {
  5085. /** A query predicate that determines which databases are listed */
  5086. filter?: Document;
  5087. /** A flag to indicate whether the command should return just the database names, or return both database names and size information */
  5088. nameOnly?: boolean;
  5089. /** A flag that determines which databases are returned based on the user privileges when access control is enabled */
  5090. authorizedDatabases?: boolean;
  5091. }
  5092. /** @public */
  5093. export declare interface ListDatabasesResult {
  5094. databases: ({
  5095. name: string;
  5096. sizeOnDisk?: number;
  5097. empty?: boolean;
  5098. } & Document)[];
  5099. totalSize?: number;
  5100. totalSizeMb?: number;
  5101. ok: 1 | 0;
  5102. }
  5103. /** @public */
  5104. export declare class ListIndexesCursor extends AbstractCursor {
  5105. parent: Collection;
  5106. options?: ListIndexesOptions;
  5107. constructor(collection: Collection, options?: ListIndexesOptions);
  5108. clone(): ListIndexesCursor;
  5109. /* Excluded from this release type: _initialize */
  5110. }
  5111. /** @public */
  5112. export declare type ListIndexesOptions = AbstractCursorOptions & {
  5113. /* Excluded from this release type: omitMaxTimeMS */
  5114. /* Excluded from this release type: rawData */
  5115. };
  5116. /** @public */
  5117. export declare class ListSearchIndexesCursor extends AggregationCursor<{
  5118. name: string;
  5119. }> {
  5120. /* Excluded from this release type: __constructor */
  5121. }
  5122. /** @public */
  5123. export declare type ListSearchIndexesOptions = Omit<AggregateOptions, 'readConcern' | 'writeConcern'>;
  5124. /** @public */
  5125. export declare interface LocalKMSProviderConfiguration {
  5126. /**
  5127. * The master key used to encrypt/decrypt data keys.
  5128. * A 96-byte long Buffer or base64 encoded string.
  5129. */
  5130. key: Binary | Uint8Array | string;
  5131. }
  5132. /** @public */
  5133. export declare interface Log extends Record<string, any> {
  5134. t: Date;
  5135. c: MongoLoggableComponent;
  5136. s: SeverityLevel;
  5137. message?: string;
  5138. }
  5139. /** @public */
  5140. export declare interface LogComponentSeveritiesClientOptions {
  5141. /** Optional severity level for command component */
  5142. command?: SeverityLevel;
  5143. /** Optional severity level for topology component */
  5144. topology?: SeverityLevel;
  5145. /** Optional severity level for server selection component */
  5146. serverSelection?: SeverityLevel;
  5147. /** Optional severity level for connection component */
  5148. connection?: SeverityLevel;
  5149. /** Optional severity level for client component */
  5150. client?: SeverityLevel;
  5151. /** Optional default severity level to be used if any of the above are unset */
  5152. default?: SeverityLevel;
  5153. }
  5154. /* Excluded from this release type: LogConvertible */
  5155. /* Excluded from this release type: Loggable */
  5156. /* Excluded from this release type: LoggableCommandFailedEvent */
  5157. /* Excluded from this release type: LoggableCommandSucceededEvent */
  5158. /* Excluded from this release type: LoggableEvent */
  5159. /* Excluded from this release type: LoggableServerHeartbeatFailedEvent */
  5160. /* Excluded from this release type: LoggableServerHeartbeatStartedEvent */
  5161. /* Excluded from this release type: LoggableServerHeartbeatSucceededEvent */
  5162. export { Long }
  5163. /** @public */
  5164. export declare type MatchKeysAndValues<TSchema> = Readonly<Partial<TSchema>> & Record<string, any>;
  5165. export { MaxKey }
  5166. /* Excluded from this release type: MessageHeader */
  5167. export { MinKey }
  5168. /** @public */
  5169. export declare interface ModifyResult<TSchema = Document> {
  5170. value: WithId<TSchema> | null;
  5171. lastErrorObject?: Document;
  5172. ok: 0 | 1;
  5173. }
  5174. /** @public */
  5175. 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"];
  5176. /**
  5177. * An error generated when the driver API is used incorrectly
  5178. *
  5179. * @privateRemarks
  5180. * Should **never** be directly instantiated
  5181. *
  5182. * @public
  5183. * @category Error
  5184. */
  5185. export declare class MongoAPIError extends MongoDriverError {
  5186. /**
  5187. * **Do not use this constructor!**
  5188. *
  5189. * Meant for internal use only.
  5190. *
  5191. * @remarks
  5192. * This class is only meant to be constructed within the driver. This constructor is
  5193. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5194. *
  5195. * @public
  5196. **/
  5197. constructor(message: string, options?: {
  5198. cause?: Error;
  5199. });
  5200. get name(): string;
  5201. }
  5202. /**
  5203. * A error generated when the user attempts to authenticate
  5204. * via AWS, but fails
  5205. *
  5206. * @public
  5207. * @category Error
  5208. */
  5209. export declare class MongoAWSError extends MongoRuntimeError {
  5210. /**
  5211. * **Do not use this constructor!**
  5212. *
  5213. * Meant for internal use only.
  5214. *
  5215. * @remarks
  5216. * This class is only meant to be constructed within the driver. This constructor is
  5217. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5218. *
  5219. * @public
  5220. **/
  5221. constructor(message: string, options?: {
  5222. cause?: Error;
  5223. });
  5224. get name(): string;
  5225. }
  5226. /**
  5227. * A error generated when the user attempts to authenticate
  5228. * via Azure, but fails.
  5229. *
  5230. * @public
  5231. * @category Error
  5232. */
  5233. export declare class MongoAzureError extends MongoOIDCError {
  5234. /**
  5235. * **Do not use this constructor!**
  5236. *
  5237. * Meant for internal use only.
  5238. *
  5239. * @remarks
  5240. * This class is only meant to be constructed within the driver. This constructor is
  5241. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5242. *
  5243. * @public
  5244. **/
  5245. constructor(message: string);
  5246. get name(): string;
  5247. }
  5248. /**
  5249. * An error generated when a batch command is re-executed after one of the commands in the batch
  5250. * has failed
  5251. *
  5252. * @public
  5253. * @category Error
  5254. */
  5255. export declare class MongoBatchReExecutionError extends MongoAPIError {
  5256. /**
  5257. * **Do not use this constructor!**
  5258. *
  5259. * Meant for internal use only.
  5260. *
  5261. * @remarks
  5262. * This class is only meant to be constructed within the driver. This constructor is
  5263. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5264. *
  5265. * @public
  5266. **/
  5267. constructor(message?: string);
  5268. get name(): string;
  5269. }
  5270. /**
  5271. * An error indicating an unsuccessful Bulk Write
  5272. * @public
  5273. * @category Error
  5274. */
  5275. export declare class MongoBulkWriteError extends MongoServerError {
  5276. result: BulkWriteResult;
  5277. writeErrors: OneOrMore<WriteError>;
  5278. err?: WriteConcernError;
  5279. /**
  5280. * **Do not use this constructor!**
  5281. *
  5282. * Meant for internal use only.
  5283. *
  5284. * @remarks
  5285. * This class is only meant to be constructed within the driver. This constructor is
  5286. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5287. *
  5288. * @public
  5289. **/
  5290. constructor(error: {
  5291. message: string;
  5292. code: number;
  5293. writeErrors?: WriteError[];
  5294. } | WriteConcernError | AnyError, result: BulkWriteResult);
  5295. get name(): string;
  5296. /** Number of documents inserted. */
  5297. get insertedCount(): number;
  5298. /** Number of documents matched for update. */
  5299. get matchedCount(): number;
  5300. /** Number of documents modified. */
  5301. get modifiedCount(): number;
  5302. /** Number of documents deleted. */
  5303. get deletedCount(): number;
  5304. /** Number of documents upserted. */
  5305. get upsertedCount(): number;
  5306. /** Inserted document generated Id's, hash key is the index of the originating operation */
  5307. get insertedIds(): {
  5308. [key: number]: any;
  5309. };
  5310. /** Upserted document generated Id's, hash key is the index of the originating operation */
  5311. get upsertedIds(): {
  5312. [key: number]: any;
  5313. };
  5314. }
  5315. /**
  5316. * An error generated when a ChangeStream operation fails to execute.
  5317. *
  5318. * @public
  5319. * @category Error
  5320. */
  5321. export declare class MongoChangeStreamError extends MongoRuntimeError {
  5322. /**
  5323. * **Do not use this constructor!**
  5324. *
  5325. * Meant for internal use only.
  5326. *
  5327. * @remarks
  5328. * This class is only meant to be constructed within the driver. This constructor is
  5329. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5330. *
  5331. * @public
  5332. **/
  5333. constructor(message: string);
  5334. get name(): string;
  5335. }
  5336. /**
  5337. * @public
  5338. *
  5339. * The **MongoClient** class is a class that allows for making Connections to MongoDB.
  5340. *
  5341. * **NOTE:** The programmatically provided options take precedence over the URI options.
  5342. *
  5343. * @remarks
  5344. *
  5345. * A MongoClient is the entry point to connecting to a MongoDB server.
  5346. *
  5347. * It handles a multitude of features on your application's behalf:
  5348. * - **Server Host Connection Configuration**: A MongoClient is responsible for reading TLS cert, ca, and crl files if provided.
  5349. * - **SRV Record Polling**: A "`mongodb+srv`" style connection string is used to have the MongoClient resolve DNS SRV records of all server hostnames which the driver periodically monitors for changes and adjusts its current view of hosts correspondingly.
  5350. * - **Server Monitoring**: The MongoClient automatically keeps monitoring the health of server nodes in your cluster to reach out to the correct and lowest latency one available.
  5351. * - **Connection Pooling**: To avoid paying the cost of rebuilding a connection to the server on every operation the MongoClient keeps idle connections preserved for reuse.
  5352. * - **Session Pooling**: The MongoClient creates logical sessions that enable retryable writes, causal consistency, and transactions. It handles pooling these sessions for reuse in subsequent operations.
  5353. * - **Cursor Operations**: A MongoClient's cursors use the health monitoring system to send the request for more documents to the same server the query began on.
  5354. * - **Mongocryptd process**: When using auto encryption, a MongoClient will launch a `mongocryptd` instance for handling encryption if the mongocrypt shared library isn't in use.
  5355. *
  5356. * There are many more features of a MongoClient that are not listed above.
  5357. *
  5358. * In order to enable these features, a number of asynchronous Node.js resources are established by the driver: Timers, FS Requests, Sockets, etc.
  5359. * For details on cleanup, please refer to the MongoClient `close()` documentation.
  5360. *
  5361. * @example
  5362. * ```ts
  5363. * import { MongoClient } from 'mongodb';
  5364. * // Enable command monitoring for debugging
  5365. * const client = new MongoClient('mongodb://localhost:27017?appName=mflix', { monitorCommands: true });
  5366. * ```
  5367. */
  5368. export declare class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable {
  5369. /* Excluded from this release type: s */
  5370. /* Excluded from this release type: topology */
  5371. /* Excluded from this release type: mongoLogger */
  5372. /* Excluded from this release type: connectionLock */
  5373. /* Excluded from this release type: closeLock */
  5374. /**
  5375. * The consolidate, parsed, transformed and merged options.
  5376. */
  5377. readonly options: Readonly<Omit<MongoOptions, 'monitorCommands' | 'ca' | 'crl' | 'key' | 'cert' | 'driverInfo'>> & Pick<MongoOptions, 'monitorCommands' | 'ca' | 'crl' | 'key' | 'cert' | 'driverInfo'> & {
  5378. /* Excluded from this release type: metadata */
  5379. };
  5380. private driverInfoList;
  5381. constructor(url: string, options?: MongoClientOptions);
  5382. /**
  5383. * @experimental
  5384. * An alias for {@link MongoClient.close|MongoClient.close()}.
  5385. */
  5386. [Symbol.asyncDispose](): Promise<void>;
  5387. /**
  5388. * Append metadata to the client metadata after instantiation.
  5389. * @param driverInfo - Information about the application or library.
  5390. */
  5391. appendMetadata(driverInfo: DriverInfo): void;
  5392. /* Excluded from this release type: checkForNonGenuineHosts */
  5393. get serverApi(): Readonly<ServerApi | undefined>;
  5394. /* Excluded from this release type: monitorCommands */
  5395. /* Excluded from this release type: monitorCommands */
  5396. /* Excluded from this release type: autoEncrypter */
  5397. get readConcern(): ReadConcern | undefined;
  5398. get writeConcern(): WriteConcern | undefined;
  5399. get readPreference(): ReadPreference;
  5400. get bsonOptions(): BSONSerializeOptions;
  5401. get timeoutMS(): number | undefined;
  5402. /**
  5403. * Executes a client bulk write operation, available on server 8.0+.
  5404. * @param models - The client bulk write models.
  5405. * @param options - The client bulk write options.
  5406. * @returns A ClientBulkWriteResult for acknowledged writes and ok: 1 for unacknowledged writes.
  5407. */
  5408. bulkWrite<SchemaMap extends Record<string, Document> = Record<string, Document>>(models: ReadonlyArray<ClientBulkWriteModel<SchemaMap>>, options?: ClientBulkWriteOptions): Promise<ClientBulkWriteResult>;
  5409. /**
  5410. * An optional method to verify a handful of assumptions that are generally useful at application boot-time before using a MongoClient.
  5411. * For detailed information about the connect process see the MongoClient.connect static method documentation.
  5412. *
  5413. * @param url - The MongoDB connection string (supports `mongodb://` and `mongodb+srv://` schemes)
  5414. * @param options - Optional configuration options for the client
  5415. *
  5416. * @see https://www.mongodb.com/docs/manual/reference/connection-string/
  5417. */
  5418. connect(): Promise<this>;
  5419. /* Excluded from this release type: _connect */
  5420. /**
  5421. * Cleans up resources managed by the MongoClient.
  5422. *
  5423. * The close method clears and closes all resources whose lifetimes are managed by the MongoClient.
  5424. * Please refer to the `MongoClient` class documentation for a high level overview of the client's key features and responsibilities.
  5425. *
  5426. * **However,** the close method does not handle the cleanup of resources explicitly created by the user.
  5427. * Any user-created driver resource with its own `close()` method should be explicitly closed by the user before calling MongoClient.close().
  5428. * This method is written as a "best effort" attempt to leave behind the least amount of resources server-side when possible.
  5429. *
  5430. * The following list defines ideal preconditions and consequent pitfalls if they are not met.
  5431. * The MongoClient, ClientSession, Cursors and ChangeStreams all support [explicit resource management](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-2.html).
  5432. * By using explicit resource management to manage the lifetime of driver resources instead of manually managing their lifetimes, the pitfalls outlined below can be avoided.
  5433. *
  5434. * The close method performs the following in the order listed:
  5435. * - Client-side:
  5436. * - **Close in-use connections**: Any connections that are currently waiting on a response from the server will be closed.
  5437. * This is performed _first_ to avoid reaching the next step (server-side clean up) and having no available connections to check out.
  5438. * - _Ideal_: All operations have been awaited or cancelled, and the outcomes, regardless of success or failure, have been processed before closing the client servicing the operation.
  5439. * - _Pitfall_: When `client.close()` is called and all connections are in use, after closing them, the client must create new connections for cleanup operations, which comes at the cost of new TLS/TCP handshakes and authentication steps.
  5440. * - Server-side:
  5441. * - **Close active cursors**: All cursors that haven't been completed will have a `killCursor` operation sent to the server they were initialized on, freeing the server-side resource.
  5442. * - _Ideal_: Cursors are explicitly closed or completed before `client.close()` is called.
  5443. * - _Pitfall_: `killCursors` may have to build a new connection if the in-use closure ended all pooled connections.
  5444. * - **End active sessions**: In-use sessions created with `client.startSession()` or `client.withSession()` or implicitly by the driver will have their `.endSession()` method called.
  5445. * Contrary to the name of the method, `endSession()` returns the session to the client's pool of sessions rather than end them on the server.
  5446. * - _Ideal_: Transaction outcomes are awaited and their corresponding explicit sessions are ended before `client.close()` is called.
  5447. * - _Pitfall_: **This step aborts in-progress transactions**. It is advisable to observe the outcome of a transaction before closing your client.
  5448. * - **End all pooled sessions**: The `endSessions` command with all session IDs the client has pooled is sent to the server to inform the cluster it can clean them up.
  5449. * - _Ideal_: No user intervention is expected.
  5450. * - _Pitfall_: None.
  5451. *
  5452. * The remaining shutdown is of the MongoClient resources that are intended to be entirely internal but is documented here as their existence relates to the JS event loop.
  5453. *
  5454. * - Client-side (again):
  5455. * - **Stop all server monitoring**: Connections kept live for detecting cluster changes and roundtrip time measurements are shutdown.
  5456. * - **Close all pooled connections**: Each server node in the cluster has a corresponding connection pool and all connections in the pool are closed. Any operations waiting to check out a connection will have an error thrown instead of a connection returned.
  5457. * - **Clear out server selection queue**: Any operations that are in the process of waiting for a server to be selected will have an error thrown instead of a server returned.
  5458. * - **Close encryption-related resources**: An internal MongoClient created for communicating with `mongocryptd` or other encryption purposes is closed. (Using this same method of course!)
  5459. *
  5460. * After the close method completes there should be no MongoClient related resources [ref-ed in Node.js' event loop](https://docs.libuv.org/en/v1.x/handle.html#reference-counting).
  5461. * This should allow Node.js to exit gracefully if MongoClient resources were the only active handles in the event loop.
  5462. *
  5463. * @param _force - currently an unused flag that has no effect. Defaults to `false`.
  5464. */
  5465. close(_force?: boolean): Promise<void>;
  5466. private _close;
  5467. /**
  5468. * Create a new Db instance sharing the current socket connections.
  5469. *
  5470. * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
  5471. * @param options - Optional settings for Db construction
  5472. */
  5473. db(dbName?: string, options?: DbOptions): Db;
  5474. /**
  5475. * Creates a new MongoClient instance and immediately connects it to MongoDB.
  5476. * This convenience method combines `new MongoClient(url, options)` and `client.connect()` in a single step.
  5477. *
  5478. * Connect can be helpful to detect configuration issues early by validating:
  5479. * - **DNS Resolution**: Verifies that SRV records and hostnames in the connection string resolve DNS entries
  5480. * - **Network Connectivity**: Confirms that host addresses are reachable and ports are open
  5481. * - **TLS Configuration**: Validates SSL/TLS certificates, CA files, and encryption settings are correct
  5482. * - **Authentication**: Verifies that provided credentials are valid
  5483. * - **Server Compatibility**: Ensures the MongoDB server version is supported by this driver version
  5484. * - **Load Balancer Setup**: For load-balanced deployments, confirms the service is properly configured
  5485. *
  5486. * @returns A promise that resolves to the same MongoClient instance once connected
  5487. *
  5488. * @remarks
  5489. * **Connection is Optional:** Calling `connect` is optional since any operation method (`find`, `insertOne`, etc.)
  5490. * will automatically perform these same validation steps if the client is not already connected.
  5491. * However, explicitly calling `connect` can make sense for:
  5492. * - **Fail-fast Error Detection**: Non-transient connection issues (hostname unresolved, port refused connection) are discovered immediately rather than during your first operation
  5493. * - **Predictable Performance**: Eliminates first connection overhead from your first database operation
  5494. *
  5495. * @remarks
  5496. * **Connection Pooling Impact:** Calling `connect` will populate the connection pool with one connection
  5497. * to a server selected by the client's configured `readPreference` (defaults to primary).
  5498. *
  5499. * @remarks
  5500. * **Timeout Behavior:** When using `timeoutMS`, the connection establishment time does not count against
  5501. * the timeout for subsequent operations. This means `connect` runs without a `timeoutMS` limit, while
  5502. * your database operations will still respect the configured timeout. If you need predictable operation
  5503. * timing with `timeoutMS`, call `connect` explicitly before performing operations.
  5504. *
  5505. * @see https://www.mongodb.com/docs/manual/reference/connection-string/
  5506. */
  5507. static connect(url: string, options?: MongoClientOptions): Promise<MongoClient>;
  5508. /**
  5509. * Creates a new ClientSession. When using the returned session in an operation
  5510. * a corresponding ServerSession will be created.
  5511. *
  5512. * @remarks
  5513. * A ClientSession instance may only be passed to operations being performed on the same
  5514. * MongoClient it was started from.
  5515. */
  5516. startSession(options?: ClientSessionOptions): ClientSession;
  5517. /**
  5518. * A convenience method for creating and handling the clean up of a ClientSession.
  5519. * The session will always be ended when the executor finishes.
  5520. *
  5521. * @param executor - An executor function that all operations using the provided session must be invoked in
  5522. * @param options - optional settings for the session
  5523. */
  5524. withSession<T = any>(executor: WithSessionCallback<T>): Promise<T>;
  5525. withSession<T = any>(options: ClientSessionOptions, executor: WithSessionCallback<T>): Promise<T>;
  5526. /**
  5527. * Create a new Change Stream, watching for new changes (insertions, updates,
  5528. * replacements, deletions, and invalidations) in this cluster. Will ignore all
  5529. * changes to system collections, as well as the local, admin, and config databases.
  5530. *
  5531. * @remarks
  5532. * watch() accepts two generic arguments for distinct use cases:
  5533. * - The first is to provide the schema that may be defined for all the data within the current cluster
  5534. * - 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
  5535. *
  5536. * @remarks
  5537. * When `timeoutMS` is configured for a change stream, it will have different behaviour depending
  5538. * on whether the change stream is in iterator mode or emitter mode. In both cases, a change
  5539. * stream will time out if it does not receive a change event within `timeoutMS` of the last change
  5540. * event.
  5541. *
  5542. * Note that if a change stream is consistently timing out when watching a collection, database or
  5543. * client that is being changed, then this may be due to the server timing out before it can finish
  5544. * processing the existing oplog. To address this, restart the change stream with a higher
  5545. * `timeoutMS`.
  5546. *
  5547. * If the change stream times out the initial aggregate operation to establish the change stream on
  5548. * the server, then the client will close the change stream. If the getMore calls to the server
  5549. * time out, then the change stream will be left open, but will throw a MongoOperationTimeoutError
  5550. * when in iterator mode and emit an error event that returns a MongoOperationTimeoutError in
  5551. * emitter mode.
  5552. *
  5553. * To determine whether or not the change stream is still open following a timeout, check the
  5554. * {@link ChangeStream.closed} getter.
  5555. *
  5556. * @example
  5557. * In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream.
  5558. * The next call can just be retried after this succeeds.
  5559. * ```ts
  5560. * const changeStream = collection.watch([], { timeoutMS: 100 });
  5561. * try {
  5562. * await changeStream.next();
  5563. * } catch (e) {
  5564. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  5565. * await changeStream.next();
  5566. * }
  5567. * throw e;
  5568. * }
  5569. * ```
  5570. *
  5571. * @example
  5572. * In emitter mode, if the change stream goes `timeoutMS` without emitting a change event, it will
  5573. * emit an error event that returns a MongoOperationTimeoutError, but will not close the change
  5574. * stream unless the resume attempt fails. There is no need to re-establish change listeners as
  5575. * this will automatically continue emitting change events once the resume attempt completes.
  5576. *
  5577. * ```ts
  5578. * const changeStream = collection.watch([], { timeoutMS: 100 });
  5579. * changeStream.on('change', console.log);
  5580. * changeStream.on('error', e => {
  5581. * if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
  5582. * // do nothing
  5583. * } else {
  5584. * changeStream.close();
  5585. * }
  5586. * });
  5587. * ```
  5588. * @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.
  5589. * @param options - Optional settings for the command
  5590. * @typeParam TSchema - Type of the data being detected by the change stream
  5591. * @typeParam TChange - Type of the whole change stream document emitted
  5592. */
  5593. watch<TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>>(pipeline?: Document[], options?: ChangeStreamOptions): ChangeStream<TSchema, TChange>;
  5594. }
  5595. /* Excluded from this release type: MongoClientAuthProviders */
  5596. /**
  5597. * An error indicating that an error occurred when processing bulk write results.
  5598. *
  5599. * @public
  5600. * @category Error
  5601. */
  5602. export declare class MongoClientBulkWriteCursorError extends MongoRuntimeError {
  5603. /**
  5604. * **Do not use this constructor!**
  5605. *
  5606. * Meant for internal use only.
  5607. *
  5608. * @remarks
  5609. * This class is only meant to be constructed within the driver. This constructor is
  5610. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5611. *
  5612. * @public
  5613. **/
  5614. constructor(message: string);
  5615. get name(): string;
  5616. }
  5617. /**
  5618. * An error indicating that an error occurred when executing the bulk write.
  5619. *
  5620. * @public
  5621. * @category Error
  5622. */
  5623. export declare class MongoClientBulkWriteError extends MongoServerError {
  5624. /**
  5625. * Write concern errors that occurred while executing the bulk write. This list may have
  5626. * multiple items if more than one server command was required to execute the bulk write.
  5627. */
  5628. writeConcernErrors: Document[];
  5629. /**
  5630. * Errors that occurred during the execution of individual write operations. This map will
  5631. * contain at most one entry if the bulk write was ordered.
  5632. */
  5633. writeErrors: Map<number, ClientBulkWriteError>;
  5634. /**
  5635. * The results of any successful operations that were performed before the error was
  5636. * encountered.
  5637. */
  5638. partialResult?: ClientBulkWriteResult;
  5639. /**
  5640. * Initialize the client bulk write error.
  5641. * @param message - The error message.
  5642. */
  5643. constructor(message: ErrorDescription);
  5644. get name(): string;
  5645. }
  5646. /**
  5647. * An error indicating that an error occurred on the client when executing a client bulk write.
  5648. *
  5649. * @public
  5650. * @category Error
  5651. */
  5652. export declare class MongoClientBulkWriteExecutionError extends MongoRuntimeError {
  5653. /**
  5654. * **Do not use this constructor!**
  5655. *
  5656. * Meant for internal use only.
  5657. *
  5658. * @remarks
  5659. * This class is only meant to be constructed within the driver. This constructor is
  5660. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5661. *
  5662. * @public
  5663. **/
  5664. constructor(message: string);
  5665. get name(): string;
  5666. }
  5667. /**
  5668. * An error generated when the MongoClient is closed and async
  5669. * operations are interrupted.
  5670. *
  5671. * @public
  5672. * @category Error
  5673. */
  5674. export declare class MongoClientClosedError extends MongoAPIError {
  5675. /**
  5676. * **Do not use this constructor!**
  5677. *
  5678. * Meant for internal use only.
  5679. *
  5680. * @remarks
  5681. * This class is only meant to be constructed within the driver. This constructor is
  5682. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5683. *
  5684. * @public
  5685. **/
  5686. constructor();
  5687. get name(): string;
  5688. }
  5689. /** @public */
  5690. export declare type MongoClientEvents = Pick<TopologyEvents, (typeof MONGO_CLIENT_EVENTS)[number]> & {
  5691. open(mongoClient: MongoClient): void;
  5692. };
  5693. /**
  5694. * Describes all possible URI query options for the mongo client
  5695. * @public
  5696. * @see https://www.mongodb.com/docs/manual/reference/connection-string
  5697. */
  5698. export declare interface MongoClientOptions extends BSONSerializeOptions, SupportedNodeConnectionOptions {
  5699. /** Specifies the name of the replica set, if the mongod is a member of a replica set. */
  5700. replicaSet?: string;
  5701. /**
  5702. * @experimental
  5703. * Specifies the time an operation will run until it throws a timeout error
  5704. */
  5705. timeoutMS?: number;
  5706. /** Enables or disables TLS/SSL for the connection. */
  5707. tls?: boolean;
  5708. /** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
  5709. ssl?: boolean;
  5710. /** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key. */
  5711. tlsCertificateKeyFile?: string;
  5712. /** Specifies the password to de-crypt the tlsCertificateKeyFile. */
  5713. tlsCertificateKeyFilePassword?: string;
  5714. /** 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. */
  5715. tlsCAFile?: string;
  5716. /** Specifies the location of a local CRL .pem file that contains the client revokation list. */
  5717. tlsCRLFile?: string;
  5718. /** Bypasses validation of the certificates presented by the mongod/mongos instance */
  5719. tlsAllowInvalidCertificates?: boolean;
  5720. /** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
  5721. tlsAllowInvalidHostnames?: boolean;
  5722. /** Disables various certificate validations. */
  5723. tlsInsecure?: boolean;
  5724. /** The time in milliseconds to attempt a connection before timing out. */
  5725. connectTimeoutMS?: number;
  5726. /** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
  5727. socketTimeoutMS?: number;
  5728. /** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
  5729. compressors?: CompressorName[] | string;
  5730. /** An integer that specifies the compression level if using zlib for network compression. */
  5731. zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
  5732. /** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
  5733. srvMaxHosts?: number;
  5734. /**
  5735. * Modifies the srv URI to look like:
  5736. *
  5737. * `_{srvServiceName}._tcp.{hostname}.{domainname}`
  5738. *
  5739. * Querying this DNS URI is expected to respond with SRV records
  5740. */
  5741. srvServiceName?: string;
  5742. /** The maximum number of connections in the connection pool. */
  5743. maxPoolSize?: number;
  5744. /** The minimum number of connections in the connection pool. */
  5745. minPoolSize?: number;
  5746. /** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
  5747. maxConnecting?: number;
  5748. /**
  5749. * The maximum amount of time a connection should remain idle in the connection pool before being marked idle, in milliseconds.
  5750. * If specified, this must be a number greater than or equal to 0, where 0 means there is no limit. Defaults to 0. After this
  5751. * time passes, the idle collection can be automatically cleaned up in the background.
  5752. */
  5753. maxIdleTimeMS?: number;
  5754. /** The maximum time in milliseconds that a thread can wait for a connection to become available. */
  5755. waitQueueTimeoutMS?: number;
  5756. /** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
  5757. readConcern?: ReadConcernLike;
  5758. /** The level of isolation */
  5759. readConcernLevel?: ReadConcernLevel;
  5760. /** Specifies the read preferences for this connection */
  5761. readPreference?: ReadPreferenceMode | ReadPreference;
  5762. /** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
  5763. maxStalenessSeconds?: number;
  5764. /** Specifies the tags document as a comma-separated list of colon-separated key-value pairs. */
  5765. readPreferenceTags?: TagSet[];
  5766. /** The auth settings for when connection to server. */
  5767. auth?: Auth;
  5768. /** Specify the database name associated with the user’s credentials. */
  5769. authSource?: string;
  5770. /** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
  5771. authMechanism?: AuthMechanism;
  5772. /** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
  5773. authMechanismProperties?: AuthMechanismProperties;
  5774. /** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
  5775. localThresholdMS?: number;
  5776. /** Specifies how long (in milliseconds) to block for server selection before throwing an exception. */
  5777. serverSelectionTimeoutMS?: number;
  5778. /** 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. */
  5779. heartbeatFrequencyMS?: number;
  5780. /** 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. */
  5781. minHeartbeatFrequencyMS?: number;
  5782. /** 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 */
  5783. appName?: string;
  5784. /** Enables retryable reads. */
  5785. retryReads?: boolean;
  5786. /** Enable retryable writes. */
  5787. retryWrites?: boolean;
  5788. /** Allow a driver to force a Single topology type with a connection string containing one host */
  5789. directConnection?: boolean;
  5790. /** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
  5791. loadBalanced?: boolean;
  5792. /**
  5793. * The write concern w value
  5794. * @deprecated Please use the `writeConcern` option instead
  5795. */
  5796. w?: W;
  5797. /**
  5798. * The write concern timeout
  5799. * @deprecated Please use the `writeConcern` option instead
  5800. */
  5801. wtimeoutMS?: number;
  5802. /**
  5803. * The journal write concern
  5804. * @deprecated Please use the `writeConcern` option instead
  5805. */
  5806. journal?: boolean;
  5807. /**
  5808. * A MongoDB WriteConcern, which describes the level of acknowledgement
  5809. * requested from MongoDB for write operations.
  5810. *
  5811. * @see https://www.mongodb.com/docs/manual/reference/write-concern/
  5812. */
  5813. writeConcern?: WriteConcern | WriteConcernSettings;
  5814. /** TCP Connection no delay */
  5815. noDelay?: boolean;
  5816. /** Force server to assign `_id` values instead of driver */
  5817. forceServerObjectId?: boolean;
  5818. /** A primary key factory function for generation of custom `_id` keys */
  5819. pkFactory?: PkFactory;
  5820. /** Enable command monitoring for this client */
  5821. monitorCommands?: boolean;
  5822. /** Server API version */
  5823. serverApi?: ServerApi | ServerApiVersion;
  5824. /**
  5825. * Optionally enable in-use auto encryption
  5826. *
  5827. * @remarks
  5828. * 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
  5829. * (see [libmongocrypt: Auto Encryption Allow-List](https://github.com/mongodb/specifications/blob/master/source/client-side-encryption/client-side-encryption.md#libmongocrypt-auto-encryption-allow-list)). To bypass automatic encryption for all operations, set bypassAutoEncryption=true in AutoEncryptionOpts.
  5830. *
  5831. * Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
  5832. *
  5833. * 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:
  5834. * - AutoEncryptionOptions.keyVaultClient is not passed.
  5835. * - AutoEncryptionOptions.bypassAutomaticEncryption is false.
  5836. *
  5837. * 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.
  5838. */
  5839. autoEncryption?: AutoEncryptionOptions;
  5840. /**
  5841. * Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver
  5842. /* @deprecated - Will be made internal in a future major release.
  5843. */
  5844. driverInfo?: DriverInfo;
  5845. /** Configures a Socks5 proxy host used for creating TCP connections. */
  5846. proxyHost?: string;
  5847. /** Configures a Socks5 proxy port used for creating TCP connections. */
  5848. proxyPort?: number;
  5849. /** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
  5850. proxyUsername?: string;
  5851. /** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
  5852. proxyPassword?: string;
  5853. /** Instructs the driver monitors to use a specific monitoring mode */
  5854. serverMonitoringMode?: ServerMonitoringMode;
  5855. /**
  5856. * @public
  5857. * Specifies the destination of the driver's logging. The default is stderr.
  5858. */
  5859. mongodbLogPath?: 'stderr' | 'stdout' | MongoDBLogWritable;
  5860. /**
  5861. * @public
  5862. * Enable logging level per component or use `default` to control any unset components.
  5863. */
  5864. mongodbLogComponentSeverities?: LogComponentSeveritiesClientOptions;
  5865. /**
  5866. * @public
  5867. * All BSON documents are stringified to EJSON. This controls the maximum length of those strings.
  5868. * It is defaulted to 1000.
  5869. */
  5870. mongodbLogMaxDocumentLength?: number;
  5871. /* Excluded from this release type: srvPoller */
  5872. /* Excluded from this release type: connectionType */
  5873. /* Excluded from this release type: __skipPingOnConnect */
  5874. }
  5875. /* Excluded from this release type: MongoClientPrivate */
  5876. /**
  5877. * An error generated when a feature that is not enabled or allowed for the current server
  5878. * configuration is used
  5879. *
  5880. *
  5881. * @public
  5882. * @category Error
  5883. */
  5884. export declare class MongoCompatibilityError extends MongoAPIError {
  5885. /**
  5886. * **Do not use this constructor!**
  5887. *
  5888. * Meant for internal use only.
  5889. *
  5890. * @remarks
  5891. * This class is only meant to be constructed within the driver. This constructor is
  5892. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5893. *
  5894. * @public
  5895. **/
  5896. constructor(message: string);
  5897. get name(): string;
  5898. }
  5899. /**
  5900. * A representation of the credentials used by MongoDB
  5901. * @public
  5902. */
  5903. export declare class MongoCredentials {
  5904. /** The username used for authentication */
  5905. readonly username: string;
  5906. /** The password used for authentication */
  5907. readonly password: string;
  5908. /** The database that the user should authenticate against */
  5909. readonly source: string;
  5910. /** The method used to authenticate */
  5911. readonly mechanism: AuthMechanism;
  5912. /** Special properties used by some types of auth mechanisms */
  5913. readonly mechanismProperties: AuthMechanismProperties;
  5914. constructor(options: MongoCredentialsOptions);
  5915. /** Determines if two MongoCredentials objects are equivalent */
  5916. equals(other: MongoCredentials): boolean;
  5917. /**
  5918. * If the authentication mechanism is set to "default", resolves the authMechanism
  5919. * based on the server version and server supported sasl mechanisms.
  5920. *
  5921. * @param hello - A hello response from the server
  5922. */
  5923. resolveAuthMechanism(hello: Document | null): MongoCredentials;
  5924. validate(): void;
  5925. static merge(creds: MongoCredentials | undefined, options: Partial<MongoCredentialsOptions>): MongoCredentials;
  5926. }
  5927. /** @public */
  5928. export declare interface MongoCredentialsOptions {
  5929. username?: string;
  5930. password: string;
  5931. source: string;
  5932. db?: string;
  5933. mechanism?: AuthMechanism;
  5934. mechanismProperties: AuthMechanismProperties;
  5935. }
  5936. /**
  5937. * @public
  5938. * An error indicating that mongodb-client-encryption failed to auto-refresh Azure KMS credentials.
  5939. */
  5940. export declare class MongoCryptAzureKMSRequestError extends MongoCryptError {
  5941. /** The body of the http response that failed, if present. */
  5942. body?: Document;
  5943. /**
  5944. * **Do not use this constructor!**
  5945. *
  5946. * Meant for internal use only.
  5947. *
  5948. * @remarks
  5949. * This class is only meant to be constructed within the driver. This constructor is
  5950. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5951. *
  5952. * @public
  5953. **/
  5954. constructor(message: string, body?: Document);
  5955. get name(): string;
  5956. }
  5957. /**
  5958. * @public
  5959. * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create data keys
  5960. */
  5961. export declare class MongoCryptCreateDataKeyError extends MongoCryptError {
  5962. encryptedFields: Document;
  5963. /**
  5964. * **Do not use this constructor!**
  5965. *
  5966. * Meant for internal use only.
  5967. *
  5968. * @remarks
  5969. * This class is only meant to be constructed within the driver. This constructor is
  5970. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5971. *
  5972. * @public
  5973. **/
  5974. constructor(encryptedFields: Document, { cause }: {
  5975. cause: Error;
  5976. });
  5977. get name(): string;
  5978. }
  5979. /**
  5980. * @public
  5981. * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create a collection
  5982. */
  5983. export declare class MongoCryptCreateEncryptedCollectionError extends MongoCryptError {
  5984. encryptedFields: Document;
  5985. /**
  5986. * **Do not use this constructor!**
  5987. *
  5988. * Meant for internal use only.
  5989. *
  5990. * @remarks
  5991. * This class is only meant to be constructed within the driver. This constructor is
  5992. * not subject to semantic versioning compatibility guarantees and may change at any time.
  5993. *
  5994. * @public
  5995. **/
  5996. constructor(encryptedFields: Document, { cause }: {
  5997. cause: Error;
  5998. });
  5999. get name(): string;
  6000. }
  6001. /* Excluded from this release type: MongocryptdManager */
  6002. /**
  6003. * @public
  6004. * An error indicating that something went wrong specifically with MongoDB Client Encryption
  6005. */
  6006. export declare class MongoCryptError extends MongoError {
  6007. /**
  6008. * **Do not use this constructor!**
  6009. *
  6010. * Meant for internal use only.
  6011. *
  6012. * @remarks
  6013. * This class is only meant to be constructed within the driver. This constructor is
  6014. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6015. *
  6016. * @public
  6017. **/
  6018. constructor(message: string, options?: {
  6019. cause?: Error;
  6020. });
  6021. get name(): string;
  6022. }
  6023. /**
  6024. * @public
  6025. *
  6026. * An error indicating an invalid argument was provided to an encryption API.
  6027. */
  6028. export declare class MongoCryptInvalidArgumentError extends MongoCryptError {
  6029. /**
  6030. * **Do not use this constructor!**
  6031. *
  6032. * Meant for internal use only.
  6033. *
  6034. * @remarks
  6035. * This class is only meant to be constructed within the driver. This constructor is
  6036. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6037. *
  6038. * @public
  6039. **/
  6040. constructor(message: string);
  6041. get name(): string;
  6042. }
  6043. /** @public */
  6044. export declare class MongoCryptKMSRequestNetworkTimeoutError extends MongoCryptError {
  6045. get name(): string;
  6046. }
  6047. /**
  6048. * An error thrown when an attempt is made to read from a cursor that has been exhausted
  6049. *
  6050. * @public
  6051. * @category Error
  6052. */
  6053. export declare class MongoCursorExhaustedError extends MongoAPIError {
  6054. /**
  6055. * **Do not use this constructor!**
  6056. *
  6057. * Meant for internal use only.
  6058. *
  6059. * @remarks
  6060. * This class is only meant to be constructed within the driver. This constructor is
  6061. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6062. *
  6063. * @public
  6064. **/
  6065. constructor(message?: string);
  6066. get name(): string;
  6067. }
  6068. /**
  6069. * An error thrown when the user attempts to add options to a cursor that has already been
  6070. * initialized
  6071. *
  6072. * @public
  6073. * @category Error
  6074. */
  6075. export declare class MongoCursorInUseError extends MongoAPIError {
  6076. /**
  6077. * **Do not use this constructor!**
  6078. *
  6079. * Meant for internal use only.
  6080. *
  6081. * @remarks
  6082. * This class is only meant to be constructed within the driver. This constructor is
  6083. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6084. *
  6085. * @public
  6086. **/
  6087. constructor(message?: string);
  6088. get name(): string;
  6089. }
  6090. /**
  6091. * @public
  6092. *
  6093. * A class representing a collection's namespace. This class enforces (through Typescript) that
  6094. * the `collection` portion of the namespace is defined and should only be
  6095. * used in scenarios where this can be guaranteed.
  6096. */
  6097. export declare class MongoDBCollectionNamespace extends MongoDBNamespace {
  6098. collection: string;
  6099. constructor(db: string, collection: string);
  6100. static fromString(namespace?: string): MongoDBCollectionNamespace;
  6101. }
  6102. /**
  6103. * @public
  6104. *
  6105. * A custom destination for structured logging messages.
  6106. */
  6107. export declare interface MongoDBLogWritable {
  6108. /**
  6109. * This function will be called for every enabled log message.
  6110. *
  6111. * It can be sync or async:
  6112. * - If it is synchronous it will block the driver from proceeding until this method returns.
  6113. * - If it is asynchronous the driver will not await the returned promise. It will attach fulfillment handling (`.then`).
  6114. * If the promise rejects the logger will write an error message to stderr and stop functioning.
  6115. * If the promise resolves the driver proceeds to the next log message (or waits for new ones to occur).
  6116. *
  6117. * Tips:
  6118. * - We recommend writing an async `write` function that _never_ rejects.
  6119. * Instead handle logging errors as necessary to your use case and make the write function a noop, until it can be recovered.
  6120. * - The Log messages are structured but **subject to change** since the intended purpose is informational.
  6121. * Program against this defensively and err on the side of stringifying whatever is passed in to write in some form or another.
  6122. *
  6123. */
  6124. write(log: Log): PromiseLike<unknown> | unknown;
  6125. }
  6126. /** @public */
  6127. export declare class MongoDBNamespace {
  6128. db: string;
  6129. collection?: string;
  6130. /**
  6131. * Create a namespace object
  6132. *
  6133. * @param db - database name
  6134. * @param collection - collection name
  6135. */
  6136. constructor(db: string, collection?: string);
  6137. toString(): string;
  6138. withCollection(collection: string): MongoDBCollectionNamespace;
  6139. static fromString(namespace?: string): MongoDBNamespace;
  6140. }
  6141. /* Excluded from this release type: MongoDBResponse */
  6142. /* Excluded from this release type: MongoDBResponseConstructor */
  6143. /**
  6144. * An error generated when the driver fails to decompress
  6145. * data received from the server.
  6146. *
  6147. * @public
  6148. * @category Error
  6149. */
  6150. export declare class MongoDecompressionError extends MongoRuntimeError {
  6151. /**
  6152. * **Do not use this constructor!**
  6153. *
  6154. * Meant for internal use only.
  6155. *
  6156. * @remarks
  6157. * This class is only meant to be constructed within the driver. This constructor is
  6158. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6159. *
  6160. * @public
  6161. **/
  6162. constructor(message: string);
  6163. get name(): string;
  6164. }
  6165. /**
  6166. * An error generated by the driver
  6167. *
  6168. * @public
  6169. * @category Error
  6170. */
  6171. export declare class MongoDriverError extends MongoError {
  6172. /**
  6173. * **Do not use this constructor!**
  6174. *
  6175. * Meant for internal use only.
  6176. *
  6177. * @remarks
  6178. * This class is only meant to be constructed within the driver. This constructor is
  6179. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6180. *
  6181. * @public
  6182. **/
  6183. constructor(message: string, options?: {
  6184. cause?: Error;
  6185. });
  6186. get name(): string;
  6187. }
  6188. /**
  6189. * @public
  6190. * @category Error
  6191. *
  6192. * @privateRemarks
  6193. * mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument
  6194. */
  6195. export declare class MongoError extends Error {
  6196. /* Excluded from this release type: errorLabelSet */
  6197. get errorLabels(): string[];
  6198. /**
  6199. * This is a number in MongoServerError and a string in MongoDriverError
  6200. * @privateRemarks
  6201. * Define the type override on the subclasses when we can use the override keyword
  6202. */
  6203. code?: number | string;
  6204. topologyVersion?: TopologyVersion;
  6205. connectionGeneration?: number;
  6206. cause?: Error;
  6207. /**
  6208. * **Do not use this constructor!**
  6209. *
  6210. * Meant for internal use only.
  6211. *
  6212. * @remarks
  6213. * This class is only meant to be constructed within the driver. This constructor is
  6214. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6215. *
  6216. * @public
  6217. **/
  6218. constructor(message: string, options?: {
  6219. cause?: Error;
  6220. });
  6221. /* Excluded from this release type: buildErrorMessage */
  6222. get name(): string;
  6223. /** Legacy name for server error responses */
  6224. get errmsg(): string;
  6225. /**
  6226. * Checks the error to see if it has an error label
  6227. *
  6228. * @param label - The error label to check for
  6229. * @returns returns true if the error has the provided error label
  6230. */
  6231. hasErrorLabel(label: string): boolean;
  6232. addErrorLabel(label: string): void;
  6233. }
  6234. /** @public */
  6235. export declare const MongoErrorLabel: Readonly<{
  6236. readonly RetryableWriteError: "RetryableWriteError";
  6237. readonly TransientTransactionError: "TransientTransactionError";
  6238. readonly UnknownTransactionCommitResult: "UnknownTransactionCommitResult";
  6239. readonly ResumableChangeStreamError: "ResumableChangeStreamError";
  6240. readonly HandshakeError: "HandshakeError";
  6241. readonly ResetPool: "ResetPool";
  6242. readonly PoolRequestedRetry: "PoolRequestedRetry";
  6243. readonly InterruptInUseConnections: "InterruptInUseConnections";
  6244. readonly NoWritesPerformed: "NoWritesPerformed";
  6245. }>;
  6246. /** @public */
  6247. export declare type MongoErrorLabel = (typeof MongoErrorLabel)[keyof typeof MongoErrorLabel];
  6248. /**
  6249. * An error generated when the user attempts to operate
  6250. * on a session that has expired or has been closed.
  6251. *
  6252. * @public
  6253. * @category Error
  6254. */
  6255. export declare class MongoExpiredSessionError extends MongoAPIError {
  6256. /**
  6257. * **Do not use this constructor!**
  6258. *
  6259. * Meant for internal use only.
  6260. *
  6261. * @remarks
  6262. * This class is only meant to be constructed within the driver. This constructor is
  6263. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6264. *
  6265. * @public
  6266. **/
  6267. constructor(message?: string);
  6268. get name(): string;
  6269. }
  6270. /**
  6271. * A error generated when the user attempts to authenticate
  6272. * via GCP, but fails.
  6273. *
  6274. * @public
  6275. * @category Error
  6276. */
  6277. export declare class MongoGCPError extends MongoOIDCError {
  6278. /**
  6279. * **Do not use this constructor!**
  6280. *
  6281. * Meant for internal use only.
  6282. *
  6283. * @remarks
  6284. * This class is only meant to be constructed within the driver. This constructor is
  6285. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6286. *
  6287. * @public
  6288. **/
  6289. constructor(message: string);
  6290. get name(): string;
  6291. }
  6292. /**
  6293. * An error generated when a malformed or invalid chunk is
  6294. * encountered when reading from a GridFSStream.
  6295. *
  6296. * @public
  6297. * @category Error
  6298. */
  6299. export declare class MongoGridFSChunkError extends MongoRuntimeError {
  6300. /**
  6301. * **Do not use this constructor!**
  6302. *
  6303. * Meant for internal use only.
  6304. *
  6305. * @remarks
  6306. * This class is only meant to be constructed within the driver. This constructor is
  6307. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6308. *
  6309. * @public
  6310. **/
  6311. constructor(message: string);
  6312. get name(): string;
  6313. }
  6314. /** An error generated when a GridFSStream operation fails to execute.
  6315. *
  6316. * @public
  6317. * @category Error
  6318. */
  6319. export declare class MongoGridFSStreamError extends MongoRuntimeError {
  6320. /**
  6321. * **Do not use this constructor!**
  6322. *
  6323. * Meant for internal use only.
  6324. *
  6325. * @remarks
  6326. * This class is only meant to be constructed within the driver. This constructor is
  6327. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6328. *
  6329. * @public
  6330. **/
  6331. constructor(message: string);
  6332. get name(): string;
  6333. }
  6334. /**
  6335. * An error generated when the user supplies malformed or unexpected arguments
  6336. * or when a required argument or field is not provided.
  6337. *
  6338. *
  6339. * @public
  6340. * @category Error
  6341. */
  6342. export declare class MongoInvalidArgumentError extends MongoAPIError {
  6343. /**
  6344. * **Do not use this constructor!**
  6345. *
  6346. * Meant for internal use only.
  6347. *
  6348. * @remarks
  6349. * This class is only meant to be constructed within the driver. This constructor is
  6350. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6351. *
  6352. * @public
  6353. **/
  6354. constructor(message: string, options?: {
  6355. cause?: Error;
  6356. });
  6357. get name(): string;
  6358. }
  6359. /**
  6360. * A error generated when the user attempts to authenticate
  6361. * via Kerberos, but fails to connect to the Kerberos client.
  6362. *
  6363. * @public
  6364. * @category Error
  6365. */
  6366. export declare class MongoKerberosError extends MongoRuntimeError {
  6367. /**
  6368. * **Do not use this constructor!**
  6369. *
  6370. * Meant for internal use only.
  6371. *
  6372. * @remarks
  6373. * This class is only meant to be constructed within the driver. This constructor is
  6374. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6375. *
  6376. * @public
  6377. **/
  6378. constructor(message: string);
  6379. get name(): string;
  6380. }
  6381. /** @public */
  6382. export declare const MongoLoggableComponent: Readonly<{
  6383. readonly COMMAND: "command";
  6384. readonly TOPOLOGY: "topology";
  6385. readonly SERVER_SELECTION: "serverSelection";
  6386. readonly CONNECTION: "connection";
  6387. readonly CLIENT: "client";
  6388. }>;
  6389. /** @public */
  6390. export declare type MongoLoggableComponent = (typeof MongoLoggableComponent)[keyof typeof MongoLoggableComponent];
  6391. /* Excluded from this release type: MongoLogger */
  6392. /* Excluded from this release type: MongoLoggerEnvOptions */
  6393. /* Excluded from this release type: MongoLoggerMongoClientOptions */
  6394. /* Excluded from this release type: MongoLoggerOptions */
  6395. /**
  6396. * An error generated when the user fails to provide authentication credentials before attempting
  6397. * to connect to a mongo server instance.
  6398. *
  6399. *
  6400. * @public
  6401. * @category Error
  6402. */
  6403. export declare class MongoMissingCredentialsError extends MongoAPIError {
  6404. /**
  6405. * **Do not use this constructor!**
  6406. *
  6407. * Meant for internal use only.
  6408. *
  6409. * @remarks
  6410. * This class is only meant to be constructed within the driver. This constructor is
  6411. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6412. *
  6413. * @public
  6414. **/
  6415. constructor(message: string);
  6416. get name(): string;
  6417. }
  6418. /**
  6419. * An error generated when a required module or dependency is not present in the local environment
  6420. *
  6421. * @public
  6422. * @category Error
  6423. */
  6424. export declare class MongoMissingDependencyError extends MongoAPIError {
  6425. dependencyName: string;
  6426. /** @remarks This property is assigned in the `Error` constructor. */
  6427. cause: Error;
  6428. /**
  6429. * **Do not use this constructor!**
  6430. *
  6431. * Meant for internal use only.
  6432. *
  6433. * @remarks
  6434. * This class is only meant to be constructed within the driver. This constructor is
  6435. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6436. *
  6437. * @public
  6438. **/
  6439. constructor(message: string, options: {
  6440. cause: Error;
  6441. dependencyName: string;
  6442. });
  6443. get name(): string;
  6444. }
  6445. /**
  6446. * An error indicating an issue with the network, including TCP errors and timeouts.
  6447. * @public
  6448. * @category Error
  6449. */
  6450. export declare class MongoNetworkError extends MongoError {
  6451. /* Excluded from this release type: beforeHandshake */
  6452. /**
  6453. * **Do not use this constructor!**
  6454. *
  6455. * Meant for internal use only.
  6456. *
  6457. * @remarks
  6458. * This class is only meant to be constructed within the driver. This constructor is
  6459. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6460. *
  6461. * @public
  6462. **/
  6463. constructor(message: string, options?: MongoNetworkErrorOptions);
  6464. get name(): string;
  6465. }
  6466. /** @public */
  6467. export declare interface MongoNetworkErrorOptions {
  6468. /** Indicates the timeout happened before a connection handshake completed */
  6469. beforeHandshake?: boolean;
  6470. cause?: Error;
  6471. }
  6472. /**
  6473. * An error indicating a network timeout occurred
  6474. * @public
  6475. * @category Error
  6476. *
  6477. * @privateRemarks
  6478. * mongodb-client-encryption has a dependency on this error with an instanceof check
  6479. */
  6480. export declare class MongoNetworkTimeoutError extends MongoNetworkError {
  6481. /**
  6482. * **Do not use this constructor!**
  6483. *
  6484. * Meant for internal use only.
  6485. *
  6486. * @remarks
  6487. * This class is only meant to be constructed within the driver. This constructor is
  6488. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6489. *
  6490. * @public
  6491. **/
  6492. constructor(message: string, options?: MongoNetworkErrorOptions);
  6493. get name(): string;
  6494. }
  6495. /**
  6496. * An error thrown when the user attempts to operate on a database or collection through a MongoClient
  6497. * that has not yet successfully called the "connect" method
  6498. *
  6499. * @public
  6500. * @category Error
  6501. */
  6502. export declare class MongoNotConnectedError extends MongoAPIError {
  6503. /**
  6504. * **Do not use this constructor!**
  6505. *
  6506. * Meant for internal use only.
  6507. *
  6508. * @remarks
  6509. * This class is only meant to be constructed within the driver. This constructor is
  6510. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6511. *
  6512. * @public
  6513. **/
  6514. constructor(message: string);
  6515. get name(): string;
  6516. }
  6517. /**
  6518. * A error generated when the user attempts to authenticate
  6519. * via OIDC callbacks, but fails.
  6520. *
  6521. * @public
  6522. * @category Error
  6523. */
  6524. export declare class MongoOIDCError extends MongoRuntimeError {
  6525. /**
  6526. * **Do not use this constructor!**
  6527. *
  6528. * Meant for internal use only.
  6529. *
  6530. * @remarks
  6531. * This class is only meant to be constructed within the driver. This constructor is
  6532. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6533. *
  6534. * @public
  6535. **/
  6536. constructor(message: string);
  6537. get name(): string;
  6538. }
  6539. /**
  6540. * @public
  6541. * @category Error
  6542. *
  6543. * The `MongoOperationTimeoutError` class represents an error that occurs when an operation could not be completed within the specified `timeoutMS`.
  6544. * It is generated by the driver in support of the "client side operation timeout" feature so inherits from `MongoDriverError`.
  6545. * When `timeoutMS` is enabled `MongoServerError`s relating to `MaxTimeExpired` errors will be converted to `MongoOperationTimeoutError`
  6546. *
  6547. * @example
  6548. * ```ts
  6549. * try {
  6550. * await blogs.insertOne(blogPost, { timeoutMS: 60_000 })
  6551. * } catch (error) {
  6552. * if (error instanceof MongoOperationTimeoutError) {
  6553. * console.log(`Oh no! writer's block!`, error);
  6554. * }
  6555. * }
  6556. * ```
  6557. */
  6558. export declare class MongoOperationTimeoutError extends MongoDriverError {
  6559. get name(): string;
  6560. }
  6561. /**
  6562. * Parsed Mongo Client Options.
  6563. *
  6564. * User supplied options are documented by `MongoClientOptions`.
  6565. *
  6566. * **NOTE:** The client's options parsing is subject to change to support new features.
  6567. * This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically.
  6568. *
  6569. * Options are sourced from:
  6570. * - connection string
  6571. * - options object passed to the MongoClient constructor
  6572. * - file system (ex. tls settings)
  6573. * - environment variables
  6574. * - DNS SRV records and TXT records
  6575. *
  6576. * Not all options may be present after client construction as some are obtained from asynchronous operations.
  6577. *
  6578. * @public
  6579. */
  6580. export declare interface MongoOptions extends Required<Pick<MongoClientOptions, 'autoEncryption' | 'connectTimeoutMS' | 'directConnection' | 'driverInfo' | 'forceServerObjectId' | 'minHeartbeatFrequencyMS' | 'heartbeatFrequencyMS' | 'localThresholdMS' | 'maxConnecting' | 'maxIdleTimeMS' | 'maxPoolSize' | 'minPoolSize' | 'monitorCommands' | 'noDelay' | 'pkFactory' | 'raw' | 'replicaSet' | 'retryReads' | 'retryWrites' | 'serverSelectionTimeoutMS' | 'socketTimeoutMS' | 'srvMaxHosts' | 'srvServiceName' | 'tlsAllowInvalidCertificates' | 'tlsAllowInvalidHostnames' | 'tlsInsecure' | 'waitQueueTimeoutMS' | 'zlibCompressionLevel'>>, SupportedNodeConnectionOptions {
  6581. appName?: string;
  6582. hosts: HostAddress[];
  6583. srvHost?: string;
  6584. credentials?: MongoCredentials;
  6585. readPreference: ReadPreference;
  6586. readConcern: ReadConcern;
  6587. loadBalanced: boolean;
  6588. directConnection: boolean;
  6589. serverApi: ServerApi;
  6590. compressors: CompressorName[];
  6591. writeConcern: WriteConcern;
  6592. dbName: string;
  6593. /* Excluded from this release type: metadata */
  6594. /* Excluded from this release type: autoEncrypter */
  6595. /* Excluded from this release type: tokenCache */
  6596. proxyHost?: string;
  6597. proxyPort?: number;
  6598. proxyUsername?: string;
  6599. proxyPassword?: string;
  6600. serverMonitoringMode: ServerMonitoringMode;
  6601. /* Excluded from this release type: connectionType */
  6602. /* Excluded from this release type: authProviders */
  6603. /* Excluded from this release type: encrypter */
  6604. /* Excluded from this release type: userSpecifiedAuthSource */
  6605. /* Excluded from this release type: userSpecifiedReplicaSet */
  6606. /**
  6607. * # NOTE ABOUT TLS Options
  6608. *
  6609. * If `tls` is provided as an option, it is equivalent to setting the `ssl` option.
  6610. *
  6611. * NodeJS native TLS options are passed through to the socket and retain their original types.
  6612. *
  6613. * ### Additional options:
  6614. *
  6615. * | nodejs native option | driver spec equivalent option name | driver option type |
  6616. * |:----------------------|:----------------------------------------------|:-------------------|
  6617. * | `ca` | `tlsCAFile` | `string` |
  6618. * | `crl` | `tlsCRLFile` | `string` |
  6619. * | `cert` | `tlsCertificateKeyFile` | `string` |
  6620. * | `key` | `tlsCertificateKeyFile` | `string` |
  6621. * | `passphrase` | `tlsCertificateKeyFilePassword` | `string` |
  6622. * | `rejectUnauthorized` | `tlsAllowInvalidCertificates` | `boolean` |
  6623. * | `checkServerIdentity` | `tlsAllowInvalidHostnames` | `boolean` |
  6624. * | see note below | `tlsInsecure` | `boolean` |
  6625. *
  6626. * If `tlsInsecure` is set to `true`, then it will set the node native options `checkServerIdentity`
  6627. * to a no-op and `rejectUnauthorized` to `false`.
  6628. *
  6629. * If `tlsInsecure` is set to `false`, then it will set the node native options `checkServerIdentity`
  6630. * to a no-op and `rejectUnauthorized` to the inverse value of `tlsAllowInvalidCertificates`. If
  6631. * `tlsAllowInvalidCertificates` is not set, then `rejectUnauthorized` will be set to `true`.
  6632. *
  6633. * ### Note on `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile`
  6634. *
  6635. * The files specified by the paths passed in to the `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile`
  6636. * fields are read lazily on the first call to `MongoClient.connect`. Once these files have been read and
  6637. * the `ca`, `cert`, `crl` and `key` fields are populated, they will not be read again on subsequent calls to
  6638. * `MongoClient.connect`. As a result, until the first call to `MongoClient.connect`, the `ca`,
  6639. * `cert`, `crl` and `key` fields will be undefined.
  6640. */
  6641. tls: boolean;
  6642. tlsCAFile?: string;
  6643. tlsCRLFile?: string;
  6644. tlsCertificateKeyFile?: string;
  6645. /* Excluded from this release type: mongoLoggerOptions */
  6646. /* Excluded from this release type: mongodbLogPath */
  6647. timeoutMS?: number;
  6648. /* Excluded from this release type: __skipPingOnConnect */
  6649. }
  6650. /**
  6651. * An error used when attempting to parse a value (like a connection string)
  6652. * @public
  6653. * @category Error
  6654. */
  6655. export declare class MongoParseError extends MongoDriverError {
  6656. /**
  6657. * **Do not use this constructor!**
  6658. *
  6659. * Meant for internal use only.
  6660. *
  6661. * @remarks
  6662. * This class is only meant to be constructed within the driver. This constructor is
  6663. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6664. *
  6665. * @public
  6666. **/
  6667. constructor(message: string);
  6668. get name(): string;
  6669. }
  6670. /**
  6671. * An error generated when the driver encounters unexpected input
  6672. * or reaches an unexpected/invalid internal state.
  6673. *
  6674. * @privateRemarks
  6675. * Should **never** be directly instantiated.
  6676. *
  6677. * @public
  6678. * @category Error
  6679. */
  6680. export declare class MongoRuntimeError extends MongoDriverError {
  6681. /**
  6682. * **Do not use this constructor!**
  6683. *
  6684. * Meant for internal use only.
  6685. *
  6686. * @remarks
  6687. * This class is only meant to be constructed within the driver. This constructor is
  6688. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6689. *
  6690. * @public
  6691. **/
  6692. constructor(message: string, options?: {
  6693. cause?: Error;
  6694. });
  6695. get name(): string;
  6696. }
  6697. /**
  6698. * An error generated when an attempt is made to operate
  6699. * on a closed/closing server.
  6700. *
  6701. * @public
  6702. * @category Error
  6703. */
  6704. export declare class MongoServerClosedError extends MongoAPIError {
  6705. /**
  6706. * **Do not use this constructor!**
  6707. *
  6708. * Meant for internal use only.
  6709. *
  6710. * @remarks
  6711. * This class is only meant to be constructed within the driver. This constructor is
  6712. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6713. *
  6714. * @public
  6715. **/
  6716. constructor(message?: string);
  6717. get name(): string;
  6718. }
  6719. /**
  6720. * An error coming from the mongo server
  6721. *
  6722. * @public
  6723. * @category Error
  6724. */
  6725. export declare class MongoServerError extends MongoError {
  6726. /** Raw error result document returned by server. */
  6727. errorResponse: ErrorDescription;
  6728. codeName?: string;
  6729. writeConcernError?: Document;
  6730. errInfo?: Document;
  6731. ok?: number;
  6732. [key: string]: any;
  6733. /**
  6734. * **Do not use this constructor!**
  6735. *
  6736. * Meant for internal use only.
  6737. *
  6738. * @remarks
  6739. * This class is only meant to be constructed within the driver. This constructor is
  6740. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6741. *
  6742. * @public
  6743. **/
  6744. constructor(message: ErrorDescription);
  6745. get name(): string;
  6746. }
  6747. /**
  6748. * An error signifying a client-side server selection error
  6749. * @public
  6750. * @category Error
  6751. */
  6752. export declare class MongoServerSelectionError extends MongoSystemError {
  6753. /**
  6754. * **Do not use this constructor!**
  6755. *
  6756. * Meant for internal use only.
  6757. *
  6758. * @remarks
  6759. * This class is only meant to be constructed within the driver. This constructor is
  6760. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6761. *
  6762. * @public
  6763. **/
  6764. constructor(message: string, reason: TopologyDescription);
  6765. get name(): string;
  6766. }
  6767. /**
  6768. * An error generated when a primary server is marked stale, never directly thrown
  6769. *
  6770. * @public
  6771. * @category Error
  6772. */
  6773. export declare class MongoStalePrimaryError extends MongoRuntimeError {
  6774. /**
  6775. * **Do not use this constructor!**
  6776. *
  6777. * Meant for internal use only.
  6778. *
  6779. * @remarks
  6780. * This class is only meant to be constructed within the driver. This constructor is
  6781. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6782. *
  6783. * @public
  6784. **/
  6785. constructor(message: string, options?: {
  6786. cause?: Error;
  6787. });
  6788. get name(): string;
  6789. }
  6790. /**
  6791. * An error signifying a general system issue
  6792. * @public
  6793. * @category Error
  6794. */
  6795. export declare class MongoSystemError extends MongoError {
  6796. /** An optional reason context, such as an error saved during flow of monitoring and selecting servers */
  6797. reason?: TopologyDescription;
  6798. /**
  6799. * **Do not use this constructor!**
  6800. *
  6801. * Meant for internal use only.
  6802. *
  6803. * @remarks
  6804. * This class is only meant to be constructed within the driver. This constructor is
  6805. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6806. *
  6807. * @public
  6808. **/
  6809. constructor(message: string, reason: TopologyDescription);
  6810. get name(): string;
  6811. }
  6812. /**
  6813. * An error thrown when the user calls a function or method not supported on a tailable cursor
  6814. *
  6815. * @public
  6816. * @category Error
  6817. */
  6818. export declare class MongoTailableCursorError extends MongoAPIError {
  6819. /**
  6820. * **Do not use this constructor!**
  6821. *
  6822. * Meant for internal use only.
  6823. *
  6824. * @remarks
  6825. * This class is only meant to be constructed within the driver. This constructor is
  6826. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6827. *
  6828. * @public
  6829. **/
  6830. constructor(message?: string);
  6831. get name(): string;
  6832. }
  6833. /**
  6834. * An error generated when an attempt is made to operate on a
  6835. * dropped, or otherwise unavailable, database.
  6836. *
  6837. * @public
  6838. * @category Error
  6839. */
  6840. export declare class MongoTopologyClosedError extends MongoAPIError {
  6841. /**
  6842. * **Do not use this constructor!**
  6843. *
  6844. * Meant for internal use only.
  6845. *
  6846. * @remarks
  6847. * This class is only meant to be constructed within the driver. This constructor is
  6848. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6849. *
  6850. * @public
  6851. **/
  6852. constructor(message?: string);
  6853. get name(): string;
  6854. }
  6855. /**
  6856. * An error generated when the user makes a mistake in the usage of transactions.
  6857. * (e.g. attempting to commit a transaction with a readPreference other than primary)
  6858. *
  6859. * @public
  6860. * @category Error
  6861. */
  6862. export declare class MongoTransactionError extends MongoAPIError {
  6863. /**
  6864. * **Do not use this constructor!**
  6865. *
  6866. * Meant for internal use only.
  6867. *
  6868. * @remarks
  6869. * This class is only meant to be constructed within the driver. This constructor is
  6870. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6871. *
  6872. * @public
  6873. **/
  6874. constructor(message: string);
  6875. get name(): string;
  6876. }
  6877. /**
  6878. * An error generated when a **parsable** unexpected response comes from the server.
  6879. * This is generally an error where the driver in a state expecting a certain behavior to occur in
  6880. * the next message from MongoDB but it receives something else.
  6881. * This error **does not** represent an issue with wire message formatting.
  6882. *
  6883. * #### Example
  6884. * When an operation fails, it is the driver's job to retry it. It must perform serverSelection
  6885. * again to make sure that it attempts the operation against a server in a good state. If server
  6886. * selection returns a server that does not support retryable operations, this error is used.
  6887. * This scenario is unlikely as retryable support would also have been determined on the first attempt
  6888. * but it is possible the state change could report a selectable server that does not support retries.
  6889. *
  6890. * @public
  6891. * @category Error
  6892. */
  6893. export declare class MongoUnexpectedServerResponseError extends MongoRuntimeError {
  6894. /**
  6895. * **Do not use this constructor!**
  6896. *
  6897. * Meant for internal use only.
  6898. *
  6899. * @remarks
  6900. * This class is only meant to be constructed within the driver. This constructor is
  6901. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6902. *
  6903. * @public
  6904. **/
  6905. constructor(message: string, options?: {
  6906. cause?: Error;
  6907. });
  6908. get name(): string;
  6909. }
  6910. /**
  6911. * An error thrown when the server reports a writeConcernError
  6912. * @public
  6913. * @category Error
  6914. */
  6915. export declare class MongoWriteConcernError extends MongoServerError {
  6916. /** The result document */
  6917. result: Document;
  6918. /**
  6919. * **Do not use this constructor!**
  6920. *
  6921. * Meant for internal use only.
  6922. *
  6923. * @remarks
  6924. * This class is only meant to be constructed within the driver. This constructor is
  6925. * not subject to semantic versioning compatibility guarantees and may change at any time.
  6926. *
  6927. * @public
  6928. **/
  6929. constructor(result: WriteConcernErrorResult);
  6930. get name(): string;
  6931. }
  6932. /* Excluded from this release type: Monitor */
  6933. /** @public */
  6934. export declare type MonitorEvents = {
  6935. serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
  6936. serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
  6937. serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
  6938. resetServer(error?: MongoError): void;
  6939. resetConnectionPool(): void;
  6940. close(): void;
  6941. } & EventEmitterWithState;
  6942. /* Excluded from this release type: MonitorInterval */
  6943. /* Excluded from this release type: MonitorIntervalOptions */
  6944. /** @public */
  6945. export declare interface MonitorOptions extends Omit<ConnectionOptions, 'id' | 'generation' | 'hostAddress'> {
  6946. connectTimeoutMS: number;
  6947. heartbeatFrequencyMS: number;
  6948. minHeartbeatFrequencyMS: number;
  6949. serverMonitoringMode: ServerMonitoringMode;
  6950. }
  6951. /* Excluded from this release type: MonitorPrivate */
  6952. /**
  6953. * @public
  6954. * returns tuple of strings (keys to be joined on '.') that represent every path into a schema
  6955. * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
  6956. *
  6957. * @remarks
  6958. * Through testing we determined that a depth of 8 is safe for the typescript compiler
  6959. * and provides reasonable compilation times. This number is otherwise not special and
  6960. * should be changed if issues are found with this level of checking. Beyond this
  6961. * depth any helpers that make use of NestedPaths should devolve to not asserting any
  6962. * type safety on the input.
  6963. */
  6964. 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) | {
  6965. _bsontype: string;
  6966. } ? [] : Type extends ReadonlyArray<infer ArrayType> ? [] | [number, ...NestedPaths<ArrayType, [...Depth, 1]>] : Type extends Map<string, any> ? [string] : Type extends object ? {
  6967. [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] : [
  6968. Key,
  6969. ...NestedPaths<Type[Key], [...Depth, 1]>
  6970. ] : // child is not structured the same as the parent
  6971. [
  6972. Key,
  6973. ...NestedPaths<Type[Key], [...Depth, 1]>
  6974. ] | [Key];
  6975. }[Extract<keyof Type, string>] : [];
  6976. /**
  6977. * @public
  6978. * returns keys (strings) for every path into a schema with a value of type
  6979. * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
  6980. */
  6981. export declare type NestedPathsOfType<TSchema, Type> = KeysOfAType<{
  6982. [Property in Join<NestedPaths<TSchema, []>, '.'>]: PropertyType<TSchema, Property>;
  6983. }, Type>;
  6984. /**
  6985. * @public
  6986. * A type that extends Document but forbids anything that "looks like" an object id.
  6987. */
  6988. export declare type NonObjectIdLikeDocument = {
  6989. [key in keyof ObjectIdLike]?: never;
  6990. } & Document;
  6991. /** It avoids using fields with not acceptable types @public */
  6992. export declare type NotAcceptedFields<TSchema, FieldType> = {
  6993. readonly [key in KeysOfOtherType<TSchema, FieldType>]?: never;
  6994. };
  6995. /** @public */
  6996. export declare type NumericType = IntegerType | Decimal128 | Double;
  6997. export { ObjectId }
  6998. /**
  6999. * The signature of the human or machine callback functions.
  7000. * @public
  7001. */
  7002. export declare type OIDCCallbackFunction = (params: OIDCCallbackParams) => Promise<OIDCResponse>;
  7003. /**
  7004. * The parameters that the driver provides to the user supplied
  7005. * human or machine callback.
  7006. *
  7007. * The version number is used to communicate callback API changes that are not breaking but that
  7008. * users may want to know about and review their implementation. Users may wish to check the version
  7009. * number and throw an error if their expected version number and the one provided do not match.
  7010. * @public
  7011. */
  7012. export declare interface OIDCCallbackParams {
  7013. /** Optional username. */
  7014. username?: string;
  7015. /** The context in which to timeout the OIDC callback. */
  7016. timeoutContext: AbortSignal;
  7017. /** The current OIDC API version. */
  7018. version: 1;
  7019. /** The IdP information returned from the server. */
  7020. idpInfo?: IdPInfo;
  7021. /** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
  7022. refreshToken?: string;
  7023. /** The token audience for GCP and Azure. */
  7024. tokenAudience?: string;
  7025. }
  7026. /**
  7027. * The response required to be returned from the machine or
  7028. * human callback workflows' callback.
  7029. * @public
  7030. */
  7031. export declare interface OIDCResponse {
  7032. /** The OIDC access token. */
  7033. accessToken: string;
  7034. /** The time when the access token expires. For future use. */
  7035. expiresInSeconds?: number;
  7036. /** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
  7037. refreshToken?: string;
  7038. }
  7039. /* Excluded from this release type: OnDemandDocument */
  7040. /* Excluded from this release type: OnDemandDocumentDeserializeOptions */
  7041. /** @public */
  7042. export declare type OneOrMore<T> = T | ReadonlyArray<T>;
  7043. /** @public */
  7044. export declare type OnlyFieldsOfType<TSchema, FieldType = any, AssignableType = FieldType> = IsAny<TSchema[keyof TSchema], AssignableType extends FieldType ? Record<string, FieldType> : Record<string, AssignableType>, AcceptedFields<TSchema, FieldType, AssignableType> & NotAcceptedFields<TSchema, FieldType> & Record<string, AssignableType>>;
  7045. /* Excluded from this release type: OpCompressedRequest */
  7046. /* Excluded from this release type: OpCompressesRequestOptions */
  7047. /** @public */
  7048. export declare interface OperationOptions extends BSONSerializeOptions {
  7049. /** Specify ClientSession for this command */
  7050. session?: ClientSession;
  7051. willRetryWrite?: boolean;
  7052. /** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */
  7053. readPreference?: ReadPreferenceLike;
  7054. /* Excluded from this release type: bypassPinningCheck */
  7055. /* Excluded from this release type: omitMaxTimeMS */
  7056. /**
  7057. * @experimental
  7058. * Specifies the time an operation will run until it throws a timeout error
  7059. */
  7060. timeoutMS?: number;
  7061. }
  7062. /* Excluded from this release type: OperationParent */
  7063. /**
  7064. * Represents a specific point in time on a server. Can be retrieved by using `db.command()`
  7065. * @public
  7066. * @see https://www.mongodb.com/docs/manual/reference/method/db.runCommand/#response
  7067. */
  7068. export declare type OperationTime = Timestamp;
  7069. /* Excluded from this release type: OpMsgOptions */
  7070. /* Excluded from this release type: OpMsgRequest */
  7071. /* Excluded from this release type: OpMsgResponse */
  7072. /* Excluded from this release type: OpQueryOptions */
  7073. /* Excluded from this release type: OpQueryRequest */
  7074. /* Excluded from this release type: OpReply */
  7075. /**
  7076. * Add an optional _id field to an object shaped type
  7077. * @public
  7078. */
  7079. export declare type OptionalId<TSchema> = EnhancedOmit<TSchema, '_id'> & {
  7080. _id?: InferIdType<TSchema>;
  7081. };
  7082. /**
  7083. * Adds an optional _id field to an object shaped type, unless the _id field is required on that type.
  7084. * In the case _id is required, this method continues to require_id.
  7085. *
  7086. * @public
  7087. *
  7088. * @privateRemarks
  7089. * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask
  7090. * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?"
  7091. * we instead ask "Does ObjectId look like (have the same shape) as the _id?"
  7092. */
  7093. export declare type OptionalUnlessRequiredId<TSchema> = TSchema extends {
  7094. _id: any;
  7095. } ? TSchema : OptionalId<TSchema>;
  7096. /** @public */
  7097. export declare class OrderedBulkOperation extends BulkOperationBase {
  7098. /* Excluded from this release type: __constructor */
  7099. addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
  7100. }
  7101. /** @public */
  7102. export declare interface PkFactory {
  7103. createPk(): any;
  7104. }
  7105. /* Excluded from this release type: PoolState */
  7106. /** @public */
  7107. export declare const ProfilingLevel: Readonly<{
  7108. readonly off: "off";
  7109. readonly slowOnly: "slow_only";
  7110. readonly all: "all";
  7111. }>;
  7112. /** @public */
  7113. export declare type ProfilingLevel = (typeof ProfilingLevel)[keyof typeof ProfilingLevel];
  7114. /** @public */
  7115. export declare type ProfilingLevelOptions = Omit<CommandOperationOptions, 'rawData'>;
  7116. /** @public */
  7117. 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;
  7118. /** @public */
  7119. export declare interface ProxyOptions {
  7120. proxyHost?: string;
  7121. proxyPort?: number;
  7122. proxyUsername?: string;
  7123. proxyPassword?: string;
  7124. }
  7125. /** @public */
  7126. export declare type PullAllOperator<TSchema> = ({
  7127. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: TSchema[key];
  7128. } & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
  7129. readonly [key: string]: ReadonlyArray<any>;
  7130. };
  7131. /** @public */
  7132. export declare type PullOperator<TSchema> = ({
  7133. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: Partial<Flatten<TSchema[key]>> | FilterOperations<Flatten<TSchema[key]>>;
  7134. } & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
  7135. readonly [key: string]: FilterOperators<any> | any;
  7136. };
  7137. /** @public */
  7138. export declare type PushOperator<TSchema> = ({
  7139. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: Flatten<TSchema[key]> | ArrayOperator<Array<Flatten<TSchema[key]>>>;
  7140. } & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
  7141. readonly [key: string]: ArrayOperator<any> | any;
  7142. };
  7143. /**
  7144. * @public
  7145. * RangeOptions specifies index options for a Queryable Encryption field supporting "range" queries.
  7146. * min, max, sparsity, trimFactor and range must match the values set in the encryptedFields of the destination collection.
  7147. * For double and decimal128, min/max/precision must all be set, or all be unset.
  7148. */
  7149. export declare interface RangeOptions {
  7150. /** min is the minimum value for the encrypted index. Required if precision is set. */
  7151. min?: any;
  7152. /** max is the minimum value for the encrypted index. Required if precision is set. */
  7153. max?: any;
  7154. /** sparsity may be used to tune performance. must be non-negative. When omitted, a default value is used. */
  7155. sparsity?: Long | bigint;
  7156. /** trimFactor may be used to tune performance. must be non-negative. When omitted, a default value is used. */
  7157. trimFactor?: Int32 | number;
  7158. precision?: number;
  7159. }
  7160. /**
  7161. * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
  7162. * of the data read from replica sets and replica set shards.
  7163. * @public
  7164. *
  7165. * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html
  7166. */
  7167. export declare class ReadConcern {
  7168. level: ReadConcernLevel | string;
  7169. /** Constructs a ReadConcern from the read concern level.*/
  7170. constructor(level: ReadConcernLevel);
  7171. /**
  7172. * Construct a ReadConcern given an options object.
  7173. *
  7174. * @param options - The options object from which to extract the write concern.
  7175. */
  7176. static fromOptions(options?: {
  7177. readConcern?: ReadConcernLike;
  7178. level?: ReadConcernLevel;
  7179. }): ReadConcern | undefined;
  7180. static get MAJORITY(): 'majority';
  7181. static get AVAILABLE(): 'available';
  7182. static get LINEARIZABLE(): 'linearizable';
  7183. static get SNAPSHOT(): 'snapshot';
  7184. toJSON(): Document;
  7185. }
  7186. /** @public */
  7187. export declare const ReadConcernLevel: Readonly<{
  7188. readonly local: "local";
  7189. readonly majority: "majority";
  7190. readonly linearizable: "linearizable";
  7191. readonly available: "available";
  7192. readonly snapshot: "snapshot";
  7193. }>;
  7194. /** @public */
  7195. export declare type ReadConcernLevel = (typeof ReadConcernLevel)[keyof typeof ReadConcernLevel];
  7196. /** @public */
  7197. export declare type ReadConcernLike = ReadConcern | {
  7198. level: ReadConcernLevel;
  7199. } | ReadConcernLevel;
  7200. /**
  7201. * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is
  7202. * used to construct connections.
  7203. * @public
  7204. *
  7205. * @see https://www.mongodb.com/docs/manual/core/read-preference/
  7206. */
  7207. export declare class ReadPreference {
  7208. mode: ReadPreferenceMode;
  7209. tags?: TagSet[];
  7210. hedge?: HedgeOptions;
  7211. maxStalenessSeconds?: number;
  7212. static PRIMARY: "primary";
  7213. static PRIMARY_PREFERRED: "primaryPreferred";
  7214. static SECONDARY: "secondary";
  7215. static SECONDARY_PREFERRED: "secondaryPreferred";
  7216. static NEAREST: "nearest";
  7217. static primary: ReadPreference;
  7218. static primaryPreferred: ReadPreference;
  7219. static secondary: ReadPreference;
  7220. static secondaryPreferred: ReadPreference;
  7221. static nearest: ReadPreference;
  7222. /**
  7223. * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
  7224. * @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.
  7225. * @param options - Additional read preference options
  7226. */
  7227. constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions);
  7228. get preference(): ReadPreferenceMode;
  7229. static fromString(mode: string): ReadPreference;
  7230. /**
  7231. * Construct a ReadPreference given an options object.
  7232. *
  7233. * @param options - The options object from which to extract the read preference.
  7234. */
  7235. static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined;
  7236. /**
  7237. * Replaces options.readPreference with a ReadPreference instance
  7238. */
  7239. static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions;
  7240. /**
  7241. * Validate if a mode is legal
  7242. *
  7243. * @param mode - The string representing the read preference mode.
  7244. */
  7245. static isValid(mode: string): boolean;
  7246. /**
  7247. * Validate if a mode is legal
  7248. *
  7249. * @param mode - The string representing the read preference mode.
  7250. */
  7251. isValid(mode?: string): boolean;
  7252. /**
  7253. * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire
  7254. * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query
  7255. */
  7256. secondaryOk(): boolean;
  7257. /**
  7258. * Check if the two ReadPreferences are equivalent
  7259. *
  7260. * @param readPreference - The read preference with which to check equality
  7261. */
  7262. equals(readPreference: ReadPreference): boolean;
  7263. /** Return JSON representation */
  7264. toJSON(): Document;
  7265. }
  7266. /** @public */
  7267. export declare interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions {
  7268. session?: ClientSession;
  7269. readPreferenceTags?: TagSet[];
  7270. hedge?: HedgeOptions;
  7271. }
  7272. /** @public */
  7273. export declare type ReadPreferenceLike = ReadPreference | ReadPreferenceMode;
  7274. /** @public */
  7275. export declare interface ReadPreferenceLikeOptions extends ReadPreferenceOptions {
  7276. readPreference?: ReadPreferenceLike | {
  7277. mode?: ReadPreferenceMode;
  7278. preference?: ReadPreferenceMode;
  7279. tags?: TagSet[];
  7280. maxStalenessSeconds?: number;
  7281. };
  7282. }
  7283. /** @public */
  7284. export declare const ReadPreferenceMode: Readonly<{
  7285. readonly primary: "primary";
  7286. readonly primaryPreferred: "primaryPreferred";
  7287. readonly secondary: "secondary";
  7288. readonly secondaryPreferred: "secondaryPreferred";
  7289. readonly nearest: "nearest";
  7290. }>;
  7291. /** @public */
  7292. export declare type ReadPreferenceMode = (typeof ReadPreferenceMode)[keyof typeof ReadPreferenceMode];
  7293. /** @public */
  7294. export declare interface ReadPreferenceOptions {
  7295. /** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/
  7296. maxStalenessSeconds?: number;
  7297. /** Server mode in which the same query is dispatched in parallel to multiple replica set members. */
  7298. hedge?: HedgeOptions;
  7299. }
  7300. /** @public */
  7301. export declare type RegExpOrString<T> = T extends string ? BSONRegExp | RegExp | T : T;
  7302. /** @public */
  7303. export declare type RemoveUserOptions = Omit<CommandOperationOptions, 'rawData'>;
  7304. /** @public */
  7305. export declare interface RenameOptions extends Omit<CommandOperationOptions, 'rawData'> {
  7306. /** Drop the target name collection if it previously exists. */
  7307. dropTarget?: boolean;
  7308. /** Unclear */
  7309. new_collection?: boolean;
  7310. }
  7311. /** @public */
  7312. export declare interface ReplaceOneModel<TSchema extends Document = Document> {
  7313. /** The filter that specifies which document to replace. In the case of multiple matches, the first document matched is replaced. */
  7314. filter: Filter<TSchema>;
  7315. /** The document with which to replace the matched document. */
  7316. replacement: WithoutId<TSchema>;
  7317. /** Specifies a collation. */
  7318. collation?: CollationOptions;
  7319. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  7320. hint?: Hint;
  7321. /** When true, creates a new document if no document matches the query. */
  7322. upsert?: boolean;
  7323. /** Specifies the sort order for the documents matched by the filter. */
  7324. sort?: Sort;
  7325. }
  7326. /** @public */
  7327. export declare interface ReplaceOptions extends CommandOperationOptions {
  7328. /** If true, allows the write to opt-out of document level validation */
  7329. bypassDocumentValidation?: boolean;
  7330. /** Specifies a collation */
  7331. collation?: CollationOptions;
  7332. /** Specify that the update query should only consider plans using the hinted index */
  7333. hint?: string | Document;
  7334. /** When true, creates a new document if no document matches the query */
  7335. upsert?: boolean;
  7336. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  7337. let?: Document;
  7338. /** Specifies the sort order for the documents matched by the filter. */
  7339. sort?: Sort;
  7340. }
  7341. /**
  7342. * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server.
  7343. * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume
  7344. * @public
  7345. */
  7346. export declare type ResumeToken = unknown;
  7347. /** @public */
  7348. export declare const ReturnDocument: Readonly<{
  7349. readonly BEFORE: "before";
  7350. readonly AFTER: "after";
  7351. }>;
  7352. /** @public */
  7353. export declare type ReturnDocument = (typeof ReturnDocument)[keyof typeof ReturnDocument];
  7354. /** @public */
  7355. export declare interface RootFilterOperators<TSchema> extends Document {
  7356. $and?: Filter<TSchema>[];
  7357. $nor?: Filter<TSchema>[];
  7358. $or?: Filter<TSchema>[];
  7359. $text?: {
  7360. $search: string;
  7361. $language?: string;
  7362. $caseSensitive?: boolean;
  7363. $diacriticSensitive?: boolean;
  7364. };
  7365. $where?: string | ((this: TSchema) => boolean);
  7366. $comment?: string | Document;
  7367. }
  7368. /* Excluded from this release type: RTTPinger */
  7369. /* Excluded from this release type: RTTPingerOptions */
  7370. /* Excluded from this release type: RTTSampler */
  7371. /** @public */
  7372. export declare class RunCommandCursor extends AbstractCursor {
  7373. readonly command: Readonly<Record<string, any>>;
  7374. readonly getMoreOptions: {
  7375. comment?: any;
  7376. maxAwaitTimeMS?: number;
  7377. batchSize?: number;
  7378. };
  7379. /**
  7380. * Controls the `getMore.comment` field
  7381. * @param comment - any BSON value
  7382. */
  7383. setComment(comment: any): this;
  7384. /**
  7385. * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await
  7386. * @param maxTimeMS - the number of milliseconds to wait for new data
  7387. */
  7388. setMaxTimeMS(maxTimeMS: number): this;
  7389. /**
  7390. * Controls the `getMore.batchSize` field
  7391. * @param batchSize - the number documents to return in the `nextBatch`
  7392. */
  7393. setBatchSize(batchSize: number): this;
  7394. /** Unsupported for RunCommandCursor */
  7395. clone(): never;
  7396. /** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */
  7397. withReadConcern(_: ReadConcernLike): never;
  7398. /** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */
  7399. addCursorFlag(_: string, __: boolean): never;
  7400. /**
  7401. * Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document
  7402. */
  7403. maxTimeMS(_: number): never;
  7404. /** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */
  7405. batchSize(_: number): never;
  7406. /* Excluded from this release type: db */
  7407. /* Excluded from this release type: __constructor */
  7408. /* Excluded from this release type: _initialize */
  7409. /* Excluded from this release type: getMore */
  7410. }
  7411. /** @public */
  7412. export declare type RunCommandOptions = {
  7413. /** Specify ClientSession for this command */
  7414. session?: ClientSession;
  7415. /** The read preference */
  7416. readPreference?: ReadPreferenceLike;
  7417. /**
  7418. * @experimental
  7419. * Specifies the time an operation will run until it throws a timeout error
  7420. */
  7421. timeoutMS?: number;
  7422. /* Excluded from this release type: omitMaxTimeMS */
  7423. /* Excluded from this release type: bypassPinningCheck */
  7424. } & BSONSerializeOptions & Abortable;
  7425. /** @public */
  7426. export declare type RunCursorCommandOptions = {
  7427. readPreference?: ReadPreferenceLike;
  7428. session?: ClientSession;
  7429. /**
  7430. * @experimental
  7431. * Specifies the time an operation will run until it throws a timeout error. Note that if
  7432. * `maxTimeMS` is provided in the command in addition to setting `timeoutMS` in the options, then
  7433. * the original value of `maxTimeMS` will be overwritten.
  7434. */
  7435. timeoutMS?: number;
  7436. /**
  7437. * @public
  7438. * @experimental
  7439. * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
  7440. * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
  7441. * `cursor.next()`.
  7442. * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
  7443. *
  7444. * Depending on the type of cursor being used, this option has different default values.
  7445. * For non-tailable cursors, this value defaults to `'cursorLifetime'`
  7446. * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
  7447. * definition can have an arbitrarily long lifetime.
  7448. *
  7449. * @example
  7450. * ```ts
  7451. * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
  7452. * for await (const doc of cursor) {
  7453. * // process doc
  7454. * // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
  7455. * // will continue to iterate successfully otherwise, regardless of the number of batches.
  7456. * }
  7457. * ```
  7458. *
  7459. * @example
  7460. * ```ts
  7461. * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
  7462. * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
  7463. * ```
  7464. */
  7465. timeoutMode?: CursorTimeoutMode;
  7466. tailable?: boolean;
  7467. awaitData?: boolean;
  7468. } & BSONSerializeOptions;
  7469. /** @public */
  7470. export declare type SchemaMember<T, V> = {
  7471. [P in keyof T]?: V;
  7472. } | {
  7473. [key: string]: V;
  7474. };
  7475. /**
  7476. * @public
  7477. */
  7478. export declare interface SearchIndexDescription extends Document {
  7479. /** The name of the index. */
  7480. name?: string;
  7481. /** The index definition. */
  7482. definition: Document;
  7483. /** The type of the index. Currently `search` or `vectorSearch` are supported. */
  7484. type?: string;
  7485. }
  7486. /** @public */
  7487. export declare interface SelectServerOptions {
  7488. readPreference?: ReadPreferenceLike;
  7489. /** How long to block for server selection before throwing an error */
  7490. serverSelectionTimeoutMS?: number;
  7491. session?: ClientSession;
  7492. operationName: string;
  7493. previousServer?: ServerDescription;
  7494. /* Excluded from this release type: timeoutContext */
  7495. }
  7496. export { serialize }
  7497. /* Excluded from this release type: Server */
  7498. /* Excluded from this release type: SERVER_CLOSED */
  7499. /* Excluded from this release type: SERVER_DESCRIPTION_CHANGED */
  7500. /* Excluded from this release type: SERVER_HEARTBEAT_FAILED */
  7501. /* Excluded from this release type: SERVER_HEARTBEAT_STARTED */
  7502. /* Excluded from this release type: SERVER_HEARTBEAT_SUCCEEDED */
  7503. /* Excluded from this release type: SERVER_OPENING */
  7504. /* Excluded from this release type: SERVER_SELECTION_FAILED */
  7505. /* Excluded from this release type: SERVER_SELECTION_STARTED */
  7506. /* Excluded from this release type: SERVER_SELECTION_SUCCEEDED */
  7507. /** @public */
  7508. export declare interface ServerApi {
  7509. version: ServerApiVersion;
  7510. strict?: boolean;
  7511. deprecationErrors?: boolean;
  7512. }
  7513. /** @public */
  7514. export declare const ServerApiVersion: Readonly<{
  7515. readonly v1: "1";
  7516. }>;
  7517. /** @public */
  7518. export declare type ServerApiVersion = (typeof ServerApiVersion)[keyof typeof ServerApiVersion];
  7519. /**
  7520. * Emitted when server is closed.
  7521. * @public
  7522. * @category Event
  7523. */
  7524. export declare class ServerClosedEvent {
  7525. /** A unique identifier for the topology */
  7526. topologyId: number;
  7527. /** The address (host/port pair) of the server */
  7528. address: string;
  7529. /* Excluded from this release type: name */
  7530. /* Excluded from this release type: __constructor */
  7531. }
  7532. /* Excluded from this release type: ServerCommandOptions */
  7533. /**
  7534. * The client's view of a single server, based on the most recent hello outcome.
  7535. *
  7536. * Internal type, not meant to be directly instantiated
  7537. * @public
  7538. */
  7539. export declare class ServerDescription {
  7540. address: string;
  7541. type: ServerType;
  7542. hosts: string[];
  7543. passives: string[];
  7544. arbiters: string[];
  7545. tags: TagSet;
  7546. error: MongoError | null;
  7547. topologyVersion: TopologyVersion | null;
  7548. minWireVersion: number;
  7549. maxWireVersion: number;
  7550. roundTripTime: number;
  7551. /** The minimum measurement of the last 10 measurements of roundTripTime that have been collected */
  7552. minRoundTripTime: number;
  7553. lastUpdateTime: number;
  7554. lastWriteDate: number;
  7555. me: string | null;
  7556. primary: string | null;
  7557. setName: string | null;
  7558. setVersion: number | null;
  7559. electionId: ObjectId | null;
  7560. logicalSessionTimeoutMinutes: number | null;
  7561. /** The max message size in bytes for the server. */
  7562. maxMessageSizeBytes: number | null;
  7563. /** The max number of writes in a bulk write command. */
  7564. maxWriteBatchSize: number | null;
  7565. /** The max bson object size. */
  7566. maxBsonObjectSize: number | null;
  7567. /** Indicates server is a mongocryptd instance. */
  7568. iscryptd: boolean;
  7569. $clusterTime?: ClusterTime;
  7570. /* Excluded from this release type: __constructor */
  7571. get hostAddress(): HostAddress;
  7572. get allHosts(): string[];
  7573. /** Is this server available for reads*/
  7574. get isReadable(): boolean;
  7575. /** Is this server data bearing */
  7576. get isDataBearing(): boolean;
  7577. /** Is this server available for writes */
  7578. get isWritable(): boolean;
  7579. get host(): string;
  7580. get port(): number;
  7581. /**
  7582. * Determines if another `ServerDescription` is equal to this one per the rules defined in the SDAM specification.
  7583. * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md
  7584. */
  7585. equals(other?: ServerDescription | null): boolean;
  7586. }
  7587. /**
  7588. * Emitted when server description changes, but does NOT include changes to the RTT.
  7589. * @public
  7590. * @category Event
  7591. */
  7592. export declare class ServerDescriptionChangedEvent {
  7593. /** A unique identifier for the topology */
  7594. topologyId: number;
  7595. /** The address (host/port pair) of the server */
  7596. address: string;
  7597. /** The previous server description */
  7598. previousDescription: ServerDescription;
  7599. /** The new server description */
  7600. newDescription: ServerDescription;
  7601. name: "serverDescriptionChanged";
  7602. /* Excluded from this release type: __constructor */
  7603. }
  7604. /* Excluded from this release type: ServerDescriptionOptions */
  7605. /** @public */
  7606. export declare type ServerEvents = {
  7607. serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
  7608. serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
  7609. serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
  7610. /* Excluded from this release type: connect */
  7611. descriptionReceived(description: ServerDescription): void;
  7612. closed(): void;
  7613. ended(): void;
  7614. } & ConnectionPoolEvents & EventEmitterWithState;
  7615. /**
  7616. * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception.
  7617. * @public
  7618. * @category Event
  7619. */
  7620. export declare class ServerHeartbeatFailedEvent {
  7621. /** The connection id for the command */
  7622. connectionId: string;
  7623. /** The execution time of the event in ms */
  7624. duration: number;
  7625. /** The command failure */
  7626. failure: Error;
  7627. /** Is true when using the streaming protocol */
  7628. awaited: boolean;
  7629. /* Excluded from this release type: name */
  7630. /* Excluded from this release type: __constructor */
  7631. }
  7632. /**
  7633. * Emitted when the server monitor’s hello command is started - immediately before
  7634. * the hello command is serialized into raw BSON and written to the socket.
  7635. *
  7636. * @public
  7637. * @category Event
  7638. */
  7639. export declare class ServerHeartbeatStartedEvent {
  7640. /** The connection id for the command */
  7641. connectionId: string;
  7642. /** Is true when using the streaming protocol */
  7643. awaited: boolean;
  7644. /* Excluded from this release type: name */
  7645. /* Excluded from this release type: __constructor */
  7646. }
  7647. /**
  7648. * Emitted when the server monitor’s hello succeeds.
  7649. * @public
  7650. * @category Event
  7651. */
  7652. export declare class ServerHeartbeatSucceededEvent {
  7653. /** The connection id for the command */
  7654. connectionId: string;
  7655. /** The execution time of the event in ms */
  7656. duration: number;
  7657. /** The command reply */
  7658. reply: Document;
  7659. /** Is true when using the streaming protocol */
  7660. awaited: boolean;
  7661. /* Excluded from this release type: name */
  7662. /* Excluded from this release type: __constructor */
  7663. }
  7664. /** @public */
  7665. export declare const ServerMonitoringMode: Readonly<{
  7666. readonly auto: "auto";
  7667. readonly poll: "poll";
  7668. readonly stream: "stream";
  7669. }>;
  7670. /** @public */
  7671. export declare type ServerMonitoringMode = (typeof ServerMonitoringMode)[keyof typeof ServerMonitoringMode];
  7672. /**
  7673. * Emitted when server is initialized.
  7674. * @public
  7675. * @category Event
  7676. */
  7677. export declare class ServerOpeningEvent {
  7678. /** A unique identifier for the topology */
  7679. topologyId: number;
  7680. /** The address (host/port pair) of the server */
  7681. address: string;
  7682. /* Excluded from this release type: name */
  7683. /* Excluded from this release type: __constructor */
  7684. }
  7685. /* Excluded from this release type: ServerOptions */
  7686. /* Excluded from this release type: ServerPrivate */
  7687. /* Excluded from this release type: ServerSelectionCallback */
  7688. /* Excluded from this release type: ServerSelectionEvent */
  7689. /* Excluded from this release type: ServerSelectionFailedEvent */
  7690. /* Excluded from this release type: ServerSelectionRequest */
  7691. /* Excluded from this release type: ServerSelectionStartedEvent */
  7692. /* Excluded from this release type: ServerSelectionSucceededEvent */
  7693. /* Excluded from this release type: ServerSelector */
  7694. /**
  7695. * Reflects the existence of a session on the server. Can be reused by the session pool.
  7696. * WARNING: not meant to be instantiated directly. For internal use only.
  7697. * @public
  7698. */
  7699. export declare class ServerSession {
  7700. id: ServerSessionId;
  7701. lastUse: number;
  7702. txnNumber: number;
  7703. isDirty: boolean;
  7704. /* Excluded from this release type: __constructor */
  7705. /**
  7706. * Determines if the server session has timed out.
  7707. *
  7708. * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
  7709. */
  7710. hasTimedOut(sessionTimeoutMinutes: number): boolean;
  7711. }
  7712. /** @public */
  7713. export declare type ServerSessionId = {
  7714. id: Binary;
  7715. };
  7716. /* Excluded from this release type: ServerSessionPool */
  7717. /**
  7718. * An enumeration of server types we know about
  7719. * @public
  7720. */
  7721. export declare const ServerType: Readonly<{
  7722. readonly Standalone: "Standalone";
  7723. readonly Mongos: "Mongos";
  7724. readonly PossiblePrimary: "PossiblePrimary";
  7725. readonly RSPrimary: "RSPrimary";
  7726. readonly RSSecondary: "RSSecondary";
  7727. readonly RSArbiter: "RSArbiter";
  7728. readonly RSOther: "RSOther";
  7729. readonly RSGhost: "RSGhost";
  7730. readonly Unknown: "Unknown";
  7731. readonly LoadBalancer: "LoadBalancer";
  7732. }>;
  7733. /** @public */
  7734. export declare type ServerType = (typeof ServerType)[keyof typeof ServerType];
  7735. /** @public */
  7736. export declare type SetFields<TSchema> = ({
  7737. readonly [key in KeysOfAType<TSchema, ReadonlyArray<any> | undefined>]?: OptionalId<Flatten<TSchema[key]>> | AddToSetOperators<Array<OptionalId<Flatten<TSchema[key]>>>>;
  7738. } & IsAny<TSchema[keyof TSchema], object, NotAcceptedFields<TSchema, ReadonlyArray<any> | undefined>>) & {
  7739. readonly [key: string]: AddToSetOperators<any> | any;
  7740. };
  7741. /** @public */
  7742. export declare type SetProfilingLevelOptions = Omit<CommandOperationOptions, 'rawData'>;
  7743. /**
  7744. * @public
  7745. * Severity levels align with unix syslog.
  7746. * Most typical driver functions will log to debug.
  7747. */
  7748. export declare const SeverityLevel: Readonly<{
  7749. readonly EMERGENCY: "emergency";
  7750. readonly ALERT: "alert";
  7751. readonly CRITICAL: "critical";
  7752. readonly ERROR: "error";
  7753. readonly WARNING: "warn";
  7754. readonly NOTICE: "notice";
  7755. readonly INFORMATIONAL: "info";
  7756. readonly DEBUG: "debug";
  7757. readonly TRACE: "trace";
  7758. readonly OFF: "off";
  7759. }>;
  7760. /** @public */
  7761. export declare type SeverityLevel = (typeof SeverityLevel)[keyof typeof SeverityLevel];
  7762. /** @public */
  7763. export declare type Sort = string | Exclude<SortDirection, {
  7764. readonly $meta: string;
  7765. }> | ReadonlyArray<string> | {
  7766. readonly [key: string]: SortDirection;
  7767. } | ReadonlyMap<string, SortDirection> | ReadonlyArray<readonly [string, SortDirection]> | readonly [string, SortDirection];
  7768. /** @public */
  7769. export declare type SortDirection = 1 | -1 | 'asc' | 'desc' | 'ascending' | 'descending' | {
  7770. readonly $meta: string;
  7771. };
  7772. /** Below stricter types were created for sort that correspond with type that the cmd takes */
  7773. /** @public */
  7774. export declare type SortDirectionForCmd = 1 | -1 | {
  7775. $meta: string;
  7776. };
  7777. /** @public */
  7778. export declare type SortForCmd = Map<string, SortDirectionForCmd>;
  7779. /* Excluded from this release type: SrvPoller */
  7780. /* Excluded from this release type: SrvPollerEvents */
  7781. /* Excluded from this release type: SrvPollerOptions */
  7782. /* Excluded from this release type: SrvPollingEvent */
  7783. /* Excluded from this release type: StateMachineExecutable */
  7784. /** @public */
  7785. export declare type Stream = Socket | TLSSocket;
  7786. /** @public */
  7787. export declare class StreamDescription {
  7788. address: string;
  7789. type: ServerType;
  7790. minWireVersion?: number;
  7791. maxWireVersion?: number;
  7792. maxBsonObjectSize: number;
  7793. maxMessageSizeBytes: number;
  7794. maxWriteBatchSize: number;
  7795. compressors: CompressorName[];
  7796. compressor?: CompressorName;
  7797. logicalSessionTimeoutMinutes?: number;
  7798. loadBalanced: boolean;
  7799. __nodejs_mock_server__?: boolean;
  7800. zlibCompressionLevel?: number;
  7801. serverConnectionId: bigint | null;
  7802. hello: Document | null;
  7803. constructor(address: string, options?: StreamDescriptionOptions);
  7804. receiveResponse(response: Document | null): void;
  7805. parseServerConnectionID(serverConnectionId: number | Double | bigint | Long): bigint;
  7806. }
  7807. /** @public */
  7808. export declare interface StreamDescriptionOptions {
  7809. compressors?: CompressorName[];
  7810. logicalSessionTimeoutMinutes?: number;
  7811. loadBalanced: boolean;
  7812. }
  7813. /**
  7814. * @public
  7815. * @experimental
  7816. */
  7817. export declare type StrictFilter<TSchema> = Partial<TSchema> | ({
  7818. [Property in Join<NestedPaths<WithId<TSchema>, []>, '.'>]?: Condition<PropertyType<WithId<TSchema>, Property>>;
  7819. } & RootFilterOperators<WithId<TSchema>>);
  7820. /**
  7821. * @public
  7822. * @experimental
  7823. */
  7824. export declare type StrictMatchKeysAndValues<TSchema> = Readonly<{
  7825. [Property in Join<NestedPaths<TSchema, []>, '.'>]?: PropertyType<TSchema, Property>;
  7826. } & {
  7827. [Property in `${NestedPathsOfType<TSchema, any[]>}.$${`[${string}]` | ''}`]?: ArrayElement<PropertyType<TSchema, Property extends `${infer Key}.$${string}` ? Key : never>>;
  7828. } & {
  7829. [Property in `${NestedPathsOfType<TSchema, Record<string, any>[]>}.$${`[${string}]` | ''}.${string}`]?: any;
  7830. } & Document>;
  7831. /**
  7832. * @public
  7833. * @experimental
  7834. */
  7835. export declare type StrictUpdateFilter<TSchema> = {
  7836. $currentDate?: OnlyFieldsOfType<TSchema, Date | Timestamp, true | {
  7837. $type: 'date' | 'timestamp';
  7838. }>;
  7839. $inc?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  7840. $min?: StrictMatchKeysAndValues<TSchema>;
  7841. $max?: StrictMatchKeysAndValues<TSchema>;
  7842. $mul?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  7843. $rename?: Record<string, string>;
  7844. $set?: StrictMatchKeysAndValues<TSchema>;
  7845. $setOnInsert?: StrictMatchKeysAndValues<TSchema>;
  7846. $unset?: OnlyFieldsOfType<TSchema, any, '' | true | 1>;
  7847. $addToSet?: SetFields<TSchema>;
  7848. $pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
  7849. $pull?: PullOperator<TSchema>;
  7850. $push?: PushOperator<TSchema>;
  7851. $pullAll?: PullAllOperator<TSchema>;
  7852. $bit?: OnlyFieldsOfType<TSchema, NumericType | undefined, {
  7853. and: IntegerType;
  7854. } | {
  7855. or: IntegerType;
  7856. } | {
  7857. xor: IntegerType;
  7858. }>;
  7859. } & Document;
  7860. /** @public */
  7861. export declare type SupportedNodeConnectionOptions = SupportedTLSConnectionOptions & SupportedTLSSocketOptions & SupportedSocketOptions;
  7862. /** @public */
  7863. export declare type SupportedSocketOptions = Pick<TcpNetConnectOpts & {
  7864. autoSelectFamily?: boolean;
  7865. autoSelectFamilyAttemptTimeout?: number;
  7866. /** Node.JS socket option to set the time the first keepalive probe is sent on an idle socket. Defaults to 120000ms */
  7867. keepAliveInitialDelay?: number;
  7868. }, (typeof LEGAL_TCP_SOCKET_OPTIONS)[number]>;
  7869. /** @public */
  7870. export declare type SupportedTLSConnectionOptions = Pick<ConnectionOptions_2 & {
  7871. allowPartialTrustChain?: boolean;
  7872. }, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>;
  7873. /** @public */
  7874. export declare type SupportedTLSSocketOptions = Pick<TLSSocketOptions, Extract<keyof TLSSocketOptions, (typeof LEGAL_TLS_SOCKET_OPTIONS)[number]>>;
  7875. /** @public */
  7876. export declare type TagSet = {
  7877. [key: string]: string;
  7878. };
  7879. /**
  7880. * Options for a Queryable Encryption field supporting text queries.
  7881. *
  7882. * @public
  7883. * @experimental Public Technical Preview: `textPreview` is an experimental feature and may break at any time.
  7884. */
  7885. export declare interface TextQueryOptions {
  7886. /** Indicates that text indexes for this field are case sensitive */
  7887. caseSensitive: boolean;
  7888. /** Indicates that text indexes for this field are diacritic sensitive. */
  7889. diacriticSensitive: boolean;
  7890. prefix?: {
  7891. /** The maximum allowed query length. */
  7892. strMaxQueryLength: Int32 | number;
  7893. /** The minimum allowed query length. */
  7894. strMinQueryLength: Int32 | number;
  7895. };
  7896. suffix?: {
  7897. /** The maximum allowed query length. */
  7898. strMaxQueryLength: Int32 | number;
  7899. /** The minimum allowed query length. */
  7900. strMinQueryLength: Int32 | number;
  7901. };
  7902. substring?: {
  7903. /** The maximum allowed length to insert. */
  7904. strMaxLength: Int32 | number;
  7905. /** The maximum allowed query length. */
  7906. strMaxQueryLength: Int32 | number;
  7907. /** The minimum allowed query length. */
  7908. strMinQueryLength: Int32 | number;
  7909. };
  7910. }
  7911. /* Excluded from this release type: Timeout */
  7912. /* Excluded from this release type: TimeoutContext */
  7913. /* Excluded from this release type: TimeoutContextOptions */
  7914. /** @public
  7915. * Configuration options for timeseries collections
  7916. * @see https://www.mongodb.com/docs/manual/core/timeseries-collections/
  7917. */
  7918. export declare interface TimeSeriesCollectionOptions extends Document {
  7919. timeField: string;
  7920. metaField?: string;
  7921. granularity?: 'seconds' | 'minutes' | 'hours' | string;
  7922. bucketMaxSpanSeconds?: number;
  7923. bucketRoundingSeconds?: number;
  7924. }
  7925. export { Timestamp }
  7926. /* Excluded from this release type: TokenCache */
  7927. /* Excluded from this release type: Topology */
  7928. /* Excluded from this release type: TOPOLOGY_CLOSED */
  7929. /* Excluded from this release type: TOPOLOGY_DESCRIPTION_CHANGED */
  7930. /* Excluded from this release type: TOPOLOGY_OPENING */
  7931. /**
  7932. * Emitted when topology is closed.
  7933. * @public
  7934. * @category Event
  7935. */
  7936. export declare class TopologyClosedEvent {
  7937. /** A unique identifier for the topology */
  7938. topologyId: number;
  7939. /* Excluded from this release type: name */
  7940. /* Excluded from this release type: __constructor */
  7941. }
  7942. /**
  7943. * Representation of a deployment of servers
  7944. * @public
  7945. */
  7946. export declare class TopologyDescription {
  7947. type: TopologyType;
  7948. setName: string | null;
  7949. maxSetVersion: number | null;
  7950. maxElectionId: ObjectId | null;
  7951. servers: Map<string, ServerDescription>;
  7952. stale: boolean;
  7953. compatible: boolean;
  7954. compatibilityError?: string;
  7955. logicalSessionTimeoutMinutes: number | null;
  7956. heartbeatFrequencyMS: number;
  7957. localThresholdMS: number;
  7958. commonWireVersion: number;
  7959. /**
  7960. * Create a TopologyDescription
  7961. */
  7962. constructor(topologyType: TopologyType, serverDescriptions?: Map<string, ServerDescription> | null, setName?: string | null, maxSetVersion?: number | null, maxElectionId?: ObjectId | null, commonWireVersion?: number | null, options?: TopologyDescriptionOptions | null);
  7963. /* Excluded from this release type: updateFromSrvPollingEvent */
  7964. /* Excluded from this release type: update */
  7965. get error(): MongoError | null;
  7966. /**
  7967. * Determines if the topology description has any known servers
  7968. */
  7969. get hasKnownServers(): boolean;
  7970. /**
  7971. * Determines if this topology description has a data-bearing server available.
  7972. */
  7973. get hasDataBearingServers(): boolean;
  7974. /* Excluded from this release type: hasServer */
  7975. /**
  7976. * Returns a JSON-serializable representation of the TopologyDescription. This is primarily
  7977. * intended for use with JSON.stringify().
  7978. *
  7979. * This method will not throw.
  7980. */
  7981. toJSON(): Document;
  7982. }
  7983. /**
  7984. * Emitted when topology description changes.
  7985. * @public
  7986. * @category Event
  7987. */
  7988. export declare class TopologyDescriptionChangedEvent {
  7989. /** A unique identifier for the topology */
  7990. topologyId: number;
  7991. /** The old topology description */
  7992. previousDescription: TopologyDescription;
  7993. /** The new topology description */
  7994. newDescription: TopologyDescription;
  7995. /* Excluded from this release type: name */
  7996. /* Excluded from this release type: __constructor */
  7997. }
  7998. /** @public */
  7999. export declare interface TopologyDescriptionOptions {
  8000. heartbeatFrequencyMS?: number;
  8001. localThresholdMS?: number;
  8002. }
  8003. /** @public */
  8004. export declare type TopologyEvents = {
  8005. /* Excluded from this release type: connect */
  8006. serverOpening(event: ServerOpeningEvent): void;
  8007. serverClosed(event: ServerClosedEvent): void;
  8008. serverDescriptionChanged(event: ServerDescriptionChangedEvent): void;
  8009. topologyClosed(event: TopologyClosedEvent): void;
  8010. topologyOpening(event: TopologyOpeningEvent): void;
  8011. topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void;
  8012. error(error: Error): void;
  8013. /* Excluded from this release type: open */
  8014. close(): void;
  8015. timeout(): void;
  8016. } & Omit<ServerEvents, 'connect'> & ConnectionPoolEvents & ConnectionEvents & EventEmitterWithState;
  8017. /**
  8018. * Emitted when topology is initialized.
  8019. * @public
  8020. * @category Event
  8021. */
  8022. export declare class TopologyOpeningEvent {
  8023. /** A unique identifier for the topology */
  8024. topologyId: number;
  8025. /* Excluded from this release type: name */
  8026. /* Excluded from this release type: __constructor */
  8027. }
  8028. /* Excluded from this release type: TopologyOptions */
  8029. /* Excluded from this release type: TopologyPrivate */
  8030. /**
  8031. * An enumeration of topology types we know about
  8032. * @public
  8033. */
  8034. export declare const TopologyType: Readonly<{
  8035. readonly Single: "Single";
  8036. readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary";
  8037. readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary";
  8038. readonly Sharded: "Sharded";
  8039. readonly Unknown: "Unknown";
  8040. readonly LoadBalanced: "LoadBalanced";
  8041. }>;
  8042. /** @public */
  8043. export declare type TopologyType = (typeof TopologyType)[keyof typeof TopologyType];
  8044. /** @public */
  8045. export declare interface TopologyVersion {
  8046. processId: ObjectId;
  8047. counter: Long;
  8048. }
  8049. /* Excluded from this release type: Transaction */
  8050. /**
  8051. * Configuration options for a transaction.
  8052. * @public
  8053. */
  8054. export declare interface TransactionOptions extends Omit<CommandOperationOptions, 'timeoutMS'> {
  8055. /** A default read concern for commands in this transaction */
  8056. readConcern?: ReadConcernLike;
  8057. /** A default writeConcern for commands in this transaction */
  8058. writeConcern?: WriteConcern;
  8059. /** A default read preference for commands in this transaction */
  8060. readPreference?: ReadPreferenceLike;
  8061. /** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */
  8062. maxCommitTimeMS?: number;
  8063. }
  8064. /* Excluded from this release type: TxnState */
  8065. /**
  8066. * Typescript type safe event emitter
  8067. * @public
  8068. */
  8069. export declare interface TypedEventEmitter<Events extends EventsDescription> extends EventEmitter {
  8070. addListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8071. addListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8072. addListener(event: string | symbol, listener: GenericListener): this;
  8073. on<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8074. on(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8075. on(event: string | symbol, listener: GenericListener): this;
  8076. once<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8077. once(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8078. once(event: string | symbol, listener: GenericListener): this;
  8079. removeListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8080. removeListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8081. removeListener(event: string | symbol, listener: GenericListener): this;
  8082. off<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8083. off(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8084. off(event: string | symbol, listener: GenericListener): this;
  8085. removeAllListeners<EventKey extends keyof Events>(event?: EventKey | CommonEvents | symbol | string): this;
  8086. listeners<EventKey extends keyof Events>(event: EventKey | CommonEvents | symbol | string): Events[EventKey][];
  8087. rawListeners<EventKey extends keyof Events>(event: EventKey | CommonEvents | symbol | string): Events[EventKey][];
  8088. emit<EventKey extends keyof Events>(event: EventKey | symbol, ...args: Parameters<Events[EventKey]>): boolean;
  8089. listenerCount<EventKey extends keyof Events>(type: EventKey | CommonEvents | symbol | string): number;
  8090. prependListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8091. prependListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8092. prependListener(event: string | symbol, listener: GenericListener): this;
  8093. prependOnceListener<EventKey extends keyof Events>(event: EventKey, listener: Events[EventKey]): this;
  8094. prependOnceListener(event: CommonEvents, listener: (eventName: string | symbol, listener: GenericListener) => void): this;
  8095. prependOnceListener(event: string | symbol, listener: GenericListener): this;
  8096. eventNames(): string[];
  8097. getMaxListeners(): number;
  8098. setMaxListeners(n: number): this;
  8099. }
  8100. /**
  8101. * Typescript type safe event emitter
  8102. * @public
  8103. */
  8104. export declare class TypedEventEmitter<Events extends EventsDescription> extends EventEmitter {
  8105. /* Excluded from this release type: mongoLogger */
  8106. /* Excluded from this release type: component */
  8107. /* Excluded from this release type: emitAndLog */
  8108. /* Excluded from this release type: emitAndLogHeartbeat */
  8109. /* Excluded from this release type: emitAndLogCommand */
  8110. }
  8111. /** @public */
  8112. export declare class UnorderedBulkOperation extends BulkOperationBase {
  8113. /* Excluded from this release type: __constructor */
  8114. handleWriteError(writeResult: BulkWriteResult): void;
  8115. addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
  8116. }
  8117. /** @public */
  8118. export declare interface UpdateDescription<TSchema extends Document = Document> {
  8119. /**
  8120. * A document containing key:value pairs of names of the fields that were
  8121. * changed, and the new value for those fields.
  8122. */
  8123. updatedFields?: Partial<TSchema>;
  8124. /**
  8125. * An array of field names that were removed from the document.
  8126. */
  8127. removedFields?: string[];
  8128. /**
  8129. * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages:
  8130. * - $addFields
  8131. * - $set
  8132. * - $replaceRoot
  8133. * - $replaceWith
  8134. */
  8135. truncatedArrays?: Array<{
  8136. /** The name of the truncated field. */
  8137. field: string;
  8138. /** The number of elements in the truncated array. */
  8139. newSize: number;
  8140. }>;
  8141. /**
  8142. * A document containing additional information about any ambiguous update paths from the update event. The document
  8143. * maps the full ambiguous update path to an array containing the actual resolved components of the path. For example,
  8144. * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like
  8145. * the following:
  8146. *
  8147. * ```
  8148. * {
  8149. * 'a.0': ['a', '0']
  8150. * }
  8151. * ```
  8152. *
  8153. * This field is only present when there are ambiguous paths that are updated as a part of the update event.
  8154. *
  8155. * On \<8.2.0 servers, this field is only present when `showExpandedEvents` is set to true.
  8156. * is enabled for the change stream.
  8157. *
  8158. * On 8.2.0+ servers, this field is present for update events regardless of whether `showExpandedEvents` is enabled.
  8159. * @sinceServerVersion 6.1.0
  8160. */
  8161. disambiguatedPaths?: Document;
  8162. }
  8163. /** @public */
  8164. export declare type UpdateFilter<TSchema> = {
  8165. $currentDate?: OnlyFieldsOfType<TSchema, Date | Timestamp, true | {
  8166. $type: 'date' | 'timestamp';
  8167. }>;
  8168. $inc?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  8169. $min?: MatchKeysAndValues<TSchema>;
  8170. $max?: MatchKeysAndValues<TSchema>;
  8171. $mul?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
  8172. $rename?: Record<string, string>;
  8173. $set?: MatchKeysAndValues<TSchema>;
  8174. $setOnInsert?: MatchKeysAndValues<TSchema>;
  8175. $unset?: OnlyFieldsOfType<TSchema, any, '' | true | 1>;
  8176. $addToSet?: SetFields<TSchema>;
  8177. $pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
  8178. $pull?: PullOperator<TSchema>;
  8179. $push?: PushOperator<TSchema>;
  8180. $pullAll?: PullAllOperator<TSchema>;
  8181. $bit?: OnlyFieldsOfType<TSchema, NumericType | undefined, {
  8182. and: IntegerType;
  8183. } | {
  8184. or: IntegerType;
  8185. } | {
  8186. xor: IntegerType;
  8187. }>;
  8188. } & Document;
  8189. /** @public */
  8190. export declare interface UpdateManyModel<TSchema extends Document = Document> {
  8191. /** The filter to limit the updated documents. */
  8192. filter: Filter<TSchema>;
  8193. /**
  8194. * The modifications to apply. The value can be either:
  8195. * UpdateFilter<TSchema> - A document that contains update operator expressions,
  8196. * Document[] - an aggregation pipeline.
  8197. */
  8198. update: UpdateFilter<TSchema> | Document[];
  8199. /** A set of filters specifying to which array elements an update should apply. */
  8200. arrayFilters?: Document[];
  8201. /** Specifies a collation. */
  8202. collation?: CollationOptions;
  8203. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  8204. hint?: Hint;
  8205. /** When true, creates a new document if no document matches the query. */
  8206. upsert?: boolean;
  8207. }
  8208. /** @public */
  8209. export declare interface UpdateOneModel<TSchema extends Document = Document> {
  8210. /** The filter that specifies which document to update. In the case of multiple matches, the first document matched is updated. */
  8211. filter: Filter<TSchema>;
  8212. /**
  8213. * The modifications to apply. The value can be either:
  8214. * UpdateFilter<TSchema> - A document that contains update operator expressions,
  8215. * Document[] - an aggregation pipeline.
  8216. */
  8217. update: UpdateFilter<TSchema> | Document[];
  8218. /** A set of filters specifying to which array elements an update should apply. */
  8219. arrayFilters?: Document[];
  8220. /** Specifies a collation. */
  8221. collation?: CollationOptions;
  8222. /** The index to use. If specified, then the query system will only consider plans using the hinted index. */
  8223. hint?: Hint;
  8224. /** When true, creates a new document if no document matches the query. */
  8225. upsert?: boolean;
  8226. /** Specifies the sort order for the documents matched by the filter. */
  8227. sort?: Sort;
  8228. }
  8229. /** @public */
  8230. export declare interface UpdateOptions extends CommandOperationOptions {
  8231. /** A set of filters specifying to which array elements an update should apply */
  8232. arrayFilters?: Document[];
  8233. /** If true, allows the write to opt-out of document level validation */
  8234. bypassDocumentValidation?: boolean;
  8235. /** Specifies a collation */
  8236. collation?: CollationOptions;
  8237. /** Specify that the update query should only consider plans using the hinted index */
  8238. hint?: Hint;
  8239. /** When true, creates a new document if no document matches the query */
  8240. upsert?: boolean;
  8241. /** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
  8242. let?: Document;
  8243. }
  8244. /**
  8245. * @public
  8246. * `TSchema` is the schema of the collection
  8247. */
  8248. export declare interface UpdateResult<TSchema extends Document = Document> {
  8249. /** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
  8250. acknowledged: boolean;
  8251. /** The number of documents that matched the filter */
  8252. matchedCount: number;
  8253. /** The number of documents that were modified */
  8254. modifiedCount: number;
  8255. /** The number of documents that were upserted */
  8256. upsertedCount: number;
  8257. /** The identifier of the inserted document if an upsert took place */
  8258. upsertedId: InferIdType<TSchema> | null;
  8259. }
  8260. /** @public */
  8261. export declare interface UpdateStatement {
  8262. /** The query that matches documents to update. */
  8263. q: Document;
  8264. /** The modifications to apply. */
  8265. u: Document | Document[];
  8266. /** If true, perform an insert if no documents match the query. */
  8267. upsert?: boolean;
  8268. /** If true, updates all documents that meet the query criteria. */
  8269. multi?: boolean;
  8270. /** Specifies the collation to use for the operation. */
  8271. collation?: CollationOptions;
  8272. /** An array of filter documents that determines which array elements to modify for an update operation on an array field. */
  8273. arrayFilters?: Document[];
  8274. /** A document or string that specifies the index to use to support the query predicate. */
  8275. hint?: Hint;
  8276. /** Specifies the sort order for the documents matched by the filter. */
  8277. sort?: SortForCmd;
  8278. }
  8279. export { UUID }
  8280. /** @public */
  8281. export declare interface ValidateCollectionOptions extends Omit<CommandOperationOptions, 'rawData'> {
  8282. /** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */
  8283. background?: boolean;
  8284. }
  8285. /** @public */
  8286. export declare type W = number | 'majority';
  8287. /* Excluded from this release type: WAITING_FOR_SUITABLE_SERVER */
  8288. /* Excluded from this release type: WaitingForSuitableServerEvent */
  8289. /* Excluded from this release type: WaitQueueMember */
  8290. /* Excluded from this release type: WithConnectionCallback */
  8291. /** Add an _id field to an object shaped type @public */
  8292. export declare type WithId<TSchema> = EnhancedOmit<TSchema, '_id'> & {
  8293. _id: InferIdType<TSchema>;
  8294. };
  8295. /** Remove the _id field from an object shaped type @public */
  8296. export declare type WithoutId<TSchema> = Omit<TSchema, '_id'>;
  8297. /** @public */
  8298. export declare type WithSessionCallback<T = unknown> = (session: ClientSession) => Promise<T>;
  8299. /** @public */
  8300. export declare type WithTransactionCallback<T = any> = (session: ClientSession) => Promise<T>;
  8301. /* Excluded from this release type: Workflow */
  8302. /**
  8303. * A MongoDB WriteConcern, which describes the level of acknowledgement
  8304. * requested from MongoDB for write operations.
  8305. * @public
  8306. *
  8307. * @see https://www.mongodb.com/docs/manual/reference/write-concern/
  8308. */
  8309. export declare class WriteConcern {
  8310. /**
  8311. * Request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
  8312. * If w is 0 and is set on a write operation, the server will not send a response.
  8313. */
  8314. readonly w?: W;
  8315. /** Request acknowledgment that the write operation has been written to the on-disk journal */
  8316. readonly journal?: boolean;
  8317. /**
  8318. * Specify a time limit to prevent write operations from blocking indefinitely.
  8319. */
  8320. readonly wtimeoutMS?: number;
  8321. /**
  8322. * Specify a time limit to prevent write operations from blocking indefinitely.
  8323. * @deprecated Will be removed in the next major version. Please use wtimeoutMS.
  8324. */
  8325. wtimeout?: number;
  8326. /**
  8327. * Request acknowledgment that the write operation has been written to the on-disk journal.
  8328. * @deprecated Will be removed in the next major version. Please use journal.
  8329. */
  8330. j?: boolean;
  8331. /**
  8332. * Equivalent to the j option.
  8333. * @deprecated Will be removed in the next major version. Please use journal.
  8334. */
  8335. fsync?: boolean | 1;
  8336. /**
  8337. * Constructs a WriteConcern from the write concern properties.
  8338. * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
  8339. * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely
  8340. * @param journal - request acknowledgment that the write operation has been written to the on-disk journal
  8341. * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version.
  8342. */
  8343. constructor(w?: W, wtimeoutMS?: number, journal?: boolean, fsync?: boolean | 1);
  8344. /**
  8345. * Apply a write concern to a command document. Will modify and return the command.
  8346. */
  8347. static apply(command: Document, writeConcern: WriteConcern): Document;
  8348. /** Construct a WriteConcern given an options object. */
  8349. static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined;
  8350. }
  8351. /**
  8352. * An error representing a failure by the server to apply the requested write concern to the bulk operation.
  8353. * @public
  8354. * @category Error
  8355. */
  8356. export declare class WriteConcernError {
  8357. /* Excluded from this release type: serverError */
  8358. constructor(error: WriteConcernErrorData);
  8359. /** Write concern error code. */
  8360. get code(): number | undefined;
  8361. /** Write concern error message. */
  8362. get errmsg(): string | undefined;
  8363. /** Write concern error info. */
  8364. get errInfo(): Document | undefined;
  8365. toJSON(): WriteConcernErrorData;
  8366. toString(): string;
  8367. }
  8368. /** @public */
  8369. export declare interface WriteConcernErrorData {
  8370. code: number;
  8371. errmsg: string;
  8372. errInfo?: Document;
  8373. }
  8374. /**
  8375. * The type of the result property of MongoWriteConcernError
  8376. * @public
  8377. */
  8378. export declare interface WriteConcernErrorResult {
  8379. writeConcernError: {
  8380. code: number;
  8381. errmsg: string;
  8382. codeName?: string;
  8383. errInfo?: Document;
  8384. };
  8385. ok: number;
  8386. code?: number;
  8387. errorLabels?: string[];
  8388. [x: string | number]: unknown;
  8389. }
  8390. /** @public */
  8391. export declare interface WriteConcernOptions {
  8392. /** Write Concern as an object */
  8393. writeConcern?: WriteConcern | WriteConcernSettings;
  8394. }
  8395. /** @public */
  8396. export declare interface WriteConcernSettings {
  8397. /** The write concern */
  8398. w?: W;
  8399. /**
  8400. * The write concern timeout.
  8401. */
  8402. wtimeoutMS?: number;
  8403. /** The journal write concern */
  8404. journal?: boolean;
  8405. /**
  8406. * The journal write concern.
  8407. * @deprecated Will be removed in the next major version. Please use the journal option.
  8408. */
  8409. j?: boolean;
  8410. /**
  8411. * The write concern timeout.
  8412. */
  8413. wtimeout?: number;
  8414. /**
  8415. * The file sync write concern.
  8416. * @deprecated Will be removed in the next major version. Please use the journal option.
  8417. */
  8418. fsync?: boolean | 1;
  8419. }
  8420. /**
  8421. * An error that occurred during a BulkWrite on the server.
  8422. * @public
  8423. * @category Error
  8424. */
  8425. export declare class WriteError {
  8426. err: BulkWriteOperationError;
  8427. constructor(err: BulkWriteOperationError);
  8428. /** WriteError code. */
  8429. get code(): number;
  8430. /** WriteError original bulk operation index. */
  8431. get index(): number;
  8432. /** WriteError message. */
  8433. get errmsg(): string | undefined;
  8434. /** WriteError details. */
  8435. get errInfo(): Document | undefined;
  8436. /** Returns the underlying operation that caused the error */
  8437. getOperation(): Document;
  8438. toJSON(): {
  8439. code: number;
  8440. index: number;
  8441. errmsg?: string;
  8442. op: Document;
  8443. };
  8444. toString(): string;
  8445. }
  8446. /* Excluded from this release type: WriteProtocolMessageType */
  8447. export { }