UNPKG

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