UNPKG

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