mongodb.d.ts 276 KB

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