UNPKG

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