declare namespace mongodb {
	/**
	 * A class representation of the BSON Binary type.
	 * @public
	 * @category BSONType
	 */
	class Binary extends BSONValue {
		get _bsontype(): "Binary";
		/* Excluded from this release type: BSON_BINARY_SUBTYPE_DEFAULT */
		/** Initial buffer default size */
		static readonly BUFFER_SIZE = 256;
		/** Default BSON type */
		static readonly SUBTYPE_DEFAULT = 0;
		/** Function BSON type */
		static readonly SUBTYPE_FUNCTION = 1;
		/** Byte Array BSON type */
		static readonly SUBTYPE_BYTE_ARRAY = 2;
		/** Deprecated UUID BSON type @deprecated Please use SUBTYPE_UUID */
		static readonly SUBTYPE_UUID_OLD = 3;
		/** UUID BSON type */
		static readonly SUBTYPE_UUID = 4;
		/** MD5 BSON type */
		static readonly SUBTYPE_MD5 = 5;
		/** Encrypted BSON type */
		static readonly SUBTYPE_ENCRYPTED = 6;
		/** Column BSON type */
		static readonly SUBTYPE_COLUMN = 7;
		/** Sensitive BSON type */
		static readonly SUBTYPE_SENSITIVE = 8;
		/** Vector BSON type */
		static readonly SUBTYPE_VECTOR = 9;
		/** User BSON type */
		static readonly SUBTYPE_USER_DEFINED = 128;
		/** datatype of a Binary Vector (subtype: 9) */
		static readonly VECTOR_TYPE: Readonly<{
			readonly Int8: 3;
			readonly Float32: 39;
			readonly PackedBit: 16;
		}>;
		/**
		 * The bytes of the Binary value.
		 *
		 * The format of a Binary value in BSON is defined as:
		 * ```txt
		 * binary	::= int32 subtype (byte*)
		 * ```
		 *
		 * This `buffer` is the "(byte*)" segment.
		 *
		 * Unless the value is subtype 2, then deserialize will read the first 4 bytes as an int32 and set this to the remaining bytes.
		 *
		 * ```txt
		 * binary	::= int32 unsigned_byte(2) int32 (byte*)
		 * ```
		 *
		 * @see https://bsonspec.org/spec.html
		 */
		buffer: Uint8Array;
		/**
		 * The binary subtype.
		 *
		 * Current defined values are:
		 *
		 * - `unsigned_byte(0)` Generic binary subtype
		 * - `unsigned_byte(1)` Function
		 * - `unsigned_byte(2)` Binary (Deprecated)
		 * - `unsigned_byte(3)` UUID (Deprecated)
		 * - `unsigned_byte(4)` UUID
		 * - `unsigned_byte(5)` MD5
		 * - `unsigned_byte(6)` Encrypted BSON value
		 * - `unsigned_byte(7)` Compressed BSON column
		 * - `unsigned_byte(8)` Sensitive
		 * - `unsigned_byte(9)` Vector
		 * - `unsigned_byte(128)` - `unsigned_byte(255)` User defined
		 */
		sub_type: number;
		/**
		 * The Binary's `buffer` can be larger than the Binary's content.
		 * This property is used to determine where the content ends in the buffer.
		 */
		position: number;
		/**
		 * Create a new Binary instance.
		 * @param buffer - a buffer object containing the binary data.
		 * @param subType - the option binary type.
		 */
		constructor(buffer?: BinarySequence, subType?: number);
		/**
		 * Updates this binary with byte_value.
		 *
		 * @param byteValue - a single byte we wish to write.
		 */
		put(byteValue: string | number | Uint8Array | number[]): void;
		/**
		 * Writes a buffer to the binary.
		 *
		 * @param sequence - a string or buffer to be written to the Binary BSON object.
		 * @param offset - specify the binary of where to write the content.
		 */
		write(sequence: BinarySequence, offset: number): void;
		/**
		 * Returns a view of **length** bytes starting at **position**.
		 *
		 * @param position - read from the given position in the Binary.
		 * @param length - the number of bytes to read.
		 */
		read(position: number, length: number): Uint8Array;
		/** returns a view of the binary value as a Uint8Array */
		value(): Uint8Array;
		/** the length of the binary sequence */
		length(): number;
		toJSON(): string;
		toString(encoding?: "hex" | "base64" | "utf8" | "utf-8"): string;
		/* Excluded from this release type: toExtendedJSON */
		toUUID(): UUID;
		/** Creates an Binary instance from a hex digit string */
		static createFromHexString(hex: string, subType?: number): Binary;
		/** Creates an Binary instance from a base64 string */
		static createFromBase64(base64: string, subType?: number): Binary;
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
		/**
		 * If this Binary represents a Int8 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Int8`),
		 * returns a copy of the bytes in a new Int8Array.
		 *
		 * If the Binary is not a Vector, or the datatype is not Int8, an error is thrown.
		 */
		toInt8Array(): Int8Array;
		/**
		 * If this Binary represents a Float32 Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.Float32`),
		 * returns a copy of the bytes in a new Float32Array.
		 *
		 * If the Binary is not a Vector, or the datatype is not Float32, an error is thrown.
		 */
		toFloat32Array(): Float32Array;
		/**
		 * If this Binary represents packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
		 * returns a copy of the bytes that are packed bits.
		 *
		 * Use `toBits` to get the unpacked bits.
		 *
		 * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
		 */
		toPackedBits(): Uint8Array;
		/**
		 * If this Binary represents a Packed bit Vector (`binary.buffer[0] === Binary.VECTOR_TYPE.PackedBit`),
		 * returns a copy of the bit unpacked into a new Int8Array.
		 *
		 * Use `toPackedBits` to get the bits still in packed form.
		 *
		 * If the Binary is not a Vector, or the datatype is not PackedBit, an error is thrown.
		 */
		toBits(): Int8Array;
		/**
		 * Constructs a Binary representing an Int8 Vector.
		 * @param array - The array to store as a view on the Binary class
		 */
		static fromInt8Array(array: Int8Array): Binary;
		/** Constructs a Binary representing an Float32 Vector. */
		static fromFloat32Array(array: Float32Array): Binary;
		/**
		 * Constructs a Binary representing a packed bit Vector.
		 *
		 * Use `fromBits` to pack an array of 1s and 0s.
		 */
		static fromPackedBits(array: Uint8Array, padding?: number): Binary;
		/**
		 * Constructs a Binary representing an Packed Bit Vector.
		 * @param array - The array of 1s and 0s to pack into the Binary instance
		 */
		static fromBits(bits: ArrayLike<number>): Binary;
	}

	/** @public */
	interface BinaryExtended {
		$binary: {
			subType: string;
			base64: string;
		};
	}

	/** @public */
	interface BinaryExtendedLegacy {
		$type: string;
		$binary: string;
	}

	/** @public */
	type BinarySequence = Uint8Array | number[];

	/* Excluded from this release type: BSON_MAJOR_VERSION */

	/* Excluded from this release type: BSON_VERSION_SYMBOL */

	/**
	 * @public
	 * @experimental
	 */
	type BSONElement = [type: number, nameOffset: number, nameLength: number, offset: number, length: number];

	/**
	 * @public
	 * @category Error
	 *
	 * `BSONError` objects are thrown when BSON encounters an error.
	 *
	 * This is the parent class for all the other errors thrown by this library.
	 */
	class BSONError extends Error {
		/* Excluded from this release type: bsonError */
		get name(): string;
		constructor(
			message: string,
			options?: {
				cause?: unknown;
			}
		);
		/**
		 * @public
		 *
		 * All errors thrown from the BSON library inherit from `BSONError`.
		 * This method can assist with determining if an error originates from the BSON library
		 * even if it does not pass an `instanceof` check against this class' constructor.
		 *
		 * @param value - any javascript value that needs type checking
		 */
		static isBSONError(value: unknown): value is BSONError;
	}

	/**
	 * @public
	 * @category Error
	 *
	 * @experimental
	 *
	 * An error generated when BSON bytes are invalid.
	 * Reports the offset the parser was able to reach before encountering the error.
	 */
	class BSONOffsetError extends BSONError {
		get name(): "BSONOffsetError";
		offset: number;
		constructor(
			message: string,
			offset: number,
			options?: {
				cause?: unknown;
			}
		);
	}

	/**
	 * A class representation of the BSON RegExp type.
	 * @public
	 * @category BSONType
	 */
	class BSONRegExp extends BSONValue {
		get _bsontype(): "BSONRegExp";
		pattern: string;
		options: string;
		/**
		 * @param pattern - The regular expression pattern to match
		 * @param options - The regular expression options
		 */
		constructor(pattern: string, options?: string);
		static parseOptions(options?: string): string;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface BSONRegExpExtended {
		$regularExpression: {
			pattern: string;
			options: string;
		};
	}

	/** @public */
	interface BSONRegExpExtendedLegacy {
		$regex: string | BSONRegExp;
		$options: string;
	}

	/**
	 * @public
	 * @category Error
	 *
	 * An error generated when BSON functions encounter an unexpected input
	 * or reaches an unexpected/invalid internal state
	 *
	 */
	class BSONRuntimeError extends BSONError {
		get name(): "BSONRuntimeError";
		constructor(message: string);
	}

	/**
	 * A class representation of the BSON Symbol type.
	 * @public
	 * @category BSONType
	 */
	class BSONSymbol extends BSONValue {
		get _bsontype(): "BSONSymbol";
		value: string;
		/**
		 * @param value - the string representing the symbol.
		 */
		constructor(value: string);
		/** Access the wrapped string value. */
		valueOf(): string;
		toString(): string;
		toJSON(): string;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface BSONSymbolExtended {
		$symbol: string;
	}

	/** @public */
	const BSONType: Readonly<{
		readonly double: 1;
		readonly string: 2;
		readonly object: 3;
		readonly array: 4;
		readonly binData: 5;
		readonly undefined: 6;
		readonly objectId: 7;
		readonly bool: 8;
		readonly date: 9;
		readonly null: 10;
		readonly regex: 11;
		readonly dbPointer: 12;
		readonly javascript: 13;
		readonly symbol: 14;
		readonly javascriptWithScope: 15;
		readonly int: 16;
		readonly timestamp: 17;
		readonly long: 18;
		readonly decimal: 19;
		readonly minKey: -1;
		readonly maxKey: 127;
	}>;

	/** @public */
	type BSONType = (typeof BSONType)[keyof typeof BSONType];

	/** @public */
	abstract class BSONValue {
		/** @public */
		abstract get _bsontype(): string;
		/* Excluded from this release type: [BSON_VERSION_SYMBOL] */
		/**
		 * @public
		 * Prints a human-readable string of BSON value information
		 * If invoked manually without node.js.inspect function, this will default to a modified JSON.stringify
		 */
		abstract inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
		/* Excluded from this release type: toExtendedJSON */
	}

	/**
	 * @public
	 * @category Error
	 */
	class BSONVersionError extends BSONError {
		get name(): "BSONVersionError";
		constructor();
	}

	/**
	 * @public
	 * @experimental
	 *
	 * A collection of functions that help work with data in a Uint8Array.
	 * ByteUtils is configured at load time to use Node.js or Web based APIs for the internal implementations.
	 */
	type ByteUtils = {
		/** Transforms the input to an instance of Buffer if running on node, otherwise Uint8Array */
		toLocalBufferType: (buffer: Uint8Array | ArrayBufferView | ArrayBuffer) => Uint8Array;
		/** Create empty space of size */
		allocate: (size: number) => Uint8Array;
		/** Create empty space of size, use pooled memory when available */
		allocateUnsafe: (size: number) => Uint8Array;
		/** Check if two Uint8Arrays are deep equal */
		equals: (a: Uint8Array, b: Uint8Array) => boolean;
		/** Check if two Uint8Arrays are deep equal */
		fromNumberArray: (array: number[]) => Uint8Array;
		/** Create a Uint8Array from a base64 string */
		fromBase64: (base64: string) => Uint8Array;
		/** Create a base64 string from bytes */
		toBase64: (buffer: Uint8Array) => string;
		/** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
		fromISO88591: (codePoints: string) => Uint8Array;
		/** **Legacy** binary strings are an outdated method of data transfer. Do not add public API support for interpreting this format */
		toISO88591: (buffer: Uint8Array) => string;
		/** Create a Uint8Array from a hex string */
		fromHex: (hex: string) => Uint8Array;
		/** Create a lowercase hex string from bytes */
		toHex: (buffer: Uint8Array) => string;
		/** Create a string from utf8 code units, fatal=true will throw an error if UTF-8 bytes are invalid, fatal=false will insert replacement characters */
		toUTF8: (buffer: Uint8Array, start: number, end: number, fatal: boolean) => string;
		/** Get the utf8 code unit count from a string if it were to be transformed to utf8 */
		utf8ByteLength: (input: string) => number;
		/** Encode UTF8 bytes generated from `source` string into `destination` at byteOffset. Returns the number of bytes encoded. */
		encodeUTF8Into: (destination: Uint8Array, source: string, byteOffset: number) => number;
		/** Generate a Uint8Array filled with random bytes with byteLength */
		randomBytes: (byteLength: number) => Uint8Array;
		/** Interprets `buffer` as an array of 32-bit values and swaps the byte order in-place. */
		swap32: (buffer: Uint8Array) => Uint8Array;
	};

	/* Excluded declaration from this release type: ByteUtils */

	/**
	 * Calculate the bson size for a passed in Javascript object.
	 *
	 * @param object - the Javascript object to calculate the BSON byte size for
	 * @returns size of BSON object in bytes
	 * @public
	 */
	function calculateObjectSize(object: Document, options?: CalculateObjectSizeOptions): number;

	/** @public */
	type CalculateObjectSizeOptions = Pick<SerializeOptions, "serializeFunctions" | "ignoreUndefined">;

	/**
	 * A class representation of the BSON Code type.
	 * @public
	 * @category BSONType
	 */
	class Code extends BSONValue {
		get _bsontype(): "Code";
		code: string;
		scope: Document | null;
		/**
		 * @param code - a string or function.
		 * @param scope - an optional scope for the function.
		 */
		constructor(code: string | Function, scope?: Document | null);
		toJSON(): {
			code: string;
			scope?: Document;
		};
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface CodeExtended {
		$code: string;
		$scope?: Document;
	}

	/**
	 * A class representation of the BSON DBRef type.
	 * @public
	 * @category BSONType
	 */
	class DBRef extends BSONValue {
		get _bsontype(): "DBRef";
		collection: string;
		oid: ObjectId;
		db?: string;
		fields: Document;
		/**
		 * @param collection - the collection name.
		 * @param oid - the reference ObjectId.
		 * @param db - optional db name, if omitted the reference is local to the current db.
		 */
		constructor(collection: string, oid: ObjectId, db?: string, fields?: Document);
		/* Excluded from this release type: namespace */
		/* Excluded from this release type: namespace */
		toJSON(): DBRefLike & Document;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface DBRefLike {
		$ref: string;
		$id: ObjectId;
		$db?: string;
	}

	/**
	 * A class representation of the BSON Decimal128 type.
	 * @public
	 * @category BSONType
	 */
	class Decimal128 extends BSONValue {
		get _bsontype(): "Decimal128";
		readonly bytes: Uint8Array;
		/**
		 * @param bytes - a buffer containing the raw Decimal128 bytes in little endian order,
		 *                or a string representation as returned by .toString()
		 */
		constructor(bytes: Uint8Array | string);
		/**
		 * Create a Decimal128 instance from a string representation
		 *
		 * @param representation - a numeric string representation.
		 */
		static fromString(representation: string): Decimal128;
		/**
		 * Create a Decimal128 instance from a string representation, allowing for rounding to 34
		 * significant digits
		 *
		 * @example Example of a number that will be rounded
		 * ```ts
		 * > let d = Decimal128.fromString('37.499999999999999196428571428571375')
		 * Uncaught:
		 * BSONError: "37.499999999999999196428571428571375" is not a valid Decimal128 string - inexact rounding
		 * at invalidErr (/home/wajames/js-bson/lib/bson.cjs:1402:11)
		 * at Decimal128.fromStringInternal (/home/wajames/js-bson/lib/bson.cjs:1633:25)
		 * at Decimal128.fromString (/home/wajames/js-bson/lib/bson.cjs:1424:27)
		 *
		 * > d = Decimal128.fromStringWithRounding('37.499999999999999196428571428571375')
		 * new Decimal128("37.49999999999999919642857142857138")
		 * ```
		 * @param representation - a numeric string representation.
		 */
		static fromStringWithRounding(representation: string): Decimal128;
		private static _fromString;
		/** Create a string representation of the raw Decimal128 value */
		toString(): string;
		toJSON(): Decimal128Extended;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface Decimal128Extended {
		$numberDecimal: string;
	}

	/**
	 * Deserialize data as BSON.
	 *
	 * @param buffer - the buffer containing the serialized set of BSON documents.
	 * @returns returns the deserialized Javascript Object.
	 * @public
	 */
	function deserialize(buffer: Uint8Array, options?: DeserializeOptions): Document;

	/** @public */
	interface DeserializeOptions {
		/**
		 * when deserializing a Long return as a BigInt.
		 * @defaultValue `false`
		 */
		useBigInt64?: boolean;
		/**
		 * when deserializing a Long will fit it into a Number if it's smaller than 53 bits.
		 * @defaultValue `true`
		 */
		promoteLongs?: boolean;
		/**
		 * when deserializing a Binary will return it as a node.js Buffer instance.
		 * @defaultValue `false`
		 */
		promoteBuffers?: boolean;
		/**
		 * when deserializing will promote BSON values to their Node.js closest equivalent types.
		 * @defaultValue `true`
		 */
		promoteValues?: boolean;
		/**
		 * allow to specify if there what fields we wish to return as unserialized raw buffer.
		 * @defaultValue `null`
		 */
		fieldsAsRaw?: Document;
		/**
		 * return BSON regular expressions as BSONRegExp instances.
		 * @defaultValue `false`
		 */
		bsonRegExp?: boolean;
		/**
		 * allows the buffer to be larger than the parsed BSON object.
		 * @defaultValue `false`
		 */
		allowObjectSmallerThanBufferSize?: boolean;
		/**
		 * Offset into buffer to begin reading document from
		 * @defaultValue `0`
		 */
		index?: number;
		raw?: boolean;
		/** Allows for opt-out utf-8 validation for all keys or
		 * specified keys. Must be all true or all false.
		 *
		 * @example
		 * ```js
		 * // disables validation on all keys
		 *  validation: { utf8: false }
		 *
		 * // enables validation only on specified keys a, b, and c
		 *  validation: { utf8: { a: true, b: true, c: true } }
		 *
		 *  // disables validation only on specified keys a, b
		 *  validation: { utf8: { a: false, b: false } }
		 * ```
		 */
		validation?: {
			utf8: boolean | Record<string, true> | Record<string, false>;
		};
	}

	/**
	 * Deserialize stream data as BSON documents.
	 *
	 * @param data - the buffer containing the serialized set of BSON documents.
	 * @param startIndex - the start index in the data Buffer where the deserialization is to start.
	 * @param numberOfDocuments - number of documents to deserialize.
	 * @param documents - an array where to store the deserialized documents.
	 * @param docStartIndex - the index in the documents array from where to start inserting documents.
	 * @param options - additional options used for the deserialization.
	 * @returns next index in the buffer after deserialization **x** numbers of documents.
	 * @public
	 */
	function deserializeStream(data: Uint8Array | ArrayBuffer, startIndex: number, numberOfDocuments: number, documents: Document[], docStartIndex: number, options: DeserializeOptions): number;

	/** @public */
	interface Document {
		[key: string]: any;
	}

	/**
	 * A class representation of the BSON Double type.
	 * @public
	 * @category BSONType
	 */
	class Double extends BSONValue {
		get _bsontype(): "Double";
		value: number;
		/**
		 * Create a Double type
		 *
		 * @param value - the number we want to represent as a double.
		 */
		constructor(value: number);
		/**
		 * Attempt to create an double type from string.
		 *
		 * This method will throw a BSONError on any string input that is not representable as a IEEE-754 64-bit double.
		 * Notably, this method will also throw on the following string formats:
		 * - Strings in non-decimal and non-exponential formats (binary, hex, or octal digits)
		 * - Strings with characters other than numeric, floating point, or leading sign characters (Note: 'Infinity', '-Infinity', and 'NaN' input strings are still allowed)
		 * - Strings with leading and/or trailing whitespace
		 *
		 * Strings with leading zeros, however, are also allowed
		 *
		 * @param value - the string we want to represent as a double.
		 */
		static fromString(value: string): Double;
		/**
		 * Access the number value.
		 *
		 * @returns returns the wrapped double number.
		 */
		valueOf(): number;
		toJSON(): number;
		toString(radix?: number): string;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface DoubleExtended {
		$numberDouble: string;
	}

	/** @public */
	const EJSON: {
		parse: typeof parse;
		stringify: typeof stringify;
		serialize: typeof EJSONserialize;
		deserialize: typeof EJSONdeserialize;
	};

	/**
	 * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
	 *
	 * @param ejson - The Extended JSON object to deserialize
	 * @param options - Optional settings passed to the parse method
	 */
	function EJSONdeserialize(ejson: Document, options?: EJSONOptions): any;

	/** @public */
	type EJSONOptions = {
		/**
		 * Output using the Extended JSON v1 spec
		 * @defaultValue `false`
		 */
		legacy?: boolean;
		/**
		 * Enable Extended JSON's `relaxed` mode, which attempts to return native JS types where possible, rather than BSON types
		 * @defaultValue `false` */
		relaxed?: boolean;
		/**
		 * Enable native bigint support
		 * @defaultValue `false`
		 */
		useBigInt64?: boolean;
	};

	/**
	 * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
	 *
	 * @param value - The object to serialize
	 * @param options - Optional settings passed to the `stringify` function
	 */
	function EJSONserialize(value: any, options?: EJSONOptions): Document;

	type InspectFn = (x: unknown, options?: unknown) => string;

	/**
	 * A class representation of a BSON Int32 type.
	 * @public
	 * @category BSONType
	 */
	class Int32 extends BSONValue {
		get _bsontype(): "Int32";
		value: number;
		/**
		 * Create an Int32 type
		 *
		 * @param value - the number we want to represent as an int32.
		 */
		constructor(value: number | string);
		/**
		 * Attempt to create an Int32 type from string.
		 *
		 * This method will throw a BSONError on any string input that is not representable as an Int32.
		 * Notably, this method will also throw on the following string formats:
		 * - Strings in non-decimal formats (exponent notation, binary, hex, or octal digits)
		 * - Strings non-numeric and non-leading sign characters (ex: '2.0', '24,000')
		 * - Strings with leading and/or trailing whitespace
		 *
		 * Strings with leading zeros, however, are allowed.
		 *
		 * @param value - the string we want to represent as an int32.
		 */
		static fromString(value: string): Int32;
		/**
		 * Access the number value.
		 *
		 * @returns returns the wrapped int32 number.
		 */
		valueOf(): number;
		toString(radix?: number): string;
		toJSON(): number;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface Int32Extended {
		$numberInt: string;
	}

	/**
	 * A class representing a 64-bit integer
	 * @public
	 * @category BSONType
	 * @remarks
	 * The internal representation of a long is the two given signed, 32-bit values.
	 * We use 32-bit pieces because these are the size of integers on which
	 * Javascript performs bit-operations.  For operations like addition and
	 * multiplication, we split each number into 16 bit pieces, which can easily be
	 * multiplied within Javascript's floating-point representation without overflow
	 * or change in sign.
	 * In the algorithms below, we frequently reduce the negative case to the
	 * positive case by negating the input(s) and then post-processing the result.
	 * Note that we must ALWAYS check specially whether those values are MIN_VALUE
	 * (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as
	 * a positive number, it overflows back into a negative).  Not handling this
	 * case would often result in infinite recursion.
	 * Common constant values ZERO, ONE, NEG_ONE, etc. are found as static properties on this class.
	 */
	class Long extends BSONValue {
		get _bsontype(): "Long";
		/** An indicator used to reliably determine if an object is a Long or not. */
		get __isLong__(): boolean;
		/**
		 * The high 32 bits as a signed value.
		 */
		high: number;
		/**
		 * The low 32 bits as a signed value.
		 */
		low: number;
		/**
		 * Whether unsigned or not.
		 */
		unsigned: boolean;
		/**
		 * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers.
		 *
		 * @param low - The low (signed) 32 bits of the long
		 * @param high - The high (signed) 32 bits of the long
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 */
		constructor(low: number, high?: number, unsigned?: boolean);
		/**
		 * Constructs a 64 bit two's-complement integer, given a bigint representation.
		 *
		 * @param value - BigInt representation of the long value
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 */
		constructor(value: bigint, unsigned?: boolean);
		/**
		 * Constructs a 64 bit two's-complement integer, given a string representation.
		 *
		 * @param value - String representation of the long value
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 */
		constructor(value: string, unsigned?: boolean);
		static TWO_PWR_24: Long;
		/** Maximum unsigned value. */
		static MAX_UNSIGNED_VALUE: Long;
		/** Signed zero */
		static ZERO: Long;
		/** Unsigned zero. */
		static UZERO: Long;
		/** Signed one. */
		static ONE: Long;
		/** Unsigned one. */
		static UONE: Long;
		/** Signed negative one. */
		static NEG_ONE: Long;
		/** Maximum signed value. */
		static MAX_VALUE: Long;
		/** Minimum signed value. */
		static MIN_VALUE: Long;
		/**
		 * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits.
		 * Each is assumed to use 32 bits.
		 * @param lowBits - The low 32 bits
		 * @param highBits - The high 32 bits
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromBits(lowBits: number, highBits: number, unsigned?: boolean): Long;
		/**
		 * Returns a Long representing the given 32 bit integer value.
		 * @param value - The 32 bit integer in question
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromInt(value: number, unsigned?: boolean): Long;
		/**
		 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
		 * @param value - The number in question
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromNumber(value: number, unsigned?: boolean): Long;
		/**
		 * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned.
		 * @param value - The number in question
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromBigInt(value: bigint, unsigned?: boolean): Long;
		/* Excluded from this release type: _fromString */
		/**
		 * Returns a signed Long representation of the given string, written using radix 10.
		 * Will throw an error if the given text is not exactly representable as a Long.
		 * Throws an error if any of the following conditions are true:
		 * - the string contains invalid characters for the radix 10
		 * - the string contains whitespace
		 * - the value the string represents is too large or too small to be a Long
		 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
		 * @param str - The textual representation of the Long
		 * @returns The corresponding Long value
		 */
		static fromStringStrict(str: string): Long;
		/**
		 * Returns a Long representation of the given string, written using the radix 10.
		 * Will throw an error if the given parameters are not exactly representable as a Long.
		 * Throws an error if any of the following conditions are true:
		 * - the string contains invalid characters for the given radix
		 * - the string contains whitespace
		 * - the value the string represents is too large or too small to be a Long
		 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
		 * @param str - The textual representation of the Long
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromStringStrict(str: string, unsigned?: boolean): Long;
		/**
		 * Returns a signed Long representation of the given string, written using the specified radix.
		 * Will throw an error if the given parameters are not exactly representable as a Long.
		 * Throws an error if any of the following conditions are true:
		 * - the string contains invalid characters for the given radix
		 * - the string contains whitespace
		 * - the value the string represents is too large or too small to be a Long
		 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
		 * @param str - The textual representation of the Long
		 * @param radix - The radix in which the text is written (2-36), defaults to 10
		 * @returns The corresponding Long value
		 */
		static fromStringStrict(str: string, radix?: boolean): Long;
		/**
		 * Returns a Long representation of the given string, written using the specified radix.
		 * Will throw an error if the given parameters are not exactly representable as a Long.
		 * Throws an error if any of the following conditions are true:
		 * - the string contains invalid characters for the given radix
		 * - the string contains whitespace
		 * - the value the string represents is too large or too small to be a Long
		 * Unlike Long.fromString, this method does not coerce '+/-Infinity' and 'NaN' to Long.Zero
		 * @param str - The textual representation of the Long
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @param radix - The radix in which the text is written (2-36), defaults to 10
		 * @returns The corresponding Long value
		 */
		static fromStringStrict(str: string, unsigned?: boolean, radix?: number): Long;
		/**
		 * Returns a signed Long representation of the given string, written using radix 10.
		 *
		 * If the input string is empty, this function will throw a BSONError.
		 *
		 * If input string does not have valid signed 64-bit Long representation, this method will return a coerced value:
		 * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
		 * - 'NaN' or '+/-Infinity' are coerced to Long.ZERO
		 * - other invalid characters sequences have variable behavior
		 *
		 * @param str - The textual representation of the Long
		 * @returns The corresponding Long value
		 */
		static fromString(str: string): Long;
		/**
		 * Returns a signed Long representation of the given string, written using the provided radix.
		 *
		 * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
		 *
		 * If input parameters do not have valid signed 64-bit Long representation, this method will return a coerced value:
		 * - inputs that overflow 64-bit signed long will be coerced to Long.MAX_VALUE and Long.MIN_VALUE respectively
		 * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
		 * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
		 * - other invalid characters sequences have variable behavior
		 * @param str - The textual representation of the Long
		 * @param radix - The radix in which the text is written (2-36), defaults to 10
		 * @returns The corresponding Long value
		 */
		static fromString(str: string, radix?: number): Long;
		/**
		 * Returns a Long representation of the given string, written using radix 10.
		 *
		 * If the input string is empty, this function will throw a BSONError.
		 *
		 * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
		 * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
		 * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
		 * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
		 * - other invalid characters sequences have variable behavior
		 * @param str - The textual representation of the Long
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromString(str: string, unsigned?: boolean): Long;
		/**
		 * Returns a Long representation of the given string, written using the specified radix.
		 *
		 * If the input string is empty or a provided radix is not within (2-36), this function will throw a BSONError.
		 *
		 * If input parameters do not have a valid 64-bit Long representation, this method will return a coerced value:
		 * - inputs that overflow 64-bit long will be coerced to max or min (if signed) values
		 * - if the radix is less than 24, 'NaN' is coerced to Long.ZERO
		 * - if the radix is less than 35, '+/-Infinity' inputs are coerced to Long.ZERO
		 * - other invalid characters sequences have variable behavior
		 * @param str - The textual representation of the Long
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @param radix - The radix in which the text is written (2-36), defaults to 10
		 * @returns The corresponding Long value
		 */
		static fromString(str: string, unsigned?: boolean, radix?: number): Long;
		/**
		 * Creates a Long from its byte representation.
		 * @param bytes - Byte representation
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @param le - Whether little or big endian, defaults to big endian
		 * @returns The corresponding Long value
		 */
		static fromBytes(bytes: number[], unsigned?: boolean, le?: boolean): Long;
		/**
		 * Creates a Long from its little endian byte representation.
		 * @param bytes - Little endian byte representation
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromBytesLE(bytes: number[], unsigned?: boolean): Long;
		/**
		 * Creates a Long from its big endian byte representation.
		 * @param bytes - Big endian byte representation
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 * @returns The corresponding Long value
		 */
		static fromBytesBE(bytes: number[], unsigned?: boolean): Long;
		/**
		 * Tests if the specified object is a Long.
		 */
		static isLong(value: unknown): value is Long;
		/**
		 * Converts the specified value to a Long.
		 * @param unsigned - Whether unsigned or not, defaults to signed
		 */
		static fromValue(
			val:
				| number
				| string
				| {
						low: number;
						high: number;
						unsigned?: boolean;
				  },
			unsigned?: boolean
		): Long;
		/** Returns the sum of this and the specified Long. */
		add(addend: string | number | Long | Timestamp): Long;
		/**
		 * Returns the sum of this and the specified Long.
		 * @returns Sum
		 */
		and(other: string | number | Long | Timestamp): Long;
		/**
		 * Compares this Long's value with the specified's.
		 * @returns 0 if they are the same, 1 if the this is greater and -1 if the given one is greater
		 */
		compare(other: string | number | Long | Timestamp): 0 | 1 | -1;
		/** This is an alias of {@link Long.compare} */
		comp(other: string | number | Long | Timestamp): 0 | 1 | -1;
		/**
		 * Returns this Long divided by the specified. The result is signed if this Long is signed or unsigned if this Long is unsigned.
		 * @returns Quotient
		 */
		divide(divisor: string | number | Long | Timestamp): Long;
		/**This is an alias of {@link Long.divide} */
		div(divisor: string | number | Long | Timestamp): Long;
		/**
		 * Tests if this Long's value equals the specified's.
		 * @param other - Other value
		 */
		equals(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.equals} */
		eq(other: string | number | Long | Timestamp): boolean;
		/** Gets the high 32 bits as a signed integer. */
		getHighBits(): number;
		/** Gets the high 32 bits as an unsigned integer. */
		getHighBitsUnsigned(): number;
		/** Gets the low 32 bits as a signed integer. */
		getLowBits(): number;
		/** Gets the low 32 bits as an unsigned integer. */
		getLowBitsUnsigned(): number;
		/** Gets the number of bits needed to represent the absolute value of this Long. */
		getNumBitsAbs(): number;
		/** Tests if this Long's value is greater than the specified's. */
		greaterThan(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.greaterThan} */
		gt(other: string | number | Long | Timestamp): boolean;
		/** Tests if this Long's value is greater than or equal the specified's. */
		greaterThanOrEqual(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.greaterThanOrEqual} */
		gte(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.greaterThanOrEqual} */
		ge(other: string | number | Long | Timestamp): boolean;
		/** Tests if this Long's value is even. */
		isEven(): boolean;
		/** Tests if this Long's value is negative. */
		isNegative(): boolean;
		/** Tests if this Long's value is odd. */
		isOdd(): boolean;
		/** Tests if this Long's value is positive. */
		isPositive(): boolean;
		/** Tests if this Long's value equals zero. */
		isZero(): boolean;
		/** Tests if this Long's value is less than the specified's. */
		lessThan(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long#lessThan}. */
		lt(other: string | number | Long | Timestamp): boolean;
		/** Tests if this Long's value is less than or equal the specified's. */
		lessThanOrEqual(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.lessThanOrEqual} */
		lte(other: string | number | Long | Timestamp): boolean;
		/** Returns this Long modulo the specified. */
		modulo(divisor: string | number | Long | Timestamp): Long;
		/** This is an alias of {@link Long.modulo} */
		mod(divisor: string | number | Long | Timestamp): Long;
		/** This is an alias of {@link Long.modulo} */
		rem(divisor: string | number | Long | Timestamp): Long;
		/**
		 * Returns the product of this and the specified Long.
		 * @param multiplier - Multiplier
		 * @returns Product
		 */
		multiply(multiplier: string | number | Long | Timestamp): Long;
		/** This is an alias of {@link Long.multiply} */
		mul(multiplier: string | number | Long | Timestamp): Long;
		/** Returns the Negation of this Long's value. */
		negate(): Long;
		/** This is an alias of {@link Long.negate} */
		neg(): Long;
		/** Returns the bitwise NOT of this Long. */
		not(): Long;
		/** Tests if this Long's value differs from the specified's. */
		notEquals(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.notEquals} */
		neq(other: string | number | Long | Timestamp): boolean;
		/** This is an alias of {@link Long.notEquals} */
		ne(other: string | number | Long | Timestamp): boolean;
		/**
		 * Returns the bitwise OR of this Long and the specified.
		 */
		or(other: number | string | Long): Long;
		/**
		 * Returns this Long with bits shifted to the left by the given amount.
		 * @param numBits - Number of bits
		 * @returns Shifted Long
		 */
		shiftLeft(numBits: number | Long): Long;
		/** This is an alias of {@link Long.shiftLeft} */
		shl(numBits: number | Long): Long;
		/**
		 * Returns this Long with bits arithmetically shifted to the right by the given amount.
		 * @param numBits - Number of bits
		 * @returns Shifted Long
		 */
		shiftRight(numBits: number | Long): Long;
		/** This is an alias of {@link Long.shiftRight} */
		shr(numBits: number | Long): Long;
		/**
		 * Returns this Long with bits logically shifted to the right by the given amount.
		 * @param numBits - Number of bits
		 * @returns Shifted Long
		 */
		shiftRightUnsigned(numBits: Long | number): Long;
		/** This is an alias of {@link Long.shiftRightUnsigned} */
		shr_u(numBits: number | Long): Long;
		/** This is an alias of {@link Long.shiftRightUnsigned} */
		shru(numBits: number | Long): Long;
		/**
		 * Returns the difference of this and the specified Long.
		 * @param subtrahend - Subtrahend
		 * @returns Difference
		 */
		subtract(subtrahend: string | number | Long | Timestamp): Long;
		/** This is an alias of {@link Long.subtract} */
		sub(subtrahend: string | number | Long | Timestamp): Long;
		/** Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. */
		toInt(): number;
		/** Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). */
		toNumber(): number;
		/** Converts the Long to a BigInt (arbitrary precision). */
		toBigInt(): bigint;
		/**
		 * Converts this Long to its byte representation.
		 * @param le - Whether little or big endian, defaults to big endian
		 * @returns Byte representation
		 */
		toBytes(le?: boolean): number[];
		/**
		 * Converts this Long to its little endian byte representation.
		 * @returns Little endian byte representation
		 */
		toBytesLE(): number[];
		/**
		 * Converts this Long to its big endian byte representation.
		 * @returns Big endian byte representation
		 */
		toBytesBE(): number[];
		/**
		 * Converts this Long to signed.
		 */
		toSigned(): Long;
		/**
		 * Converts the Long to a string written in the specified radix.
		 * @param radix - Radix (2-36), defaults to 10
		 * @throws RangeError If `radix` is out of range
		 */
		toString(radix?: number): string;
		/** Converts this Long to unsigned. */
		toUnsigned(): Long;
		/** Returns the bitwise XOR of this Long and the given one. */
		xor(other: Long | number | string): Long;
		/** This is an alias of {@link Long.isZero} */
		eqz(): boolean;
		/** This is an alias of {@link Long.lessThanOrEqual} */
		le(other: string | number | Long | Timestamp): boolean;
		toExtendedJSON(options?: EJSONOptions): number | LongExtended;
		static fromExtendedJSON(
			doc: {
				$numberLong: string;
			},
			options?: EJSONOptions
		): number | Long | bigint;
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface LongExtended {
		$numberLong: string;
	}

	/** @public */
	type LongWithoutOverrides = new (low: unknown, high?: number | boolean, unsigned?: boolean) => {
		[P in Exclude<keyof Long, TimestampOverrides>]: Long[P];
	};

	/** @public */
	const LongWithoutOverridesClass: LongWithoutOverrides;

	/**
	 * A class representation of the BSON MaxKey type.
	 * @public
	 * @category BSONType
	 */
	class MaxKey extends BSONValue {
		get _bsontype(): "MaxKey";
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(): string;
	}

	/** @public */
	interface MaxKeyExtended {
		$maxKey: 1;
	}

	/**
	 * A class representation of the BSON MinKey type.
	 * @public
	 * @category BSONType
	 */
	class MinKey extends BSONValue {
		get _bsontype(): "MinKey";
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(): string;
	}

	/** @public */
	interface MinKeyExtended {
		$minKey: 1;
	}

	/**
	 * @experimental
	 * @public
	 *
	 * A collection of functions that get or set various numeric types and bit widths from a Uint8Array.
	 */
	type NumberUtils = {
		/** Is true if the current system is big endian. */
		isBigEndian: boolean;
		/**
		 * Parses a signed int32 at offset. Throws a `RangeError` if value is negative.
		 */
		getNonnegativeInt32LE: (source: Uint8Array, offset: number) => number;
		getInt32LE: (source: Uint8Array, offset: number) => number;
		getUint32LE: (source: Uint8Array, offset: number) => number;
		getUint32BE: (source: Uint8Array, offset: number) => number;
		getBigInt64LE: (source: Uint8Array, offset: number) => bigint;
		getFloat64LE: (source: Uint8Array, offset: number) => number;
		setInt32BE: (destination: Uint8Array, offset: number, value: number) => 4;
		setInt32LE: (destination: Uint8Array, offset: number, value: number) => 4;
		setBigInt64LE: (destination: Uint8Array, offset: number, value: bigint) => 8;
		setFloat64LE: (destination: Uint8Array, offset: number, value: number) => 8;
	};

	/**
	 * Number parsing and serializing utilities.
	 *
	 * @experimental
	 * @public
	 */
	const NumberUtils: NumberUtils;

	/**
	 * A class representation of the BSON ObjectId type.
	 * @public
	 * @category BSONType
	 */
	class ObjectId extends BSONValue {
		get _bsontype(): "ObjectId";
		/* Excluded from this release type: index */
		static cacheHexString: boolean;
		/* Excluded from this release type: buffer */
		/**
		 * Create ObjectId from a number.
		 *
		 * @param inputId - A number.
		 * @deprecated Instead, use `static createFromTime()` to set a numeric value for the new ObjectId.
		 */
		constructor(inputId: number);
		/**
		 * Create ObjectId from a 24 character hex string.
		 *
		 * @param inputId - A 24 character hex string.
		 */
		constructor(inputId: string);
		/**
		 * Create ObjectId from the BSON ObjectId type.
		 *
		 * @param inputId - The BSON ObjectId type.
		 */
		constructor(inputId: ObjectId);
		/**
		 * Create ObjectId from the object type that has the toHexString method.
		 *
		 * @param inputId - The ObjectIdLike type.
		 */
		constructor(inputId: ObjectIdLike);
		/**
		 * Create ObjectId from a 12 byte binary Buffer.
		 *
		 * @param inputId - A 12 byte binary Buffer.
		 */
		constructor(inputId: Uint8Array);
		/** To generate a new ObjectId, use ObjectId() with no argument. */
		constructor();
		/**
		 * Implementation overload.
		 *
		 * @param inputId - All input types that are used in the constructor implementation.
		 */
		constructor(inputId?: string | number | ObjectId | ObjectIdLike | Uint8Array);
		/**
		 * The ObjectId bytes
		 * @readonly
		 */
		get id(): Uint8Array;
		set id(value: Uint8Array);
		/* Excluded from this release type: validateHexString */
		/** Returns the ObjectId id as a 24 lowercase character hex string representation */
		toHexString(): string;
		/* Excluded from this release type: getInc */
		/**
		 * Generate a 12 byte id buffer used in ObjectId's
		 *
		 * @param time - pass in a second based timestamp.
		 */
		static generate(time?: number): Uint8Array;
		/**
		 * Converts the id into a 24 character hex string for printing, unless encoding is provided.
		 * @param encoding - hex or base64
		 */
		toString(encoding?: "hex" | "base64"): string;
		/** Converts to its JSON the 24 character hex string representation. */
		toJSON(): string;
		/* Excluded from this release type: is */
		/**
		 * Compares the equality of this ObjectId with `otherID`.
		 *
		 * @param otherId - ObjectId instance to compare against.
		 */
		equals(otherId: string | ObjectId | ObjectIdLike | undefined | null): boolean;
		/** Returns the generation date (accurate up to the second) that this ID was generated. */
		getTimestamp(): Date;
		/* Excluded from this release type: createPk */
		/* Excluded from this release type: serializeInto */
		/**
		 * Creates an ObjectId from a second based number, with the rest of the ObjectId zeroed out. Used for comparisons or sorting the ObjectId.
		 *
		 * @param time - an integer number representing a number of seconds.
		 */
		static createFromTime(time: number): ObjectId;
		/**
		 * Creates an ObjectId from a hex string representation of an ObjectId.
		 *
		 * @param hexString - create a ObjectId from a passed in 24 character hexstring.
		 */
		static createFromHexString(hexString: string): ObjectId;
		/** Creates an ObjectId instance from a base64 string */
		static createFromBase64(base64: string): ObjectId;
		/**
		 * Checks if a value can be used to create a valid bson ObjectId
		 * @param id - any JS value
		 */
		static isValid(id: string | number | ObjectId | ObjectIdLike | Uint8Array): boolean;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		/* Excluded from this release type: isCached */
		/**
		 * Converts to a string representation of this Id.
		 *
		 * @returns return the 24 character hex string representation.
		 */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface ObjectIdExtended {
		$oid: string;
	}

	/** @public */
	interface ObjectIdLike {
		id: string | Uint8Array;
		__id?: string;
		toHexString(): string;
	}

	/**
	 * @experimental
	 * @public
	 *
	 * A new set of BSON APIs that are currently experimental and not intended for production use.
	 */
	type OnDemand = {
		parseToElements: (this: void, bytes: Uint8Array, startOffset?: number) => Iterable<BSONElement>;
		BSONElement: BSONElement;
		ByteUtils: ByteUtils;
		NumberUtils: NumberUtils;
	};

	/**
	 * @experimental
	 * @public
	 */
	const onDemand: OnDemand;

	/**
	 * Parse an Extended JSON string, constructing the JavaScript value or object described by that
	 * string.
	 *
	 * @example
	 * ```js
	 * const { EJSON } = require('bson');
	 * const text = '{ "int32": { "$numberInt": "10" } }';
	 *
	 * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
	 * console.log(EJSON.parse(text, { relaxed: false }));
	 *
	 * // prints { int32: 10 }
	 * console.log(EJSON.parse(text));
	 * ```
	 */
	function parse(text: string, options?: EJSONOptions): any;

	/**
	 * Serialize a Javascript object.
	 *
	 * @param object - the Javascript object to serialize.
	 * @returns Buffer object containing the serialized object.
	 * @public
	 */
	function serialize(object: Document, options?: SerializeOptions): Uint8Array;

	/** @public */
	interface SerializeOptions {
		/**
		 * the serializer will check if keys are valid.
		 * @defaultValue `false`
		 */
		checkKeys?: boolean;
		/**
		 * serialize the javascript functions
		 * @defaultValue `false`
		 */
		serializeFunctions?: boolean;
		/**
		 * serialize will not emit undefined fields
		 * note that the driver sets this to `false`
		 * @defaultValue `true`
		 */
		ignoreUndefined?: boolean;
		/* Excluded from this release type: minInternalBufferSize */
		/**
		 * the index in the buffer where we wish to start serializing into
		 * @defaultValue `0`
		 */
		index?: number;
	}

	/**
	 * Serialize a Javascript object using a predefined Buffer and index into the buffer,
	 * useful when pre-allocating the space for serialization.
	 *
	 * @param object - the Javascript object to serialize.
	 * @param finalBuffer - the Buffer you pre-allocated to store the serialized BSON object.
	 * @returns the index pointing to the last written byte in the buffer.
	 * @public
	 */
	function serializeWithBufferAndIndex(object: Document, finalBuffer: Uint8Array, options?: SerializeOptions): number;

	/**
	 * Sets the size of the internal serialization buffer.
	 *
	 * @param size - The desired size for the internal serialization buffer in bytes
	 * @public
	 */
	function setInternalBufferSize(size: number): void;

	/**
	 * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
	 * function is specified or optionally including only the specified properties if a replacer array
	 * is specified.
	 *
	 * @param value - The value to convert to extended JSON
	 * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
	 * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
	 * @param options - Optional settings
	 *
	 * @example
	 * ```js
	 * const { EJSON } = require('bson');
	 * const Int32 = require('mongodb').Int32;
	 * const doc = { int32: new Int32(10) };
	 *
	 * // prints '{"int32":{"$numberInt":"10"}}'
	 * console.log(EJSON.stringify(doc, { relaxed: false }));
	 *
	 * // prints '{"int32":10}'
	 * console.log(EJSON.stringify(doc));
	 * ```
	 */
	function stringify(value: any, replacer?: (number | string)[] | ((this: any, key: string, value: any) => any) | EJSONOptions, space?: string | number, options?: EJSONOptions): string;

	/**
	 * @public
	 * @category BSONType
	 *
	 * A special type for _internal_ MongoDB use and is **not** associated with the regular Date type.
	 */
	class Timestamp extends LongWithoutOverridesClass {
		get _bsontype(): "Timestamp";
		static readonly MAX_VALUE: Long;
		/**
		 * An incrementing ordinal for operations within a given second.
		 */
		get i(): number;
		/**
		 * A `time_t` value measuring seconds since the Unix epoch
		 */
		get t(): number;
		/**
		 * @param int - A 64-bit bigint representing the Timestamp.
		 */
		constructor(int: bigint);
		/**
		 * @param long - A 64-bit Long representing the Timestamp.
		 */
		constructor(long: Long);
		/**
		 * @param value - A pair of two values indicating timestamp and increment.
		 */
		constructor(value: { t: number; i: number });
		toJSON(): {
			$timestamp: string;
		};
		/** Returns a Timestamp represented by the given (32-bit) integer value. */
		static fromInt(value: number): Timestamp;
		/** Returns a Timestamp representing the given number value, provided that it is a finite number. Otherwise, zero is returned. */
		static fromNumber(value: number): Timestamp;
		/**
		 * Returns a Timestamp for the given high and low bits. Each is assumed to use 32 bits.
		 *
		 * @param lowBits - the low 32-bits.
		 * @param highBits - the high 32-bits.
		 */
		static fromBits(lowBits: number, highBits: number): Timestamp;
		/**
		 * Returns a Timestamp from the given string, optionally using the given radix.
		 *
		 * @param str - the textual representation of the Timestamp.
		 * @param optRadix - the radix in which the text is written.
		 */
		static fromString(str: string, optRadix: number): Timestamp;
		/* Excluded from this release type: toExtendedJSON */
		/* Excluded from this release type: fromExtendedJSON */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	interface TimestampExtended {
		$timestamp: {
			t: number;
			i: number;
		};
	}

	/** @public */
	type TimestampOverrides = "_bsontype" | "toExtendedJSON" | "fromExtendedJSON" | "inspect";

	/**
	 * A class representation of the BSON UUID type.
	 * @public
	 */
	class UUID extends Binary {
		/**
		 * Create a UUID type
		 *
		 * When the argument to the constructor is omitted a random v4 UUID will be generated.
		 *
		 * @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
		 */
		constructor(input?: string | Uint8Array | UUID);
		/**
		 * The UUID bytes
		 * @readonly
		 */
		get id(): Uint8Array;
		set id(value: Uint8Array);
		/**
		 * Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
		 * @param includeDashes - should the string exclude dash-separators.
		 */
		toHexString(includeDashes?: boolean): string;
		/**
		 * Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
		 */
		toString(encoding?: "hex" | "base64"): string;
		/**
		 * Converts the id into its JSON string representation.
		 * A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
		 */
		toJSON(): string;
		/**
		 * Compares the equality of this UUID with `otherID`.
		 *
		 * @param otherId - UUID instance to compare against.
		 */
		equals(otherId: string | Uint8Array | UUID): boolean;
		/**
		 * Creates a Binary instance from the current UUID.
		 */
		toBinary(): Binary;
		/**
		 * Generates a populated buffer containing a v4 uuid
		 */
		static generate(): Uint8Array;
		/**
		 * Checks if a value is a valid bson UUID
		 * @param input - UUID, string or Buffer to validate.
		 */
		static isValid(input: string | Uint8Array | UUID | Binary): boolean;
		/**
		 * Creates an UUID from a hex string representation of an UUID.
		 * @param hexString - 32 or 36 character hex string (dashes excluded/included).
		 */
		static createFromHexString(hexString: string): UUID;
		/** Creates an UUID from a base64 string representation of an UUID. */
		static createFromBase64(base64: string): UUID;
		/* Excluded from this release type: bytesFromString */
		/* Excluded from this release type: isValidUUIDString */
		/**
		 * Converts to a string representation of this Id.
		 *
		 * @returns return the 36 character hex string representation.
		 *
		 */
		inspect(depth?: number, options?: unknown, inspect?: InspectFn): string;
	}

	/** @public */
	type UUIDExtended = {
		$uuid: string;
	};

	/** @public */
	abstract class AbstractCursor<TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> implements AsyncDisposable_2 {
		/* Excluded from this release type: cursorId */
		/* Excluded from this release type: cursorSession */
		/* Excluded from this release type: selectedServer */
		/* Excluded from this release type: cursorNamespace */
		/* Excluded from this release type: documents */
		/* Excluded from this release type: cursorClient */
		/* Excluded from this release type: transform */
		/* Excluded from this release type: initialized */
		/* Excluded from this release type: isClosed */
		/* Excluded from this release type: isKilled */
		/* Excluded from this release type: cursorOptions */
		/* Excluded from this release type: timeoutContext */
		/** @event */
		static readonly CLOSE: "close";
		/* Excluded from this release type: deserializationOptions */
		/* Excluded from this release type: __constructor */
		/**
		 * The cursor has no id until it receives a response from the initial cursor creating command.
		 *
		 * It is non-zero for as long as the database has an open cursor.
		 *
		 * The initiating command may receive a zero id if the entire result is in the `firstBatch`.
		 */
		get id(): Long | undefined;
		/* Excluded from this release type: isDead */
		/* Excluded from this release type: client */
		/* Excluded from this release type: server */
		get namespace(): MongoDBNamespace;
		get readPreference(): ReadPreference;
		get readConcern(): ReadConcern | undefined;
		/* Excluded from this release type: session */
		/* Excluded from this release type: session */
		/**
		 * The cursor is closed and all remaining locally buffered documents have been iterated.
		 */
		get closed(): boolean;
		/**
		 * A `killCursors` command was attempted on this cursor.
		 * This is performed if the cursor id is non zero.
		 */
		get killed(): boolean;
		get loadBalanced(): boolean;
		/* Excluded from this release type: [Symbol.asyncDispose] */
		/* Excluded from this release type: asyncDispose */
		/** Returns current buffered documents length */
		bufferedCount(): number;
		/** Returns current buffered documents */
		readBufferedDocuments(number?: number): NonNullable<TSchema>[];
		[Symbol.asyncIterator](): AsyncGenerator<TSchema, void, void>;
		hasNext(): Promise<boolean>;
		/** Get the next available document from the cursor, returns null if no more documents are available. */
		next(): Promise<TSchema | null>;
		/**
		 * Try to get the next available document from the cursor or `null` if an empty batch is returned
		 */
		tryNext(): Promise<TSchema | null>;
		/**
		 * Iterates over all the documents for this cursor using the iterator, callback pattern.
		 *
		 * If the iterator returns `false`, iteration will stop.
		 *
		 * @param iterator - The iteration callback.
		 * @deprecated - Will be removed in a future release. Use for await...of instead.
		 */
		forEach(iterator: (doc: TSchema) => boolean | void): Promise<void>;
		/**
		 * Frees any client-side resources used by the cursor.
		 */
		close(options?: { timeoutMS?: number }): Promise<void>;
		/**
		 * Returns an array of documents. The caller is responsible for making sure that there
		 * is enough memory to store the results. Note that the array only contains partial
		 * results when this cursor had been previously accessed. In that case,
		 * cursor.rewind() can be used to reset the cursor.
		 */
		toArray(): Promise<TSchema[]>;
		/**
		 * Add a cursor flag to the cursor
		 *
		 * @param flag - The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
		 * @param value - The flag boolean value.
		 */
		addCursorFlag(flag: CursorFlag, value: boolean): this;
		/**
		 * Map all documents using the provided function
		 * If there is a transform set on the cursor, that will be called first and the result passed to
		 * this function's transform.
		 *
		 * @remarks
		 *
		 * **Note** Cursors use `null` internally to indicate that there are no more documents in the cursor. Providing a mapping
		 * function that maps values to `null` will result in the cursor closing itself before it has finished iterating
		 * all documents.  This will **not** result in a memory leak, just surprising behavior.  For example:
		 *
		 * ```typescript
		 * const cursor = collection.find({});
		 * cursor.map(() => null);
		 *
		 * const documents = await cursor.toArray();
		 * // documents is always [], regardless of how many documents are in the collection.
		 * ```
		 *
		 * Other falsey values are allowed:
		 *
		 * ```typescript
		 * const cursor = collection.find({});
		 * cursor.map(() => '');
		 *
		 * const documents = await cursor.toArray();
		 * // documents is now an array of empty strings
		 * ```
		 *
		 * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
		 * it **does not** return a new instance of a cursor. This means when calling map,
		 * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
		 * Take note of the following example:
		 *
		 * @example
		 * ```typescript
		 * const cursor: FindCursor<Document> = coll.find();
		 * const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);
		 * const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
		 * ```
		 * @param transform - The mapping transformation method.
		 */
		map<T = any>(transform: (doc: TSchema) => T): AbstractCursor<T>;
		/**
		 * Set the ReadPreference for the cursor.
		 *
		 * @param readPreference - The new read preference for the cursor.
		 */
		withReadPreference(readPreference: ReadPreferenceLike): this;
		/**
		 * Set the ReadPreference for the cursor.
		 *
		 * @param readPreference - The new read preference for the cursor.
		 */
		withReadConcern(readConcern: ReadConcernLike): this;
		/**
		 * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
		 *
		 * @param value - Number of milliseconds to wait before aborting the query.
		 */
		maxTimeMS(value: number): this;
		/**
		 * Set the batch size for the cursor.
		 *
		 * @param value - The number of documents to return per batch. See {@link https://www.mongodb.com/docs/manual/reference/command/find/|find command documentation}.
		 */
		batchSize(value: number): this;
		/**
		 * Rewind this cursor to its uninitialized state. Any options that are present on the cursor will
		 * remain in effect. Iterating this cursor will cause new queries to be sent to the server, even
		 * if the resultant data has already been retrieved by this cursor.
		 */
		rewind(): void;
		/**
		 * Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
		 */
		abstract clone(): AbstractCursor<TSchema>;
		/* Excluded from this release type: _initialize */
		/* Excluded from this release type: getMore */
		/* Excluded from this release type: cursorInit */
		/* Excluded from this release type: fetchBatch */
		/* Excluded from this release type: cleanup */
		/* Excluded from this release type: hasEmittedClose */
		/* Excluded from this release type: emitClose */
		/* Excluded from this release type: transformDocument */
		/* Excluded from this release type: throwIfInitialized */
	}

	/** @public */
	type AbstractCursorEvents = {
		[AbstractCursor.CLOSE](): void;
	};

	/** @public */
	interface AbstractCursorOptions extends BSONSerializeOptions {
		session?: ClientSession;
		readPreference?: ReadPreferenceLike;
		readConcern?: ReadConcernLike;
		/**
		 * Specifies the number of documents to return in each response from MongoDB
		 */
		batchSize?: number;
		/**
		 * When applicable `maxTimeMS` controls the amount of time the initial command
		 * that constructs a cursor should take. (ex. find, aggregate, listCollections)
		 */
		maxTimeMS?: number;
		/**
		 * When applicable `maxAwaitTimeMS` controls the amount of time subsequent getMores
		 * that a cursor uses to fetch more data should take. (ex. cursor.next())
		 */
		maxAwaitTimeMS?: number;
		/**
		 * Comment to apply to the operation.
		 *
		 * In server versions pre-4.4, 'comment' must be string.  A server
		 * error will be thrown if any other type is provided.
		 *
		 * In server versions 4.4 and above, 'comment' can be any valid BSON type.
		 */
		comment?: unknown;
		/**
		 * By default, MongoDB will automatically close a cursor when the
		 * client has exhausted all results in the cursor. However, for [capped collections](https://www.mongodb.com/docs/manual/core/capped-collections)
		 * you may use a Tailable Cursor that remains open after the client exhausts
		 * the results in the initial cursor.
		 */
		tailable?: boolean;
		/**
		 * If awaitData is set to true, when the cursor reaches the end of the capped collection,
		 * MongoDB blocks the query thread for a period of time waiting for new data to arrive.
		 * When new data is inserted into the capped collection, the blocked thread is signaled
		 * to wake up and return the next batch to the client.
		 */
		awaitData?: boolean;
		noCursorTimeout?: boolean;
		/** 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. */
		timeoutMS?: number;
		/**
		 * @public
		 * @experimental
		 * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
		 * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
		 * `cursor.next()`.
		 * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
		 *
		 * Depending on the type of cursor being used, this option has different default values.
		 * For non-tailable cursors, this value defaults to `'cursorLifetime'`
		 * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
		 * definition can have an arbitrarily long lifetime.
		 *
		 * @example
		 * ```ts
		 * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
		 * for await (const doc of cursor) {
		 *  // process doc
		 *  // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
		 *  // will continue to iterate successfully otherwise, regardless of the number of batches.
		 * }
		 * ```
		 *
		 * @example
		 * ```ts
		 * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
		 * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
		 * ```
		 */
		timeoutMode?: CursorTimeoutMode;
		/* Excluded from this release type: timeoutContext */
	}

	/* Excluded from this release type: AbstractOperation */

	/** @public */
	type AcceptedFields<TSchema, FieldType, AssignableType> = {
		readonly [key in KeysOfAType<TSchema, FieldType>]?: AssignableType;
	};

	/** @public */
	type AddToSetOperators<Type> = {
		$each?: Array<Flatten<Type>>;
	};

	/**
	 * The **Admin** class is an internal class that allows convenient access to
	 * the admin functionality and commands for MongoDB.
	 *
	 * **ADMIN Cannot directly be instantiated**
	 * @public
	 *
	 * @example
	 * ```ts
	 * import { MongoClient } from 'mongodb';
	 *
	 * const client = new MongoClient('mongodb://localhost:27017');
	 * const admin = client.db().admin();
	 * const dbInfo = await admin.listDatabases();
	 * for (const db of dbInfo.databases) {
	 *   console.log(db.name);
	 * }
	 * ```
	 */
	class Admin {
		/* Excluded from this release type: s */
		/* Excluded from this release type: __constructor */
		/**
		 * Execute a command
		 *
		 * The driver will ensure the following fields are attached to the command sent to the server:
		 * - `lsid` - sourced from an implicit session or options.session
		 * - `$readPreference` - defaults to primary or can be configured by options.readPreference
		 * - `$db` - sourced from the name of this database
		 *
		 * If the client has a serverApi setting:
		 * - `apiVersion`
		 * - `apiStrict`
		 * - `apiDeprecationErrors`
		 *
		 * When in a transaction:
		 * - `readConcern` - sourced from readConcern set on the TransactionOptions
		 * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
		 *
		 * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
		 *
		 * @param command - The command to execute
		 * @param options - Optional settings for the command
		 */
		command(command: Document, options?: RunCommandOptions): Promise<Document>;
		/**
		 * Retrieve the server build information
		 *
		 * @param options - Optional settings for the command
		 */
		buildInfo(options?: CommandOperationOptions): Promise<Document>;
		/**
		 * Retrieve the server build information
		 *
		 * @param options - Optional settings for the command
		 */
		serverInfo(options?: CommandOperationOptions): Promise<Document>;
		/**
		 * Retrieve this db's server status.
		 *
		 * @param options - Optional settings for the command
		 */
		serverStatus(options?: CommandOperationOptions): Promise<Document>;
		/**
		 * Ping the MongoDB server and retrieve results
		 *
		 * @param options - Optional settings for the command
		 */
		ping(options?: CommandOperationOptions): Promise<Document>;
		/**
		 * Remove a user from a database
		 *
		 * @param username - The username to remove
		 * @param options - Optional settings for the command
		 */
		removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
		/**
		 * Validate an existing collection
		 *
		 * @param collectionName - The name of the collection to validate.
		 * @param options - Optional settings for the command
		 */
		validateCollection(collectionName: string, options?: ValidateCollectionOptions): Promise<Document>;
		/**
		 * List the available databases
		 *
		 * @param options - Optional settings for the command
		 */
		listDatabases(options?: ListDatabasesOptions): Promise<ListDatabasesResult>;
		/**
		 * Get ReplicaSet status
		 *
		 * @param options - Optional settings for the command
		 */
		replSetGetStatus(options?: CommandOperationOptions): Promise<Document>;
	}

	/* Excluded from this release type: AdminPrivate */

	/* Excluded from this release type: AggregateOperation */

	/** @public */
	interface AggregateOptions extends Omit<CommandOperationOptions, "explain"> {
		/** allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 \>). */
		allowDiskUse?: boolean;
		/** The number of documents to return per batch. See [aggregation documentation](https://www.mongodb.com/docs/manual/reference/command/aggregate). */
		batchSize?: number;
		/** Allow driver to bypass schema validation. */
		bypassDocumentValidation?: boolean;
		/** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */
		cursor?: Document;
		/**
		 * Specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
		 */
		maxTimeMS?: number;
		/** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */
		maxAwaitTimeMS?: number;
		/** Specify collation. */
		collation?: CollationOptions;
		/** Add an index selection hint to an aggregation command */
		hint?: Hint;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		out?: string;
		/**
		 * Specifies the verbosity mode for the explain output.
		 * @deprecated This API is deprecated in favor of `collection.aggregate().explain()`
		 * or `db.aggregate().explain()`.
		 */
		explain?: ExplainOptions["explain"];
		/* Excluded from this release type: timeoutMode */
	}

	/**
	 * The **AggregationCursor** class is an internal class that embodies an aggregation cursor on MongoDB
	 * allowing for iteration over the results returned from the underlying query. It supports
	 * one by one document iteration, conversion to an array or can be iterated as a Node 4.X
	 * or higher stream
	 * @public
	 */
	class AggregationCursor<TSchema = any> extends ExplainableCursor<TSchema> {
		readonly pipeline: Document[];
		/* Excluded from this release type: aggregateOptions */
		/* Excluded from this release type: __constructor */
		clone(): AggregationCursor<TSchema>;
		map<T>(transform: (doc: TSchema) => T): AggregationCursor<T>;
		/* Excluded from this release type: _initialize */
		/** Execute the explain for the cursor */
		explain(): Promise<Document>;
		explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;
		explain(options: { timeoutMS?: number }): Promise<Document>;
		explain(
			verbosity: ExplainVerbosityLike | ExplainCommandOptions,
			options: {
				timeoutMS?: number;
			}
		): Promise<Document>;
		/** Add a stage to the aggregation pipeline
		 * @example
		 * ```
		 * const documents = await users.aggregate().addStage({ $match: { name: /Mike/ } }).toArray();
		 * ```
		 * @example
		 * ```
		 * const documents = await users.aggregate()
		 *   .addStage<{ name: string }>({ $project: { name: true } })
		 *   .toArray(); // type of documents is { name: string }[]
		 * ```
		 */
		addStage(stage: Document): this;
		addStage<T = Document>(stage: Document): AggregationCursor<T>;
		/** Add a group stage to the aggregation pipeline */
		group<T = TSchema>($group: Document): AggregationCursor<T>;
		/** Add a limit stage to the aggregation pipeline */
		limit($limit: number): this;
		/** Add a match stage to the aggregation pipeline */
		match($match: Document): this;
		/** Add an out stage to the aggregation pipeline */
		out(
			$out:
				| {
						db: string;
						coll: string;
				  }
				| string
		): this;
		/**
		 * Add a project stage to the aggregation pipeline
		 *
		 * @remarks
		 * In order to strictly type this function you must provide an interface
		 * that represents the effect of your projection on the result documents.
		 *
		 * By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
		 * You should specify a parameterized type to have assertions on your final results.
		 *
		 * @example
		 * ```typescript
		 * // Best way
		 * const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
		 * // Flexible way
		 * const docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });
		 * ```
		 *
		 * @remarks
		 * In order to strictly type this function you must provide an interface
		 * that represents the effect of your projection on the result documents.
		 *
		 * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
		 * it **does not** return a new instance of a cursor. This means when calling project,
		 * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
		 * Take note of the following example:
		 *
		 * @example
		 * ```typescript
		 * const cursor: AggregationCursor<{ a: number; b: string }> = coll.aggregate([]);
		 * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
		 * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
		 *
		 * // or always use chaining and save the final cursor
		 *
		 * const cursor = coll.aggregate().project<{ a: string }>({
		 *   _id: 0,
		 *   a: { $convert: { input: '$a', to: 'string' }
		 * }});
		 * ```
		 */
		project<T extends Document = Document>($project: Document): AggregationCursor<T>;
		/** Add a lookup stage to the aggregation pipeline */
		lookup($lookup: Document): this;
		/** Add a redact stage to the aggregation pipeline */
		redact($redact: Document): this;
		/** Add a skip stage to the aggregation pipeline */
		skip($skip: number): this;
		/** Add a sort stage to the aggregation pipeline */
		sort($sort: Sort): this;
		/** Add a unwind stage to the aggregation pipeline */
		unwind($unwind: Document | string): this;
		/** Add a geoNear stage to the aggregation pipeline */
		geoNear($geoNear: Document): this;
	}

	/** @public */
	interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {}

	/**
	 * It is possible to search using alternative types in mongodb e.g.
	 * string types can be searched using a regex in mongo
	 * array types can be searched using their element type
	 * @public
	 */
	type AlternativeType<T> = T extends ReadonlyArray<infer U> ? T | RegExpOrString<U> : RegExpOrString<T>;

	/** @public */
	type AnyBulkWriteOperation<TSchema extends Document = Document> =
		| {
				insertOne: InsertOneModel<TSchema>;
		  }
		| {
				replaceOne: ReplaceOneModel<TSchema>;
		  }
		| {
				updateOne: UpdateOneModel<TSchema>;
		  }
		| {
				updateMany: UpdateManyModel<TSchema>;
		  }
		| {
				deleteOne: DeleteOneModel<TSchema>;
		  }
		| {
				deleteMany: DeleteManyModel<TSchema>;
		  };

	/**
	 * Used to represent any of the client bulk write models that can be passed as an array
	 * to MongoClient#bulkWrite.
	 * @public
	 */
	type AnyClientBulkWriteModel<TSchema extends Document> = ClientInsertOneModel<TSchema> | ClientReplaceOneModel<TSchema> | ClientUpdateOneModel<TSchema> | ClientUpdateManyModel<TSchema> | ClientDeleteOneModel<TSchema> | ClientDeleteManyModel<TSchema>;

	/** @public */
	type AnyError = MongoError | Error;

	/** @public */
	type ArrayElement<Type> = Type extends ReadonlyArray<infer Item> ? Item : never;

	/** @public */
	type ArrayOperator<Type> = {
		$each?: Array<Flatten<Type>>;
		$slice?: number;
		$position?: number;
		$sort?: Sort;
	};

	/**
	 * @public
	 */
	interface AsyncDisposable_2 {
		/* Excluded from this release type: [Symbol.asyncDispose] */
		/* Excluded from this release type: asyncDispose */
	}

	/** @public */
	interface Auth {
		/** The username for auth */
		username?: string;
		/** The password for auth */
		password?: string;
	}

	/* Excluded from this release type: AuthContext */

	/** @public */
	const AuthMechanism: Readonly<{
		readonly MONGODB_AWS: "MONGODB-AWS";
		readonly MONGODB_CR: "MONGODB-CR";
		readonly MONGODB_DEFAULT: "DEFAULT";
		readonly MONGODB_GSSAPI: "GSSAPI";
		readonly MONGODB_PLAIN: "PLAIN";
		readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1";
		readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256";
		readonly MONGODB_X509: "MONGODB-X509";
		readonly MONGODB_OIDC: "MONGODB-OIDC";
	}>;

	/** @public */
	type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism];

	/** @public */
	interface AuthMechanismProperties extends Document {
		SERVICE_HOST?: string;
		SERVICE_NAME?: string;
		SERVICE_REALM?: string;
		CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue;
		AWS_SESSION_TOKEN?: string;
		/** A user provided OIDC machine callback function. */
		OIDC_CALLBACK?: OIDCCallbackFunction;
		/** A user provided OIDC human interacted callback function. */
		OIDC_HUMAN_CALLBACK?: OIDCCallbackFunction;
		/** The OIDC environment. Note that 'test' is for internal use only. */
		ENVIRONMENT?: "test" | "azure" | "gcp" | "k8s";
		/** Allowed hosts that OIDC auth can connect to. */
		ALLOWED_HOSTS?: string[];
		/** The resource token for OIDC auth in Azure and GCP. */
		TOKEN_RESOURCE?: string;
	}

	/* Excluded from this release type: AuthProvider */

	/* Excluded from this release type: AutoEncrypter */

	/**
	 * @public
	 *
	 * Extra options related to the mongocryptd process
	 * \* _Available in MongoDB 6.0 or higher._
	 */
	type AutoEncryptionExtraOptions = NonNullable<AutoEncryptionOptions["extraOptions"]>;

	/** @public */
	const AutoEncryptionLoggerLevel: Readonly<{
		readonly FatalError: 0;
		readonly Error: 1;
		readonly Warning: 2;
		readonly Info: 3;
		readonly Trace: 4;
	}>;

	/**
	 * @public
	 * The level of severity of the log message
	 *
	 * | Value | Level |
	 * |-------|-------|
	 * | 0 | Fatal Error |
	 * | 1 | Error |
	 * | 2 | Warning |
	 * | 3 | Info |
	 * | 4 | Trace |
	 */
	type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel];

	/** @public */
	interface AutoEncryptionOptions {
		/* Excluded from this release type: metadataClient */
		/** A `MongoClient` used to fetch keys from a key vault */
		keyVaultClient?: MongoClient;
		/** The namespace where keys are stored in the key vault */
		keyVaultNamespace?: string;
		/** Configuration options that are used by specific KMS providers during key generation, encryption, and decryption. */
		kmsProviders?: KMSProviders;
		/**
		 * A map of namespaces to a local JSON schema for encryption
		 *
		 * **NOTE**: Supplying options.schemaMap provides more security than relying on JSON Schemas obtained from the server.
		 * It protects against a malicious server advertising a false JSON Schema, which could trick the client into sending decrypted data that should be encrypted.
		 * Schemas supplied in the schemaMap only apply to configuring automatic encryption for Client-Side Field Level Encryption.
		 * Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
		 */
		schemaMap?: Document;
		/** Supply a schema for the encrypted fields in the document  */
		encryptedFieldsMap?: Document;
		/** Allows the user to bypass auto encryption, maintaining implicit decryption */
		bypassAutoEncryption?: boolean;
		/** Allows users to bypass query analysis */
		bypassQueryAnalysis?: boolean;
		options?: {
			/** An optional hook to catch logging messages from the underlying encryption engine */
			logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
		};
		extraOptions?: {
			/**
			 * A local process the driver communicates with to determine how to encrypt values in a command.
			 * Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise
			 */
			mongocryptdURI?: string;
			/** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting  */
			mongocryptdBypassSpawn?: boolean;
			/** The path to the mongocryptd executable on the system */
			mongocryptdSpawnPath?: string;
			/** Command line arguments to use when auto-spawning a mongocryptd */
			mongocryptdSpawnArgs?: string[];
			/**
			 * Full path to a MongoDB Crypt shared library to be used (instead of mongocryptd).
			 *
			 * This needs to be the path to the file itself, not a directory.
			 * It can be an absolute or relative path. If the path is relative and
			 * its first component is `$ORIGIN`, it will be replaced by the directory
			 * containing the mongodb-client-encryption native addon file. Otherwise,
			 * the path will be interpreted relative to the current working directory.
			 *
			 * Currently, loading different MongoDB Crypt shared library files from different
			 * MongoClients in the same process is not supported.
			 *
			 * If this option is provided and no MongoDB Crypt shared library could be loaded
			 * from the specified location, creating the MongoClient will fail.
			 *
			 * If this option is not provided and `cryptSharedLibRequired` is not specified,
			 * the AutoEncrypter will attempt to spawn and/or use mongocryptd according
			 * to the mongocryptd-specific `extraOptions` options.
			 *
			 * Specifying a path prevents mongocryptd from being used as a fallback.
			 *
			 * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
			 */
			cryptSharedLibPath?: string;
			/**
			 * If specified, never use mongocryptd and instead fail when the MongoDB Crypt
			 * shared library could not be loaded.
			 *
			 * This is always true when `cryptSharedLibPath` is specified.
			 *
			 * Requires the MongoDB Crypt shared library, available in MongoDB 6.0 or higher.
			 */
			cryptSharedLibRequired?: boolean;
			/* Excluded from this release type: cryptSharedLibSearchPaths */
		};
		proxyOptions?: ProxyOptions;
		/** The TLS options to use connecting to the KMS provider */
		tlsOptions?: CSFLEKMSTlsOptions;
	}

	/**
	 * @public
	 * Configuration options for making an AWS encryption key
	 */
	interface AWSEncryptionKeyOptions {
		/**
		 * The AWS region of the KMS
		 */
		region: string;
		/**
		 * The Amazon Resource Name (ARN) to the AWS customer master key (CMK)
		 */
		key: string;
		/**
		 * An alternate host to send KMS requests to. May include port number.
		 */
		endpoint?: string | undefined;
	}

	/** @public */
	interface AWSKMSProviderConfiguration {
		/**
		 * The access key used for the AWS KMS provider
		 */
		accessKeyId: string;
		/**
		 * The secret access key used for the AWS KMS provider
		 */
		secretAccessKey: string;
		/**
		 * An optional AWS session token that will be used as the
		 * X-Amz-Security-Token header for AWS requests.
		 */
		sessionToken?: string;
	}

	/**
	 * @public
	 * Configuration options for making an Azure encryption key
	 */
	interface AzureEncryptionKeyOptions {
		/**
		 * Key name
		 */
		keyName: string;
		/**
		 * Key vault URL, typically `<name>.vault.azure.net`
		 */
		keyVaultEndpoint: string;
		/**
		 * Key version
		 */
		keyVersion?: string | undefined;
	}

	/** @public */
	type AzureKMSProviderConfiguration =
		| {
				/**
				 * The tenant ID identifies the organization for the account
				 */
				tenantId: string;
				/**
				 * The client ID to authenticate a registered application
				 */
				clientId: string;
				/**
				 * The client secret to authenticate a registered application
				 */
				clientSecret: string;
				/**
				 * If present, a host with optional port. E.g. "example.com" or "example.com:443".
				 * This is optional, and only needed if customer is using a non-commercial Azure instance
				 * (e.g. a government or China account, which use different URLs).
				 * Defaults to "login.microsoftonline.com"
				 */
				identityPlatformEndpoint?: string | undefined;
		  }
		| {
				/**
				 * If present, an access token to authenticate with Azure.
				 */
				accessToken: string;
		  };

	/**
	 * Keeps the state of a unordered batch so we can rewrite the results
	 * correctly after command execution
	 *
	 * @public
	 */
	class Batch<T = Document> {
		originalZeroIndex: number;
		currentIndex: number;
		originalIndexes: number[];
		batchType: BatchType;
		operations: T[];
		size: number;
		sizeBytes: number;
		constructor(batchType: BatchType, originalZeroIndex: number);
	}

	/** @public */
	const BatchType: Readonly<{
		readonly INSERT: 1;
		readonly UPDATE: 2;
		readonly DELETE: 3;
	}>;

	/** @public */
	type BatchType = (typeof BatchType)[keyof typeof BatchType];

	/** @public */
	type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray<number>;

	/**
	 * BSON Serialization options.
	 * @public
	 */
	interface BSONSerializeOptions extends Omit<SerializeOptions, "index">, Omit<DeserializeOptions, "evalFunctions" | "cacheFunctions" | "cacheFunctionsCrc32" | "allowObjectSmallerThanBufferSize" | "index" | "validation"> {
		/**
		 * Enabling the raw option will return a [Node.js Buffer](https://nodejs.org/api/buffer.html)
		 * which is allocated using [allocUnsafe API](https://nodejs.org/api/buffer.html#static-method-bufferallocunsafesize).
		 * See this section from the [Node.js Docs here](https://nodejs.org/api/buffer.html#what-makes-bufferallocunsafe-and-bufferallocunsafeslow-unsafe)
		 * for more detail about what "unsafe" refers to in this context.
		 * 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
		 * your own buffer and clone the contents:
		 *
		 * @example
		 * ```ts
		 * const raw = await collection.findOne({}, { raw: true });
		 * const myBuffer = Buffer.alloc(raw.byteLength);
		 * myBuffer.set(raw, 0);
		 * // Only save and use `myBuffer` beyond this point
		 * ```
		 *
		 * @remarks
		 * 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)).
		 * It does correctly work at `Db`, `Collection`, and per operation the same as other BSON options work.
		 */
		raw?: boolean;
		/** Enable utf8 validation when deserializing BSON documents.  Defaults to true. */
		enableUtf8Validation?: boolean;
	}

	/** @public */
	type BSONTypeAlias = keyof typeof BSONType;

	/* Excluded from this release type: BufferPool */

	/** @public */
	abstract class BulkOperationBase {
		private collection;
		isOrdered: boolean;
		/* Excluded from this release type: s */
		operationId?: number;
		/* Excluded from this release type: __constructor */
		/**
		 * Add a single insert document to the bulk operation
		 *
		 * @example
		 * ```ts
		 * const bulkOp = collection.initializeOrderedBulkOp();
		 *
		 * // Adds three inserts to the bulkOp.
		 * bulkOp
		 *   .insert({ a: 1 })
		 *   .insert({ b: 2 })
		 *   .insert({ c: 3 });
		 * await bulkOp.execute();
		 * ```
		 */
		insert(document: Document): BulkOperationBase;
		/**
		 * Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
		 * Returns a builder object used to complete the definition of the operation.
		 *
		 * @example
		 * ```ts
		 * const bulkOp = collection.initializeOrderedBulkOp();
		 *
		 * // Add an updateOne to the bulkOp
		 * bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
		 *
		 * // Add an updateMany to the bulkOp
		 * bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
		 *
		 * // Add an upsert
		 * bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
		 *
		 * // Add a deletion
		 * bulkOp.find({ g: 7 }).deleteOne();
		 *
		 * // Add a multi deletion
		 * bulkOp.find({ h: 8 }).delete();
		 *
		 * // Add a replaceOne
		 * bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
		 *
		 * // Update using a pipeline (requires Mongodb 4.2 or higher)
		 * bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
		 *   { $set: { total: { $sum: [ '$y', '$z' ] } } }
		 * ]);
		 *
		 * // All of the ops will now be executed
		 * await bulkOp.execute();
		 * ```
		 */
		find(selector: Document): FindOperators;
		/** Specifies a raw operation to perform in the bulk write. */
		raw(op: AnyBulkWriteOperation): this;
		get length(): number;
		get bsonOptions(): BSONSerializeOptions;
		get writeConcern(): WriteConcern | undefined;
		get batches(): Batch[];
		execute(options?: BulkWriteOptions): Promise<BulkWriteResult>;
		/* Excluded from this release type: handleWriteError */
		abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
		private shouldForceServerObjectId;
	}

	/* Excluded from this release type: BulkOperationPrivate */

	/* Excluded from this release type: BulkResult */

	/** @public */
	interface BulkWriteOperationError {
		index: number;
		code: number;
		errmsg: string;
		errInfo: Document;
		op: Document | UpdateStatement | DeleteStatement;
	}

	/** @public */
	interface BulkWriteOptions extends CommandOperationOptions {
		/**
		 * Allow driver to bypass schema validation.
		 * @defaultValue `false` - documents will be validated by default
		 **/
		bypassDocumentValidation?: boolean;
		/**
		 * If true, when an insert fails, don't execute the remaining writes.
		 * If false, continue with remaining inserts when one fails.
		 * @defaultValue `true` - inserts are ordered by default
		 */
		ordered?: boolean;
		/**
		 * Force server to assign _id values instead of driver.
		 * @defaultValue `false` - the driver generates `_id` fields by default
		 **/
		forceServerObjectId?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		/* Excluded from this release type: timeoutContext */
	}

	/**
	 * @public
	 * The result of a bulk write.
	 */
	class BulkWriteResult {
		private readonly result;
		/** Number of documents inserted. */
		readonly insertedCount: number;
		/** Number of documents matched for update. */
		readonly matchedCount: number;
		/** Number of documents modified. */
		readonly modifiedCount: number;
		/** Number of documents deleted. */
		readonly deletedCount: number;
		/** Number of documents upserted. */
		readonly upsertedCount: number;
		/** Upserted document generated Id's, hash key is the index of the originating operation */
		readonly upsertedIds: {
			[key: number]: any;
		};
		/** Inserted document generated Id's, hash key is the index of the originating operation */
		readonly insertedIds: {
			[key: number]: any;
		};
		private static generateIdMap;
		/* Excluded from this release type: __constructor */
		/** Evaluates to true if the bulk operation correctly executes */
		get ok(): number;
		/* Excluded from this release type: getSuccessfullyInsertedIds */
		/** Returns the upserted id at the given index */
		getUpsertedIdAt(index: number): Document | undefined;
		/** Returns raw internal result */
		getRawResponse(): Document;
		/** Returns true if the bulk operation contains a write error */
		hasWriteErrors(): boolean;
		/** Returns the number of write errors off the bulk operation */
		getWriteErrorCount(): number;
		/** Returns a specific write error object */
		getWriteErrorAt(index: number): WriteError | undefined;
		/** Retrieve all write errors */
		getWriteErrors(): WriteError[];
		/** Retrieve the write concern error if one exists */
		getWriteConcernError(): WriteConcernError | undefined;
		toString(): string;
		isOk(): boolean;
	}

	/**
	 * MongoDB Driver style callback
	 * @public
	 */
	type Callback<T = any> = (error?: AnyError, result?: T) => void;

	/** @public */
	class CancellationToken extends TypedEventEmitter<{
		cancel(): void;
	}> {}

	/**
	 * Only present when the `showExpandedEvents` flag is enabled.
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/modify/#mongodb-data-modify
	 */
	interface ChangeStreamCollModDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "modify";
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/create/#mongodb-data-create
	 */
	interface ChangeStreamCreateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "create";
	}

	/**
	 * Only present when the `showExpandedEvents` flag is enabled.
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/createIndexes/#mongodb-data-createIndexes
	 */
	interface ChangeStreamCreateIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
		/** Describes the type of operation represented in this change notification */
		operationType: "createIndexes";
	}

	/* Excluded from this release type: ChangeStreamCursor */

	/* Excluded from this release type: ChangeStreamCursorOptions */

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event
	 */
	interface ChangeStreamDeleteDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "delete";
		/** Namespace the delete event occurred on */
		ns: ChangeStreamNameSpace;
		/**
		 * Contains the pre-image of the modified or deleted document if the
		 * pre-image is available for the change event and either 'required' or
		 * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
		 * when creating the change stream. If 'whenAvailable' was specified but the
		 * pre-image is unavailable, this will be explicitly set to null.
		 */
		fullDocumentBeforeChange?: TSchema;
	}

	/** @public */
	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;

	/** @public */
	interface ChangeStreamDocumentCollectionUUID {
		/**
		 * The UUID (Binary subtype 4) of the collection that the operation was performed on.
		 *
		 * Only present when the `showExpandedEvents` flag is enabled.
		 *
		 * **NOTE:** collectionUUID will be converted to a NodeJS Buffer if the promoteBuffers
		 *    flag is enabled.
		 *
		 * @sinceServerVersion 6.1.0
		 */
		collectionUUID: Binary;
	}

	/** @public */
	interface ChangeStreamDocumentCommon {
		/**
		 * The id functions as an opaque token for use when resuming an interrupted
		 * change stream.
		 */
		_id: ResumeToken;
		/**
		 * The timestamp from the oplog entry associated with the event.
		 * For events that happened as part of a multi-document transaction, the associated change stream
		 * notifications will have the same clusterTime value, namely the time when the transaction was committed.
		 * On a sharded cluster, events that occur on different shards can have the same clusterTime but be
		 * associated with different transactions or even not be associated with any transaction.
		 * To identify events for a single transaction, you can use the combination of lsid and txnNumber in the change stream event document.
		 */
		clusterTime?: Timestamp;
		/**
		 * The transaction number.
		 * Only present if the operation is part of a multi-document transaction.
		 *
		 * **NOTE:** txnNumber can be a Long if promoteLongs is set to false
		 */
		txnNumber?: number;
		/**
		 * The identifier for the session associated with the transaction.
		 * Only present if the operation is part of a multi-document transaction.
		 */
		lsid?: ServerSessionId;
		/**
		 * When the change stream's backing aggregation pipeline contains the $changeStreamSplitLargeEvent
		 * stage, events larger than 16MB will be split into multiple events and contain the
		 * following information about which fragment the current event is.
		 */
		splitEvent?: ChangeStreamSplitEvent;
	}

	/** @public */
	interface ChangeStreamDocumentKey<TSchema extends Document = Document> {
		/**
		 * For unsharded collections this contains a single field `_id`.
		 * For sharded collections, this will contain all the components of the shard key
		 */
		documentKey: {
			_id: InferIdType<TSchema>;
			[shardKey: string]: any;
		};
	}

	/** @public */
	interface ChangeStreamDocumentOperationDescription {
		/**
		 * An description of the operation.
		 *
		 * Only present when the `showExpandedEvents` flag is enabled.
		 *
		 * @sinceServerVersion 6.1.0
		 */
		operationDescription?: Document;
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event
	 */
	interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon {
		/** Describes the type of operation represented in this change notification */
		operationType: "dropDatabase";
		/** The database dropped */
		ns: {
			db: string;
		};
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#drop-event
	 */
	interface ChangeStreamDropDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "drop";
		/** Namespace the drop event occurred on */
		ns: ChangeStreamNameSpace;
	}

	/**
	 * Only present when the `showExpandedEvents` flag is enabled.
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/dropIndexes/#mongodb-data-dropIndexes
	 */
	interface ChangeStreamDropIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
		/** Describes the type of operation represented in this change notification */
		operationType: "dropIndexes";
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event
	 */
	interface ChangeStreamInsertDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "insert";
		/** This key will contain the document being inserted */
		fullDocument: TSchema;
		/** Namespace the insert event occurred on */
		ns: ChangeStreamNameSpace;
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#invalidate-event
	 */
	interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon {
		/** Describes the type of operation represented in this change notification */
		operationType: "invalidate";
	}

	/** @public */
	interface ChangeStreamNameSpace {
		db: string;
		coll: string;
	}

	/**
	 * 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.
	 * @public
	 */
	interface ChangeStreamOptions extends Omit<AggregateOptions, "writeConcern"> {
		/**
		 * Allowed values: 'updateLookup', 'whenAvailable', 'required'.
		 *
		 * When set to 'updateLookup', the change notification for partial updates
		 * will include both a delta describing the changes to the document as well
		 * as a copy of the entire document that was changed from some time after
		 * the change occurred.
		 *
		 * When set to 'whenAvailable', configures the change stream to return the
		 * post-image of the modified document for replace and update change events
		 * if the post-image for this event is available.
		 *
		 * When set to 'required', the same behavior as 'whenAvailable' except that
		 * an error is raised if the post-image is not available.
		 */
		fullDocument?: string;
		/**
		 * Allowed values: 'whenAvailable', 'required', 'off'.
		 *
		 * The default is to not send a value, which is equivalent to 'off'.
		 *
		 * When set to 'whenAvailable', configures the change stream to return the
		 * pre-image of the modified document for replace, update, and delete change
		 * events if it is available.
		 *
		 * When set to 'required', the same behavior as 'whenAvailable' except that
		 * an error is raised if the pre-image is not available.
		 */
		fullDocumentBeforeChange?: string;
		/** The maximum amount of time for the server to wait on new documents to satisfy a change stream query. */
		maxAwaitTimeMS?: number;
		/**
		 * Allows you to start a changeStream after a specified event.
		 * @see https://www.mongodb.com/docs/manual/changeStreams/#resumeafter-for-change-streams
		 */
		resumeAfter?: ResumeToken;
		/**
		 * Similar to resumeAfter, but will allow you to start after an invalidated event.
		 * @see https://www.mongodb.com/docs/manual/changeStreams/#startafter-for-change-streams
		 */
		startAfter?: ResumeToken;
		/** Will start the changeStream after the specified operationTime. */
		startAtOperationTime?: OperationTime;
		/**
		 * The number of documents to return per batch.
		 * @see https://www.mongodb.com/docs/manual/reference/command/aggregate
		 */
		batchSize?: number;
		/**
		 * When enabled, configures the change stream to include extra change events.
		 *
		 * - createIndexes
		 * - dropIndexes
		 * - modify
		 * - create
		 * - shardCollection
		 * - reshardCollection
		 * - refineCollectionShardKey
		 */
		showExpandedEvents?: boolean;
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/refineCollectionShardKey/#mongodb-data-refineCollectionShardKey
	 */
	interface ChangeStreamRefineCollectionShardKeyDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
		/** Describes the type of operation represented in this change notification */
		operationType: "refineCollectionShardKey";
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#rename-event
	 */
	interface ChangeStreamRenameDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "rename";
		/** The new name for the `ns.coll` collection */
		to: {
			db: string;
			coll: string;
		};
		/** The "from" namespace that the rename occurred on */
		ns: ChangeStreamNameSpace;
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#replace-event
	 */
	interface ChangeStreamReplaceDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema> {
		/** Describes the type of operation represented in this change notification */
		operationType: "replace";
		/** The fullDocument of a replace event represents the document after the insert of the replacement document */
		fullDocument: TSchema;
		/** Namespace the replace event occurred on */
		ns: ChangeStreamNameSpace;
		/**
		 * Contains the pre-image of the modified or deleted document if the
		 * pre-image is available for the change event and either 'required' or
		 * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
		 * when creating the change stream. If 'whenAvailable' was specified but the
		 * pre-image is unavailable, this will be explicitly set to null.
		 */
		fullDocumentBeforeChange?: TSchema;
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/reshardCollection/#mongodb-data-reshardCollection
	 */
	interface ChangeStreamReshardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
		/** Describes the type of operation represented in this change notification */
		operationType: "reshardCollection";
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/shardCollection/#mongodb-data-shardCollection
	 */
	interface ChangeStreamShardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription {
		/** Describes the type of operation represented in this change notification */
		operationType: "shardCollection";
	}

	/** @public */
	interface ChangeStreamSplitEvent {
		/** Which fragment of the change this is. */
		fragment: number;
		/** The total number of fragments. */
		of: number;
	}

	/**
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/change-events/#update-event
	 */
	interface ChangeStreamUpdateDocument<TSchema extends Document = Document> extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey<TSchema>, ChangeStreamDocumentCollectionUUID {
		/** Describes the type of operation represented in this change notification */
		operationType: "update";
		/**
		 * This is only set if `fullDocument` is set to `'updateLookup'`
		 * Contains the point-in-time post-image of the modified document if the
		 * post-image is available and either 'required' or 'whenAvailable' was
		 * specified for the 'fullDocument' option when creating the change stream.
		 */
		fullDocument?: TSchema;
		/** Contains a description of updated and removed fields in this operation */
		updateDescription: UpdateDescription<TSchema>;
		/** Namespace the update event occurred on */
		ns: ChangeStreamNameSpace;
		/**
		 * Contains the pre-image of the modified or deleted document if the
		 * pre-image is available for the change event and either 'required' or
		 * 'whenAvailable' was specified for the 'fullDocumentBeforeChange' option
		 * when creating the change stream. If 'whenAvailable' was specified but the
		 * pre-image is unavailable, this will be explicitly set to null.
		 */
		fullDocumentBeforeChange?: TSchema;
	}

	/** @public */
	interface ClientBulkWriteError {
		code: number;
		message: string;
	}

	/**
	 * A mapping of namespace strings to collections schemas.
	 * @public
	 *
	 * @example
	 * ```ts
	 * type MongoDBSchemas = {
	 *   'db.books': Book;
	 *   'db.authors': Author;
	 * }
	 *
	 * const model: ClientBulkWriteModel<MongoDBSchemas> = {
	 *   namespace: 'db.books'
	 *   name: 'insertOne',
	 *   document: { title: 'Practical MongoDB Aggregations', authorName: 3 } // error `authorName` cannot be number
	 * };
	 * ```
	 *
	 * The type of the `namespace` field narrows other parts of the BulkWriteModel to use the correct schema for type assertions.
	 *
	 */
	type ClientBulkWriteModel<SchemaMap extends Record<string, Document> = Record<string, Document>> = {
		[Namespace in keyof SchemaMap]: AnyClientBulkWriteModel<SchemaMap[Namespace]> & {
			namespace: Namespace;
		};
	}[keyof SchemaMap];

	/** @public */
	interface ClientBulkWriteOptions extends CommandOperationOptions {
		/**
		 * If true, when an insert fails, don't execute the remaining writes.
		 * If false, continue with remaining inserts when one fails.
		 * @defaultValue `true` - inserts are ordered by default
		 */
		ordered?: boolean;
		/**
		 * Allow driver to bypass schema validation.
		 * @defaultValue `false` - documents will be validated by default
		 **/
		bypassDocumentValidation?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		/**
		 * Whether detailed results for each successful operation should be included in the returned
		 * BulkWriteResult.
		 */
		verboseResults?: boolean;
	}

	/** @public */
	interface ClientBulkWriteResult {
		/**
		 * Whether the bulk write was acknowledged.
		 */
		readonly acknowledged: boolean;
		/**
		 * The total number of documents inserted across all insert operations.
		 */
		readonly insertedCount: number;
		/**
		 * The total number of documents upserted across all update operations.
		 */
		readonly upsertedCount: number;
		/**
		 * The total number of documents matched across all update operations.
		 */
		readonly matchedCount: number;
		/**
		 * The total number of documents modified across all update operations.
		 */
		readonly modifiedCount: number;
		/**
		 * The total number of documents deleted across all delete operations.
		 */
		readonly deletedCount: number;
		/**
		 * The results of each individual insert operation that was successfully performed.
		 */
		readonly insertResults?: ReadonlyMap<number, ClientInsertOneResult>;
		/**
		 * The results of each individual update operation that was successfully performed.
		 */
		readonly updateResults?: ReadonlyMap<number, ClientUpdateResult>;
		/**
		 * The results of each individual delete operation that was successfully performed.
		 */
		readonly deleteResults?: ReadonlyMap<number, ClientDeleteResult>;
	}

	/** @public */
	interface ClientDeleteManyModel<TSchema> extends ClientWriteModel {
		name: "deleteMany";
		/**
		 * The filter used to determine if a document should be deleted.
		 * For a deleteMany operation, all matches are removed.
		 */
		filter: Filter<TSchema>;
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
	}

	/** @public */
	interface ClientDeleteOneModel<TSchema> extends ClientWriteModel {
		name: "deleteOne";
		/**
		 * The filter used to determine if a document should be deleted.
		 * For a deleteOne operation, the first match is removed.
		 */
		filter: Filter<TSchema>;
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
	}

	/** @public */
	interface ClientDeleteResult {
		/**
		 * The number of documents that were deleted.
		 */
		deletedCount: number;
	}

	/**
	 * @public
	 * The public interface for explicit in-use encryption
	 */
	class ClientEncryption {
		/* Excluded from this release type: _client */
		/* Excluded from this release type: _keyVaultNamespace */
		/* Excluded from this release type: _keyVaultClient */
		/* Excluded from this release type: _proxyOptions */
		/* Excluded from this release type: _tlsOptions */
		/* Excluded from this release type: _kmsProviders */
		/* Excluded from this release type: _timeoutMS */
		/* Excluded from this release type: _mongoCrypt */
		/* Excluded from this release type: getMongoCrypt */
		/**
		 * Create a new encryption instance
		 *
		 * @example
		 * ```ts
		 * new ClientEncryption(mongoClient, {
		 *   keyVaultNamespace: 'client.encryption',
		 *   kmsProviders: {
		 *     local: {
		 *       key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer
		 *     }
		 *   }
		 * });
		 * ```
		 *
		 * @example
		 * ```ts
		 * new ClientEncryption(mongoClient, {
		 *   keyVaultNamespace: 'client.encryption',
		 *   kmsProviders: {
		 *     aws: {
		 *       accessKeyId: AWS_ACCESS_KEY,
		 *       secretAccessKey: AWS_SECRET_KEY
		 *     }
		 *   }
		 * });
		 * ```
		 */
		constructor(client: MongoClient, options: ClientEncryptionOptions);
		/**
		 * Creates a data key used for explicit encryption and inserts it into the key vault namespace
		 *
		 * @example
		 * ```ts
		 * // Using async/await to create a local key
		 * const dataKeyId = await clientEncryption.createDataKey('local');
		 * ```
		 *
		 * @example
		 * ```ts
		 * // Using async/await to create an aws key
		 * const dataKeyId = await clientEncryption.createDataKey('aws', {
		 *   masterKey: {
		 *     region: 'us-east-1',
		 *     key: 'xxxxxxxxxxxxxx' // CMK ARN here
		 *   }
		 * });
		 * ```
		 *
		 * @example
		 * ```ts
		 * // Using async/await to create an aws key with a keyAltName
		 * const dataKeyId = await clientEncryption.createDataKey('aws', {
		 *   masterKey: {
		 *     region: 'us-east-1',
		 *     key: 'xxxxxxxxxxxxxx' // CMK ARN here
		 *   },
		 *   keyAltNames: [ 'mySpecialKey' ]
		 * });
		 * ```
		 */
		createDataKey(provider: ClientEncryptionDataKeyProvider, options?: ClientEncryptionCreateDataKeyProviderOptions): Promise<UUID>;
		/**
		 * 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.
		 *
		 * If no matches are found, then no bulk write is performed.
		 *
		 * @example
		 * ```ts
		 * // rewrapping all data data keys (using a filter that matches all documents)
		 * const filter = {};
		 *
		 * const result = await clientEncryption.rewrapManyDataKey(filter);
		 * if (result.bulkWriteResult != null) {
		 *  // keys were re-wrapped, results will be available in the bulkWrite object.
		 * }
		 * ```
		 *
		 * @example
		 * ```ts
		 * // attempting to rewrap all data keys with no matches
		 * const filter = { _id: new Binary() } // assume _id matches no documents in the database
		 * const result = await clientEncryption.rewrapManyDataKey(filter);
		 *
		 * if (result.bulkWriteResult == null) {
		 *  // no keys matched, `bulkWriteResult` does not exist on the result object
		 * }
		 * ```
		 */
		rewrapManyDataKey(
			filter: Filter<DataKey>,
			options: ClientEncryptionRewrapManyDataKeyProviderOptions
		): Promise<{
			bulkWriteResult?: BulkWriteResult;
		}>;
		/**
		 * Deletes the key with the provided id from the keyvault, if it exists.
		 *
		 * @example
		 * ```ts
		 * // delete a key by _id
		 * const id = new Binary(); // id is a bson binary subtype 4 object
		 * const { deletedCount } = await clientEncryption.deleteKey(id);
		 *
		 * if (deletedCount != null && deletedCount > 0) {
		 *   // successful deletion
		 * }
		 * ```
		 *
		 */
		deleteKey(_id: Binary): Promise<DeleteResult>;
		/**
		 * Finds all the keys currently stored in the keyvault.
		 *
		 * This method will not throw.
		 *
		 * @returns a FindCursor over all keys in the keyvault.
		 * @example
		 * ```ts
		 * // fetching all keys
		 * const keys = await clientEncryption.getKeys().toArray();
		 * ```
		 */
		getKeys(): FindCursor<DataKey>;
		/**
		 * Finds a key in the keyvault with the specified _id.
		 *
		 * Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
		 * match the id.  The promise rejects with an error if an error is thrown.
		 * @example
		 * ```ts
		 * // getting a key by id
		 * const id = new Binary(); // id is a bson binary subtype 4 object
		 * const key = await clientEncryption.getKey(id);
		 * if (!key) {
		 *  // key is null if there was no matching key
		 * }
		 * ```
		 */
		getKey(_id: Binary): Promise<DataKey | null>;
		/**
		 * Finds a key in the keyvault which has the specified keyAltName.
		 *
		 * @param keyAltName - a keyAltName to search for a key
		 * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
		 * match the keyAltName.  The promise rejects with an error if an error is thrown.
		 * @example
		 * ```ts
		 * // get a key by alt name
		 * const keyAltName = 'keyAltName';
		 * const key = await clientEncryption.getKeyByAltName(keyAltName);
		 * if (!key) {
		 *  // key is null if there is no matching key
		 * }
		 * ```
		 */
		getKeyByAltName(keyAltName: string): Promise<WithId<DataKey> | null>;
		/**
		 * Adds a keyAltName to a key identified by the provided _id.
		 *
		 * This method resolves to/returns the *old* key value (prior to adding the new altKeyName).
		 *
		 * @param _id - The id of the document to update.
		 * @param keyAltName - a keyAltName to search for a key
		 * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
		 * match the id.  The promise rejects with an error if an error is thrown.
		 * @example
		 * ```ts
		 * // adding an keyAltName to a data key
		 * const id = new Binary();  // id is a bson binary subtype 4 object
		 * const keyAltName = 'keyAltName';
		 * const oldKey = await clientEncryption.addKeyAltName(id, keyAltName);
		 * if (!oldKey) {
		 *  // null is returned if there is no matching document with an id matching the supplied id
		 * }
		 * ```
		 */
		addKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null>;
		/**
		 * Adds a keyAltName to a key identified by the provided _id.
		 *
		 * This method resolves to/returns the *old* key value (prior to removing the new altKeyName).
		 *
		 * If the removed keyAltName is the last keyAltName for that key, the `altKeyNames` property is unset from the document.
		 *
		 * @param _id - The id of the document to update.
		 * @param keyAltName - a keyAltName to search for a key
		 * @returns Returns a promise that either resolves to a {@link DataKey} if a document matches the key or null if no documents
		 * match the id.  The promise rejects with an error if an error is thrown.
		 * @example
		 * ```ts
		 * // removing a key alt name from a data key
		 * const id = new Binary();  // id is a bson binary subtype 4 object
		 * const keyAltName = 'keyAltName';
		 * const oldKey = await clientEncryption.removeKeyAltName(id, keyAltName);
		 *
		 * if (!oldKey) {
		 *  // null is returned if there is no matching document with an id matching the supplied id
		 * }
		 * ```
		 */
		removeKeyAltName(_id: Binary, keyAltName: string): Promise<WithId<DataKey> | null>;
		/**
		 * A convenience method for creating an encrypted collection.
		 * This method will create data keys for any encryptedFields that do not have a `keyId` defined
		 * and then create a new collection with the full set of encryptedFields.
		 *
		 * @param db - A Node.js driver Db object with which to create the collection
		 * @param name - The name of the collection to be created
		 * @param options - Options for createDataKey and for createCollection
		 * @returns created collection and generated encryptedFields
		 * @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.
		 * @throws MongoCryptCreateEncryptedCollectionError - If creating the collection fails, an error will be rejected that has the entire `encryptedFields` that were created.
		 */
		createEncryptedCollection<TSchema extends Document = Document>(
			db: Db,
			name: string,
			options: {
				provider: ClientEncryptionDataKeyProvider;
				createCollectionOptions: Omit<CreateCollectionOptions, "encryptedFields"> & {
					encryptedFields: Document;
				};
				masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions;
			}
		): Promise<{
			collection: Collection<TSchema>;
			encryptedFields: Document;
		}>;
		/**
		 * Explicitly encrypt a provided value. Note that either `options.keyId` or `options.keyAltName` must
		 * be specified. Specifying both `options.keyId` and `options.keyAltName` is considered an error.
		 *
		 * @param value - The value that you wish to serialize. Must be of a type that can be serialized into BSON
		 * @param options -
		 * @returns a Promise that either resolves with the encrypted value, or rejects with an error.
		 *
		 * @example
		 * ```ts
		 * // Encryption with async/await api
		 * async function encryptMyData(value) {
		 *   const keyId = await clientEncryption.createDataKey('local');
		 *   return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
		 * }
		 * ```
		 *
		 * @example
		 * ```ts
		 * // Encryption using a keyAltName
		 * async function encryptMyData(value) {
		 *   await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });
		 *   return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });
		 * }
		 * ```
		 */
		encrypt(value: unknown, options: ClientEncryptionEncryptOptions): Promise<Binary>;
		/**
		 * Encrypts a Match Expression or Aggregate Expression to query a range index.
		 *
		 * Only supported when queryType is "range" and algorithm is "Range".
		 *
		 * @param expression - a BSON document of one of the following forms:
		 *  1. A Match Expression of this form:
		 *      `{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}`
		 *  2. An Aggregate Expression of this form:
		 *      `{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}`
		 *
		 *    `$gt` may also be `$gte`. `$lt` may also be `$lte`.
		 *
		 * @param options -
		 * @returns Returns a Promise that either resolves with the encrypted value or rejects with an error.
		 */
		encryptExpression(expression: Document, options: ClientEncryptionEncryptOptions): Promise<Binary>;
		/**
		 * Explicitly decrypt a provided encrypted value
		 *
		 * @param value - An encrypted value
		 * @returns a Promise that either resolves with the decrypted value, or rejects with an error
		 *
		 * @example
		 * ```ts
		 * // Decrypting value with async/await API
		 * async function decryptMyValue(value) {
		 *   return clientEncryption.decrypt(value);
		 * }
		 * ```
		 */
		decrypt<T = any>(value: Binary): Promise<T>;
		/* Excluded from this release type: askForKMSCredentials */
		static get libmongocryptVersion(): string;
		/* Excluded from this release type: _encrypt */
	}

	/**
	 * @public
	 * Options to provide when creating a new data key.
	 */
	interface ClientEncryptionCreateDataKeyProviderOptions {
		/**
		 * Identifies a new KMS-specific key used to encrypt the new data key
		 */
		masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | KMIPEncryptionKeyOptions | undefined;
		/**
		 * An optional list of string alternate names used to reference a key.
		 * If a key is created with alternate names, then encryption may refer to the key by the unique alternate name instead of by _id.
		 */
		keyAltNames?: string[] | undefined;
		/** @experimental */
		keyMaterial?: Buffer | Binary;
		/* Excluded from this release type: timeoutContext */
	}

	/**
	 * @public
	 *
	 * A data key provider.  Allowed values:
	 *
	 * - aws, gcp, local, kmip or azure
	 * - (`mongodb-client-encryption>=6.0.1` only) a named key, in the form of:
	 *    `aws:<name>`, `gcp:<name>`, `local:<name>`, `kmip:<name>`, `azure:<name>`
	 *  where `name` is an alphanumeric string, underscores allowed.
	 */
	type ClientEncryptionDataKeyProvider = keyof KMSProviders;

	/**
	 * @public
	 * Options to provide when encrypting data.
	 */
	interface ClientEncryptionEncryptOptions {
		/**
		 * The algorithm to use for encryption.
		 */
		algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" | "AEAD_AES_256_CBC_HMAC_SHA_512-Random" | "Indexed" | "Unindexed" | "Range";
		/**
		 * The id of the Binary dataKey to use for encryption
		 */
		keyId?: Binary;
		/**
		 * A unique string name corresponding to an already existing dataKey.
		 */
		keyAltName?: string;
		/** The contention factor. */
		contentionFactor?: bigint | number;
		/**
		 * The query type.
		 */
		queryType?: "equality" | "range";
		/** The index options for a Queryable Encryption field supporting "range" queries.*/
		rangeOptions?: RangeOptions;
	}

	/**
	 * @public
	 * Additional settings to provide when creating a new `ClientEncryption` instance.
	 */
	interface ClientEncryptionOptions {
		/**
		 * The namespace of the key vault, used to store encryption keys
		 */
		keyVaultNamespace: string;
		/**
		 * A MongoClient used to fetch keys from a key vault. Defaults to client.
		 */
		keyVaultClient?: MongoClient | undefined;
		/**
		 * Options for specific KMS providers to use
		 */
		kmsProviders?: KMSProviders;
		/**
		 * Options for specifying a Socks5 proxy to use for connecting to the KMS.
		 */
		proxyOptions?: ProxyOptions;
		/**
		 * TLS options for kms providers to use.
		 */
		tlsOptions?: CSFLEKMSTlsOptions;
		/**
		 * @experimental
		 *
		 * The timeout setting to be used for all the operations on ClientEncryption.
		 *
		 * When provided, `timeoutMS` is used as the timeout for each operation executed on
		 * the ClientEncryption object.  For example:
		 *
		 * ```typescript
		 * const clientEncryption = new ClientEncryption(client, {
		 *  timeoutMS: 1_000
		 *  kmsProviders: { local: { key: '<KEY>' } }
		 * });
		 *
		 * // `1_000` is used as the timeout for createDataKey call
		 * await clientEncryption.createDataKey('local');
		 * ```
		 *
		 * If `timeoutMS` is configured on the provided client, the client's `timeoutMS` value
		 * will be used unless `timeoutMS` is also provided as a client encryption option.
		 *
		 * ```typescript
		 * const client = new MongoClient('<uri>', { timeoutMS: 2_000 });
		 *
		 * // timeoutMS is set to 1_000 on clientEncryption
		 * const clientEncryption = new ClientEncryption(client, {
		 *  timeoutMS: 1_000
		 *  kmsProviders: { local: { key: '<KEY>' } }
		 * });
		 * ```
		 */
		timeoutMS?: number;
	}

	/**
	 * @public
	 * @experimental
	 */
	interface ClientEncryptionRewrapManyDataKeyProviderOptions {
		provider: ClientEncryptionDataKeyProvider;
		masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | KMIPEncryptionKeyOptions | undefined;
	}

	/**
	 * @public
	 * @experimental
	 */
	interface ClientEncryptionRewrapManyDataKeyResult {
		/** The result of rewrapping data keys. If unset, no keys matched the filter. */
		bulkWriteResult?: BulkWriteResult;
	}

	/**
	 * @public
	 *
	 * TLS options to use when connecting. The spec specifically calls out which insecure
	 * tls options are not allowed:
	 *
	 *  - tlsAllowInvalidCertificates
	 *  - tlsAllowInvalidHostnames
	 *  - tlsInsecure
	 *
	 * These options are not included in the type, and are ignored if provided.
	 */
	type ClientEncryptionTlsOptions = Pick<MongoClientOptions, "tlsCAFile" | "tlsCertificateKeyFile" | "tlsCertificateKeyFilePassword">;

	/** @public */
	interface ClientInsertOneModel<TSchema> extends ClientWriteModel {
		name: "insertOne";
		/** The document to insert. */
		document: OptionalId<TSchema>;
	}

	/** @public */
	interface ClientInsertOneResult {
		/**
		 * The _id of the inserted document.
		 */
		insertedId: any;
	}

	/**
	 * @public
	 * @see https://github.com/mongodb/specifications/blob/master/source/mongodb-handshake/handshake.md#hello-command
	 */
	interface ClientMetadata {
		driver: {
			name: string;
			version: string;
		};
		os: {
			type: string;
			name?: NodeJS.Platform;
			architecture?: string;
			version?: string;
		};
		platform: string;
		application?: {
			name: string;
		};
		/** FaaS environment information */
		env?: {
			name: "aws.lambda" | "gcp.func" | "azure.func" | "vercel";
			timeout_sec?: Int32;
			memory_mb?: Int32;
			region?: string;
			url?: string;
		};
	}

	/** @public */
	interface ClientMetadataOptions {
		driverInfo?: {
			name?: string;
			version?: string;
			platform?: string;
		};
		appName?: string;
	}

	/** @public */
	interface ClientReplaceOneModel<TSchema> extends ClientWriteModel {
		name: "replaceOne";
		/**
		 * The filter used to determine if a document should be replaced.
		 * For a replaceOne operation, the first match is replaced.
		 */
		filter: Filter<TSchema>;
		/** The document with which to replace the matched document. */
		replacement: WithoutId<TSchema>;
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query. */
		upsert?: boolean;
	}

	/**
	 * A class representing a client session on the server
	 *
	 * NOTE: not meant to be instantiated directly.
	 * @public
	 */
	class ClientSession extends TypedEventEmitter<ClientSessionEvents> implements AsyncDisposable_2 {
		/* Excluded from this release type: client */
		/* Excluded from this release type: sessionPool */
		hasEnded: boolean;
		clientOptions: MongoOptions;
		supports: {
			causalConsistency: boolean;
		};
		clusterTime?: ClusterTime;
		operationTime?: Timestamp;
		explicit: boolean;
		/* Excluded from this release type: owner */
		defaultTransactionOptions: TransactionOptions;
		transaction: Transaction;
		/* Excluded from this release type: commitAttempted */
		/* Excluded from this release type: [kServerSession] */
		/* Excluded from this release type: [kSnapshotTime] */
		/* Excluded from this release type: [kSnapshotEnabled] */
		/* Excluded from this release type: [kPinnedConnection] */
		/* Excluded from this release type: [kTxnNumberIncrement] */
		/**
		 * @experimental
		 * Specifies the time an operation in a given `ClientSession` will run until it throws a timeout error
		 */
		timeoutMS?: number;
		/* Excluded from this release type: timeoutContext */
		/* Excluded from this release type: __constructor */
		/** The server id associated with this session */
		get id(): ServerSessionId | undefined;
		get serverSession(): ServerSession;
		/** Whether or not this session is configured for snapshot reads */
		get snapshotEnabled(): boolean;
		get loadBalanced(): boolean;
		/* Excluded from this release type: pinnedConnection */
		/* Excluded from this release type: pin */
		/* Excluded from this release type: unpin */
		get isPinned(): boolean;
		/**
		 * Frees any client-side resources held by the current session.  If a session is in a transaction,
		 * the transaction is aborted.
		 *
		 * Does not end the session on the server.
		 *
		 * @param options - Optional settings. Currently reserved for future use
		 */
		endSession(options?: EndSessionOptions): Promise<void>;
		/* Excluded from this release type: [Symbol.asyncDispose] */
		/* Excluded from this release type: asyncDispose */
		/**
		 * Advances the operationTime for a ClientSession.
		 *
		 * @param operationTime - the `BSON.Timestamp` of the operation type it is desired to advance to
		 */
		advanceOperationTime(operationTime: Timestamp): void;
		/**
		 * Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
		 *
		 * @param clusterTime - the $clusterTime returned by the server from another session in the form of a document containing the `BSON.Timestamp` clusterTime and signature
		 */
		advanceClusterTime(clusterTime: ClusterTime): void;
		/**
		 * Used to determine if this session equals another
		 *
		 * @param session - The session to compare to
		 */
		equals(session: ClientSession): boolean;
		/**
		 * Increment the transaction number on the internal ServerSession
		 *
		 * @privateRemarks
		 * This helper increments a value stored on the client session that will be
		 * added to the serverSession's txnNumber upon applying it to a command.
		 * This is because the serverSession is lazily acquired after a connection is obtained
		 */
		incrementTransactionNumber(): void;
		/** @returns whether this session is currently in a transaction or not */
		inTransaction(): boolean;
		/**
		 * Starts a new transaction with the given options.
		 *
		 * @remarks
		 * **IMPORTANT**: Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
		 * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
		 * undefined behaviour.
		 *
		 * @param options - Options for the transaction
		 */
		startTransaction(options?: TransactionOptions): void;
		/**
		 * Commits the currently active transaction in this session.
		 *
		 * @param options - Optional options, can be used to override `defaultTimeoutMS`.
		 */
		commitTransaction(options?: { timeoutMS?: number }): Promise<void>;
		/**
		 * Aborts the currently active transaction in this session.
		 *
		 * @param options - Optional options, can be used to override `defaultTimeoutMS`.
		 */
		abortTransaction(options?: { timeoutMS?: number }): Promise<void>;
		/* Excluded from this release type: abortTransaction */
		/**
		 * This is here to ensure that ClientSession is never serialized to BSON.
		 */
		toBSON(): never;
		/**
		 * Starts a transaction and runs a provided function, ensuring the commitTransaction is always attempted when all operations run in the function have completed.
		 *
		 * **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.
		 *
		 * **IMPORTANT:** Running operations in parallel is not supported during a transaction. The use of `Promise.all`,
		 * `Promise.allSettled`, `Promise.race`, etc to parallelize operations inside a transaction is
		 * undefined behaviour.
		 *
		 * **IMPORTANT:** When running an operation inside a `withTransaction` callback, if it is not
		 * provided the explicit session in its options, it will not be part of the transaction and it will not respect timeoutMS.
		 *
		 *
		 * @remarks
		 * - If all operations successfully complete and the `commitTransaction` operation is successful, then the provided function will return the result of the provided function.
		 * - 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.
		 *   - If the transaction is manually aborted within the provided function it will not throw.
		 * - If the driver needs to attempt to retry the operations, the provided function may be called multiple times.
		 *
		 * Checkout a descriptive example here:
		 * @see https://www.mongodb.com/blog/post/quick-start-nodejs--mongodb--how-to-implement-transactions
		 *
		 * If a command inside withTransaction fails:
		 * - It may cause the transaction on the server to be aborted.
		 * - This situation is normally handled transparently by the driver.
		 * - 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.
		 * - The driver will then retry the transaction indefinitely.
		 *
		 * To avoid this situation, the application must not silently handle errors within the provided function.
		 * 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.
		 *
		 * @param fn - callback to run within a transaction
		 * @param options - optional settings for the transaction
		 * @returns A raw command response or undefined
		 */
		withTransaction<T = any>(
			fn: WithTransactionCallback<T>,
			options?: TransactionOptions & {
				/**
				 * Configures a timeoutMS expiry for the entire withTransactionCallback.
				 *
				 * @remarks
				 * - The remaining timeout will not be applied to callback operations that do not use the ClientSession.
				 * - Overriding timeoutMS for operations executed using the explicit session inside the provided callback will result in a client-side error.
				 */
				timeoutMS?: number;
			}
		): Promise<T>;
	}

	/** @public */
	type ClientSessionEvents = {
		ended(session: ClientSession): void;
	};

	/** @public */
	interface ClientSessionOptions {
		/** Whether causal consistency should be enabled on this session */
		causalConsistency?: boolean;
		/** Whether all read operations should be read from the same snapshot for this session (NOTE: not compatible with `causalConsistency=true`) */
		snapshot?: boolean;
		/** The default TransactionOptions to use for transactions started on this session. */
		defaultTransactionOptions?: TransactionOptions;
		/**
		 * @public
		 * @experimental
		 * An overriding timeoutMS value to use for a client-side timeout.
		 * If not provided the session uses the timeoutMS specified on the MongoClient.
		 */
		defaultTimeoutMS?: number;
		/* Excluded from this release type: owner */
		/* Excluded from this release type: explicit */
		/* Excluded from this release type: initialClusterTime */
	}

	/** @public */
	interface ClientUpdateManyModel<TSchema> extends ClientWriteModel {
		name: "updateMany";
		/**
		 * The filter used to determine if a document should be updated.
		 * For an updateMany operation, all matches are updated.
		 */
		filter: Filter<TSchema>;
		/**
		 * The modifications to apply. The value can be either:
		 * UpdateFilter<Document> - A document that contains update operator expressions,
		 * Document[] - an aggregation pipeline.
		 */
		update: UpdateFilter<TSchema> | Document[];
		/** A set of filters specifying to which array elements an update should apply. */
		arrayFilters?: Document[];
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query. */
		upsert?: boolean;
	}

	/** @public */
	interface ClientUpdateOneModel<TSchema> extends ClientWriteModel {
		name: "updateOne";
		/**
		 * The filter used to determine if a document should be updated.
		 * For an updateOne operation, the first match is updated.
		 */
		filter: Filter<TSchema>;
		/**
		 * The modifications to apply. The value can be either:
		 * UpdateFilter<Document> - A document that contains update operator expressions,
		 * Document[] - an aggregation pipeline.
		 */
		update: UpdateFilter<TSchema> | Document[];
		/** A set of filters specifying to which array elements an update should apply. */
		arrayFilters?: Document[];
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query. */
		upsert?: boolean;
	}

	/** @public */
	interface ClientUpdateResult {
		/**
		 * The number of documents that matched the filter.
		 */
		matchedCount: number;
		/**
		 * The number of documents that were modified.
		 */
		modifiedCount: number;
		/**
		 * The _id field of the upserted document if an upsert occurred.
		 *
		 * It MUST be possible to discern between a BSON Null upserted ID value and this field being
		 * unset. If necessary, drivers MAY add a didUpsert boolean field to differentiate between
		 * these two cases.
		 */
		upsertedId?: any;
		/**
		 * Determines if the upsert did include an _id, which includes the case of the _id being null.
		 */
		didUpsert: boolean;
	}

	/** @public */
	interface ClientWriteModel {
		/**
		 * The namespace for the write.
		 *
		 * A namespace is a combination of the database name and the name of the collection: `<database-name>.<collection>`.
		 * All documents belong to a namespace.
		 *
		 * @see https://www.mongodb.com/docs/manual/reference/limits/#std-label-faq-dev-namespace
		 */
		namespace: string;
	}

	/**
	 * @public
	 * @deprecated This interface is deprecated and will be removed in a future release as it is not used
	 * in the driver
	 */
	interface CloseOptions {
		force?: boolean;
	}

	/** @public
	 * Configuration options for clustered collections
	 * @see https://www.mongodb.com/docs/manual/core/clustered-collections/
	 */
	interface ClusteredCollectionOptions extends Document {
		name?: string;
		key: Document;
		unique: boolean;
	}

	/**
	 * @public
	 * Gossiped in component for the cluster time tracking the state of user databases
	 * across the cluster. It may optionally include a signature identifying the process that
	 * generated such a value.
	 */
	interface ClusterTime {
		clusterTime: Timestamp;
		/** Used to validate the identity of a request or response's ClusterTime. */
		signature?: {
			hash: Binary;
			keyId: Long;
		};
	}

	/** @public */
	interface CollationOptions {
		locale: string;
		caseLevel?: boolean;
		caseFirst?: string;
		strength?: number;
		numericOrdering?: boolean;
		alternate?: string;
		maxVariable?: string;
		backwards?: boolean;
		normalization?: boolean;
	}

	/**
	 * The **Collection** class is an internal class that embodies a MongoDB collection
	 * allowing for insert/find/update/delete and other command operation on that MongoDB collection.
	 *
	 * **COLLECTION Cannot directly be instantiated**
	 * @public
	 *
	 * @example
	 * ```ts
	 * import { MongoClient } from 'mongodb';
	 *
	 * interface Pet {
	 *   name: string;
	 *   kind: 'dog' | 'cat' | 'fish';
	 * }
	 *
	 * const client = new MongoClient('mongodb://localhost:27017');
	 * const pets = client.db().collection<Pet>('pets');
	 *
	 * const petCursor = pets.find();
	 *
	 * for await (const pet of petCursor) {
	 *   console.log(`${pet.name} is a ${pet.kind}!`);
	 * }
	 * ```
	 */

	/** @public */
	interface CollectionInfo extends Document {
		name: string;
		type?: string;
		options?: Document;
		info?: {
			readOnly?: false;
			uuid?: Binary;
		};
		idIndex?: Document;
	}

	/** @public */
	interface CollectionOptions extends BSONSerializeOptions, WriteConcernOptions {
		/** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */
		readConcern?: ReadConcernLike;
		/** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */
		readPreference?: ReadPreferenceLike;
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
	}

	/* Excluded from this release type: CollectionPrivate */

	/* Excluded from this release type: COMMAND_FAILED */

	/* Excluded from this release type: COMMAND_STARTED */

	/* Excluded from this release type: COMMAND_SUCCEEDED */

	/**
	 * An event indicating the failure of a given command
	 * @public
	 * @category Event
	 */
	class CommandFailedEvent {
		address: string;
		/** Driver generated connection id */
		connectionId?: string | number;
		/**
		 * Server generated connection id
		 * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
		 */
		serverConnectionId: bigint | null;
		requestId: number;
		duration: number;
		commandName: string;
		failure: Error;
		serviceId?: ObjectId;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
		get hasServiceId(): boolean;
	}

	/* Excluded from this release type: CommandOperation */

	/** @public */
	interface CommandOperationOptions extends OperationOptions, WriteConcernOptions, ExplainOptions {
		/** Specify a read concern and level for the collection. (only MongoDB 3.2 or higher supported) */
		readConcern?: ReadConcernLike;
		/** Collation */
		collation?: CollationOptions;
		/**
		 * maxTimeMS is a server-side time limit in milliseconds for processing an operation.
		 */
		maxTimeMS?: number;
		/**
		 * Comment to apply to the operation.
		 *
		 * In server versions pre-4.4, 'comment' must be string.  A server
		 * error will be thrown if any other type is provided.
		 *
		 * In server versions 4.4 and above, 'comment' can be any valid BSON type.
		 */
		comment?: unknown;
		/** Should retry failed writes */
		retryWrites?: boolean;
		dbName?: string;
		authdb?: string;
		noResponse?: boolean;
	}

	/* Excluded from this release type: CommandOptions */

	/**
	 * An event indicating the start of a given command
	 * @public
	 * @category Event
	 */
	class CommandStartedEvent {
		commandObj?: Document;
		requestId: number;
		databaseName: string;
		commandName: string;
		command: Document;
		address: string;
		/** Driver generated connection id */
		connectionId?: string | number;
		/**
		 * Server generated connection id
		 * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId"
		 * from the server on 4.2+.
		 */
		serverConnectionId: bigint | null;
		serviceId?: ObjectId;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
		get hasServiceId(): boolean;
	}

	/**
	 * An event indicating the success of a given command
	 * @public
	 * @category Event
	 */
	class CommandSucceededEvent {
		address: string;
		/** Driver generated connection id */
		connectionId?: string | number;
		/**
		 * Server generated connection id
		 * Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
		 */
		serverConnectionId: bigint | null;
		requestId: number;
		duration: number;
		commandName: string;
		reply: unknown;
		serviceId?: ObjectId;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
		get hasServiceId(): boolean;
	}

	/** @public */
	type CommonEvents = "newListener" | "removeListener";

	/** @public */
	const Compressor: Readonly<{
		readonly none: 0;
		readonly snappy: 1;
		readonly zlib: 2;
		readonly zstd: 3;
	}>;

	/** @public */
	type Compressor = (typeof Compressor)[CompressorName];

	/** @public */
	type CompressorName = keyof typeof Compressor;

	/** @public */
	type Condition<T> = AlternativeType<T> | FilterOperators<AlternativeType<T>>;

	/* Excluded from this release type: configureExplicitResourceManagement */

	/* Excluded from this release type: Connection */

	/* Excluded from this release type: CONNECTION_CHECK_OUT_FAILED */

	/* Excluded from this release type: CONNECTION_CHECK_OUT_STARTED */

	/* Excluded from this release type: CONNECTION_CHECKED_IN */

	/* Excluded from this release type: CONNECTION_CHECKED_OUT */

	/* Excluded from this release type: CONNECTION_CLOSED */

	/* Excluded from this release type: CONNECTION_CREATED */

	/* Excluded from this release type: CONNECTION_POOL_CLEARED */

	/* Excluded from this release type: CONNECTION_POOL_CLOSED */

	/* Excluded from this release type: CONNECTION_POOL_CREATED */

	/* Excluded from this release type: CONNECTION_POOL_READY */

	/* Excluded from this release type: CONNECTION_READY */

	/**
	 * An event published when a connection is checked into the connection pool
	 * @public
	 * @category Event
	 */
	class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {
		/** The id of the connection */
		connectionId: number | "<monitor>";
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a connection is checked out of the connection pool
	 * @public
	 * @category Event
	 */
	class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {
		/** The id of the connection */
		connectionId: number | "<monitor>";
		/* Excluded from this release type: name */
		/**
		 * The time it took to check out the connection.
		 * More specifically, the time elapsed between
		 * emitting a `ConnectionCheckOutStartedEvent`
		 * and emitting this event as part of the same checking out.
		 *
		 */
		durationMS: number;
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a request to check a connection out fails
	 * @public
	 * @category Event
	 */
	class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {
		/** The reason the attempt to check out failed */
		reason: string;
		/* Excluded from this release type: error */
		/* Excluded from this release type: name */
		/**
		 * The time it took to check out the connection.
		 * More specifically, the time elapsed between
		 * emitting a `ConnectionCheckOutStartedEvent`
		 * and emitting this event as part of the same check out.
		 */
		durationMS: number;
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a request to check a connection out begins
	 * @public
	 * @category Event
	 */
	class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a connection is closed
	 * @public
	 * @category Event
	 */
	class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {
		/** The id of the connection */
		connectionId: number | "<monitor>";
		/** The reason the connection was closed */
		reason: string;
		serviceId?: ObjectId;
		/* Excluded from this release type: name */
		/* Excluded from this release type: error */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a connection pool creates a new connection
	 * @public
	 * @category Event
	 */
	class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {
		/** A monotonically increasing, per-pool id for the newly created connection */
		connectionId: number | "<monitor>";
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	type ConnectionEvents = {
		commandStarted(event: CommandStartedEvent): void;
		commandSucceeded(event: CommandSucceededEvent): void;
		commandFailed(event: CommandFailedEvent): void;
		clusterTimeReceived(clusterTime: Document): void;
		close(): void;
		pinned(pinType: string): void;
		unpinned(pinType: string): void;
	};

	/** @public */
	interface ConnectionOptions extends StreamDescriptionOptions, ProxyOptions {
		id: number | "<monitor>";
		generation: number;
		/* Excluded from this release type: autoEncrypter */
		serverApi?: ServerApi;
		monitorCommands: boolean;
		/* Excluded from this release type: connectionType */
		credentials?: MongoCredentials;
		/* Excluded from this release type: authProviders */
		connectTimeoutMS?: number;
		tls: boolean;
		noDelay?: boolean;
		socketTimeoutMS?: number;
		cancellationToken?: CancellationToken;
		metadata: ClientMetadata;
		/* Excluded from this release type: extendedMetadata */
		/* Excluded from this release type: mongoLogger */
	}

	/* Excluded from this release type: ConnectionPool */

	/**
	 * An event published when a connection pool is cleared
	 * @public
	 * @category Event
	 */
	class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {
		/* Excluded from this release type: serviceId */
		interruptInUseConnections?: boolean;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a connection pool is closed
	 * @public
	 * @category Event
	 */
	class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a connection pool is created
	 * @public
	 * @category Event
	 */
	class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {
		/** The options used to create this connection pool */
		options: Pick<ConnectionPoolOptions, "maxPoolSize" | "minPoolSize" | "maxConnecting" | "maxIdleTimeMS" | "waitQueueTimeoutMS">;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	type ConnectionPoolEvents = {
		connectionPoolCreated(event: ConnectionPoolCreatedEvent): void;
		connectionPoolReady(event: ConnectionPoolReadyEvent): void;
		connectionPoolClosed(event: ConnectionPoolClosedEvent): void;
		connectionPoolCleared(event: ConnectionPoolClearedEvent): void;
		connectionCreated(event: ConnectionCreatedEvent): void;
		connectionReady(event: ConnectionReadyEvent): void;
		connectionClosed(event: ConnectionClosedEvent): void;
		connectionCheckOutStarted(event: ConnectionCheckOutStartedEvent): void;
		connectionCheckOutFailed(event: ConnectionCheckOutFailedEvent): void;
		connectionCheckedOut(event: ConnectionCheckedOutEvent): void;
		connectionCheckedIn(event: ConnectionCheckedInEvent): void;
	} & Omit<ConnectionEvents, "close" | "message">;

	/* Excluded from this release type: ConnectionPoolMetrics */

	/**
	 * The base class for all monitoring events published from the connection pool
	 * @public
	 * @category Event
	 */
	abstract class ConnectionPoolMonitoringEvent {
		/** A timestamp when the event was created  */
		time: Date;
		/** The address (host/port pair) of the pool */
		address: string;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	interface ConnectionPoolOptions extends Omit<ConnectionOptions, "id" | "generation"> {
		/** The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections. */
		maxPoolSize: number;
		/** The minimum number of connections that MUST exist at any moment in a single connection pool. */
		minPoolSize: number;
		/** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
		maxConnecting: number;
		/** The maximum amount of time a connection should remain idle in the connection pool before being marked idle. */
		maxIdleTimeMS: number;
		/** 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. */
		waitQueueTimeoutMS: number;
		/** If we are in load balancer mode. */
		loadBalanced: boolean;
		/* Excluded from this release type: minPoolSizeCheckFrequencyMS */
	}

	/**
	 * An event published when a connection pool is ready
	 * @public
	 * @category Event
	 */
	class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent {
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * An event published when a connection is ready for use
	 * @public
	 * @category Event
	 */
	class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {
		/** The id of the connection */
		connectionId: number | "<monitor>";
		/**
		 * The time it took to establish the connection.
		 * In accordance with the definition of establishment of a connection
		 * specified by `ConnectionPoolOptions.maxConnecting`,
		 * it is the time elapsed between emitting a `ConnectionCreatedEvent`
		 * and emitting this event as part of the same checking out.
		 *
		 * Naturally, when establishing a connection is part of checking out,
		 * this duration is not greater than
		 * `ConnectionCheckedOutEvent.duration`.
		 */
		durationMS: number;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	interface ConnectOptions {
		readPreference?: ReadPreference;
	}

	/** @public */
	interface CountDocumentsOptions extends AggregateOptions {
		/** The number of documents to skip. */
		skip?: number;
		/** The maximum amount of documents to consider. */
		limit?: number;
	}

	/** @public */
	interface CountOptions extends CommandOperationOptions {
		/** The number of documents to skip. */
		skip?: number;
		/** The maximum amounts to count before aborting. */
		limit?: number;
		/**
		 * Number of milliseconds to wait before aborting the query.
		 */
		maxTimeMS?: number;
		/** An index name hint for the query. */
		hint?: string | Document;
	}

	/** @public */
	interface CreateCollectionOptions extends CommandOperationOptions {
		/** Create a capped collection */
		capped?: boolean;
		/** @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. */
		autoIndexId?: boolean;
		/** The size of the capped collection in bytes */
		size?: number;
		/** The maximum number of documents in the capped collection */
		max?: number;
		/** Available for the MMAPv1 storage engine only to set the usePowerOf2Sizes and the noPadding flag */
		flags?: number;
		/** Allows users to specify configuration to the storage engine on a per-collection basis when creating a collection */
		storageEngine?: Document;
		/** Allows users to specify validation rules or expressions for the collection. For more information, see Document Validation */
		validator?: Document;
		/** Determines how strictly MongoDB applies the validation rules to existing documents during an update */
		validationLevel?: string;
		/** Determines whether to error on invalid documents or just warn about the violations but allow invalid documents to be inserted */
		validationAction?: string;
		/** Allows users to specify a default configuration for indexes when creating a collection */
		indexOptionDefaults?: Document;
		/** 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) */
		viewOn?: string;
		/** An array that consists of the aggregation pipeline stage. Creates the view by applying the specified pipeline to the viewOn collection or view */
		pipeline?: Document[];
		/** A primary key factory function for generation of custom _id keys. */
		pkFactory?: PkFactory;
		/** A document specifying configuration options for timeseries collections. */
		timeseries?: TimeSeriesCollectionOptions;
		/** A document specifying configuration options for clustered collections. For MongoDB 5.3 and above. */
		clusteredIndex?: ClusteredCollectionOptions;
		/** The number of seconds after which a document in a timeseries or clustered collection expires. */
		expireAfterSeconds?: number;
		/** @experimental */
		encryptedFields?: Document;
		/**
		 * If set, enables pre-update and post-update document events to be included for any
		 * change streams that listen on this collection.
		 */
		changeStreamPreAndPostImages?: {
			enabled: boolean;
		};
	}

	/** @public */
	interface CreateIndexesOptions extends Omit<CommandOperationOptions, "writeConcern"> {
		/** Creates the index in the background, yielding whenever possible. */
		background?: boolean;
		/** Creates an unique index. */
		unique?: boolean;
		/** Override the autogenerated index name (useful if the resulting name is larger than 128 bytes) */
		name?: string;
		/** Creates a partial index based on the given filter object (MongoDB 3.2 or higher) */
		partialFilterExpression?: Document;
		/** Creates a sparse index. */
		sparse?: boolean;
		/** Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) */
		expireAfterSeconds?: number;
		/** Allows users to configure the storage engine on a per-index basis when creating an index. (MongoDB 3.0 or higher) */
		storageEngine?: Document;
		/** (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. */
		commitQuorum?: number | string;
		/** Specifies the index version number, either 0 or 1. */
		version?: number;
		weights?: Document;
		default_language?: string;
		language_override?: string;
		textIndexVersion?: number;
		"2dsphereIndexVersion"?: number;
		bits?: number;
		/** For geospatial indexes set the lower bound for the co-ordinates. */
		min?: number;
		/** For geospatial indexes set the high bound for the co-ordinates. */
		max?: number;
		bucketSize?: number;
		wildcardProjection?: Document;
		/** 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) */
		hidden?: boolean;
	}

	/** @public */
	type CSFLEKMSTlsOptions = {
		aws?: ClientEncryptionTlsOptions;
		gcp?: ClientEncryptionTlsOptions;
		kmip?: ClientEncryptionTlsOptions;
		local?: ClientEncryptionTlsOptions;
		azure?: ClientEncryptionTlsOptions;
		[key: string]: ClientEncryptionTlsOptions | undefined;
	};

	/* Excluded from this release type: CSOTTimeoutContext */

	/* Excluded from this release type: CSOTTimeoutContextOptions */

	/** @public */
	const CURSOR_FLAGS: readonly ["tailable", "oplogReplay", "noCursorTimeout", "awaitData", "exhaust", "partial"];

	/** @public */
	type CursorFlag = (typeof CURSOR_FLAGS)[number];

	/* Excluded from this release type: CursorResponse */

	/** @public */
	interface CursorStreamOptions {
		/** A transformation method applied to each document emitted by the stream */
		transform?(this: void, doc: Document): Document;
	}

	/* Excluded from this release type: CursorTimeoutContext */

	/**
	 * @public
	 * @experimental
	 * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
	 * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
	 * `cursor.next()`.
	 * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
	 *
	 * Depending on the type of cursor being used, this option has different default values.
	 * For non-tailable cursors, this value defaults to `'cursorLifetime'`
	 * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
	 * definition can have an arbitrarily long lifetime.
	 *
	 * @example
	 * ```ts
	 * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
	 * for await (const doc of cursor) {
	 *  // process doc
	 *  // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
	 *  // will continue to iterate successfully otherwise, regardless of the number of batches.
	 * }
	 * ```
	 *
	 * @example
	 * ```ts
	 * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
	 * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
	 * ```
	 */
	const CursorTimeoutMode: Readonly<{
		readonly ITERATION: "iteration";
		readonly LIFETIME: "cursorLifetime";
	}>;

	/**
	 * @public
	 * @experimental
	 */
	type CursorTimeoutMode = (typeof CursorTimeoutMode)[keyof typeof CursorTimeoutMode];

	/**
	 * @public
	 * The schema for a DataKey in the key vault collection.
	 */
	interface DataKey {
		_id: UUID;
		version?: number;
		keyAltNames?: string[];
		keyMaterial: Binary;
		creationDate: Date;
		updateDate: Date;
		status: number;
		masterKey: Document;
	}

	/**
	 * The **Db** class is a class that represents a MongoDB Database.
	 * @public
	 *
	 * @example
	 * ```ts
	 * import { MongoClient } from 'mongodb';
	 *
	 * interface Pet {
	 *   name: string;
	 *   kind: 'dog' | 'cat' | 'fish';
	 * }
	 *
	 * const client = new MongoClient('mongodb://localhost:27017');
	 * const db = client.db();
	 *
	 * // Create a collection that validates our union
	 * await db.createCollection<Pet>('pets', {
	 *   validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }
	 * })
	 * ```
	 */
	class Db {
		/* Excluded from this release type: s */
		/* Excluded from this release type: client */
		static SYSTEM_NAMESPACE_COLLECTION: string;
		static SYSTEM_INDEX_COLLECTION: string;
		static SYSTEM_PROFILE_COLLECTION: string;
		static SYSTEM_USER_COLLECTION: string;
		static SYSTEM_COMMAND_COLLECTION: string;
		static SYSTEM_JS_COLLECTION: string;
		/**
		 * Creates a new Db instance.
		 *
		 * Db name cannot contain a dot, the server may apply more restrictions when an operation is run.
		 *
		 * @param client - The MongoClient for the database.
		 * @param databaseName - The name of the database this instance represents.
		 * @param options - Optional settings for Db construction.
		 */
		constructor(client: MongoClient, databaseName: string, options?: DbOptions);
		get databaseName(): string;
		get options(): DbOptions | undefined;
		/**
		 * Check if a secondary can be used (because the read preference is *not* set to primary)
		 */
		get secondaryOk(): boolean;
		get readConcern(): ReadConcern | undefined;
		/**
		 * The current readPreference of the Db. If not explicitly defined for
		 * this Db, will be inherited from the parent MongoClient
		 */
		get readPreference(): ReadPreference;
		get bsonOptions(): BSONSerializeOptions;
		get writeConcern(): WriteConcern | undefined;
		get namespace(): string;
		get timeoutMS(): number | undefined;
		/**
		 * Create a new collection on a server with the specified options. Use this to create capped collections.
		 * More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
		 *
		 * Collection namespace validation is performed server-side.
		 *
		 * @param name - The name of the collection to create
		 * @param options - Optional settings for the command
		 */
		createCollection<TSchema extends Document = Document>(name: string, options?: CreateCollectionOptions): Promise<Collection<TSchema>>;
		/**
		 * Execute a command
		 *
		 * @remarks
		 * This command does not inherit options from the MongoClient.
		 *
		 * The driver will ensure the following fields are attached to the command sent to the server:
		 * - `lsid` - sourced from an implicit session or options.session
		 * - `$readPreference` - defaults to primary or can be configured by options.readPreference
		 * - `$db` - sourced from the name of this database
		 *
		 * If the client has a serverApi setting:
		 * - `apiVersion`
		 * - `apiStrict`
		 * - `apiDeprecationErrors`
		 *
		 * When in a transaction:
		 * - `readConcern` - sourced from readConcern set on the TransactionOptions
		 * - `writeConcern` - sourced from writeConcern set on the TransactionOptions
		 *
		 * Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.
		 *
		 * @param command - The command to run
		 * @param options - Optional settings for the command
		 */
		command(command: Document, options?: RunCommandOptions): Promise<Document>;
		/**
		 * Execute an aggregation framework pipeline against the database.
		 *
		 * @param pipeline - An array of aggregation stages to be executed
		 * @param options - Optional settings for the command
		 */
		aggregate<T extends Document = Document>(pipeline?: Document[], options?: AggregateOptions): AggregationCursor<T>;
		/** Return the Admin db instance */
		admin(): Admin;
		/**
		 * Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
		 *
		 * Collection namespace validation is performed server-side.
		 *
		 * @param name - the collection name we wish to access.
		 * @returns return the new Collection instance
		 */
		collection<TSchema extends Document = Document>(name: string, options?: CollectionOptions): Collection<TSchema>;
		/**
		 * Get all the db statistics.
		 *
		 * @param options - Optional settings for the command
		 */
		stats(options?: DbStatsOptions): Promise<Document>;
		/**
		 * List all collections of this database with optional filter
		 *
		 * @param filter - Query to filter collections by
		 * @param options - Optional settings for the command
		 */
		listCollections(
			filter: Document,
			options: Exclude<ListCollectionsOptions, "nameOnly"> & {
				nameOnly: true;
			}
		): ListCollectionsCursor<Pick<CollectionInfo, "name" | "type">>;
		listCollections(
			filter: Document,
			options: Exclude<ListCollectionsOptions, "nameOnly"> & {
				nameOnly: false;
			}
		): ListCollectionsCursor<CollectionInfo>;
		listCollections<T extends Pick<CollectionInfo, "name" | "type"> | CollectionInfo = Pick<CollectionInfo, "name" | "type"> | CollectionInfo>(filter?: Document, options?: ListCollectionsOptions): ListCollectionsCursor<T>;
		/**
		 * Rename a collection.
		 *
		 * @remarks
		 * This operation does not inherit options from the MongoClient.
		 *
		 * @param fromCollection - Name of current collection to rename
		 * @param toCollection - New name of of the collection
		 * @param options - Optional settings for the command
		 */
		renameCollection<TSchema extends Document = Document>(fromCollection: string, toCollection: string, options?: RenameOptions): Promise<Collection<TSchema>>;
		/**
		 * Drop a collection from the database, removing it permanently. New accesses will create a new collection.
		 *
		 * @param name - Name of collection to drop
		 * @param options - Optional settings for the command
		 */
		dropCollection(name: string, options?: DropCollectionOptions): Promise<boolean>;
		/**
		 * Drop a database, removing it permanently from the server.
		 *
		 * @param options - Optional settings for the command
		 */
		dropDatabase(options?: DropDatabaseOptions): Promise<boolean>;
		/**
		 * Fetch all collections for the current db.
		 *
		 * @param options - Optional settings for the command
		 */
		collections(options?: ListCollectionsOptions): Promise<Collection[]>;
		/**
		 * Creates an index on the db and collection.
		 *
		 * @param name - Name of the collection to create the index on.
		 * @param indexSpec - Specify the field to index, or an index specification
		 * @param options - Optional settings for the command
		 */
		createIndex(name: string, indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
		/**
		 * Remove a user from a database
		 *
		 * @param username - The username to remove
		 * @param options - Optional settings for the command
		 */
		removeUser(username: string, options?: RemoveUserOptions): Promise<boolean>;
		/**
		 * Set the current profiling level of MongoDB
		 *
		 * @param level - The new profiling level (off, slow_only, all).
		 * @param options - Optional settings for the command
		 */
		setProfilingLevel(level: ProfilingLevel, options?: SetProfilingLevelOptions): Promise<ProfilingLevel>;
		/**
		 * Retrieve the current profiling Level for MongoDB
		 *
		 * @param options - Optional settings for the command
		 */
		profilingLevel(options?: ProfilingLevelOptions): Promise<string>;
		/**
		 * Retrieves this collections index info.
		 *
		 * @param name - The name of the collection.
		 * @param options - Optional settings for the command
		 */
		indexInformation(
			name: string,
			options: IndexInformationOptions & {
				full: true;
			}
		): Promise<IndexDescriptionInfo[]>;
		indexInformation(
			name: string,
			options: IndexInformationOptions & {
				full?: false;
			}
		): Promise<IndexDescriptionCompact>;
		indexInformation(name: string, options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
		indexInformation(name: string): Promise<IndexDescriptionCompact>;
		/**
		 * A low level cursor API providing basic driver functionality:
		 * - ClientSession management
		 * - ReadPreference for server selection
		 * - Running getMores automatically when a local batch is exhausted
		 *
		 * @param command - The command that will start a cursor on the server.
		 * @param options - Configurations for running the command, bson options will apply to getMores
		 */
		runCursorCommand(command: Document, options?: RunCursorCommandOptions): RunCommandCursor;
	}

	/* Excluded from this release type: DB_AGGREGATE_COLLECTION */

	/** @public */
	interface DbOptions extends BSONSerializeOptions, WriteConcernOptions {
		/** If the database authentication is dependent on another databaseName. */
		authSource?: string;
		/** Force server to assign _id values instead of driver. */
		forceServerObjectId?: boolean;
		/** The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). */
		readPreference?: ReadPreferenceLike;
		/** A primary key factory object for generation of custom _id keys. */
		pkFactory?: PkFactory;
		/** Specify a read concern for the collection. (only MongoDB 3.2 or higher supported) */
		readConcern?: ReadConcern;
		/** Should retry failed writes */
		retryWrites?: boolean;
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
	}

	/** @public */
	interface DbStatsOptions extends CommandOperationOptions {
		/** Divide the returned sizes by scale value. */
		scale?: number;
	}

	/** @public */
	interface DeleteManyModel<TSchema extends Document = Document> {
		/** The filter to limit the deleted documents. */
		filter: Filter<TSchema>;
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
	}

	/** @public */
	interface DeleteOneModel<TSchema extends Document = Document> {
		/** The filter to limit the deleted documents. */
		filter: Filter<TSchema>;
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
	}

	/** @public */
	interface DeleteOptions extends CommandOperationOptions, WriteConcernOptions {
		/** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */
		ordered?: boolean;
		/** Specifies the collation to use for the operation */
		collation?: CollationOptions;
		/** Specify that the update query should only consider plans using the hinted index */
		hint?: string | Document;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
	}

	/** @public */
	interface DeleteResult {
		/** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined. */
		acknowledged: boolean;
		/** The number of documents that were deleted */
		deletedCount: number;
	}

	/** @public */
	interface DeleteStatement {
		/** The query that matches documents to delete. */
		q: Document;
		/** The number of matching documents to delete. */
		limit: number;
		/** Specifies the collation to use for the operation. */
		collation?: CollationOptions;
		/** A document or string that specifies the index to use to support the query predicate. */
		hint?: Hint;
	}

	/** @public */
	type DistinctOptions = CommandOperationOptions;

	/** @public */
	interface DriverInfo {
		name?: string;
		version?: string;
		platform?: string;
	}

	/** @public */
	interface DropCollectionOptions extends CommandOperationOptions {
		/** @experimental */
		encryptedFields?: Document;
	}

	/** @public */
	type DropDatabaseOptions = CommandOperationOptions;

	/** @public */
	type DropIndexesOptions = CommandOperationOptions;

	/* Excluded from this release type: Encrypter */

	/* Excluded from this release type: EncrypterOptions */

	/** @public */
	interface EndSessionOptions {
		/* Excluded from this release type: error */
		force?: boolean;
		forceClear?: boolean;
		/** Specifies the time an operation will run until it throws a timeout error */
		timeoutMS?: number;
	}

	/** TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions @public */
	type EnhancedOmit<TRecordOrUnion, KeyUnion> = string extends keyof TRecordOrUnion ? TRecordOrUnion : TRecordOrUnion extends any ? Pick<TRecordOrUnion, Exclude<keyof TRecordOrUnion, KeyUnion>> : never;

	/** @public */
	interface ErrorDescription extends Document {
		message?: string;
		errmsg?: string;
		$err?: string;
		errorLabels?: string[];
		errInfo?: Document;
	}

	/** @public */
	interface EstimatedDocumentCountOptions extends CommandOperationOptions {
		/**
		 * The maximum amount of time to allow the operation to run.
		 *
		 * This option is sent only if the caller explicitly provides a value. The default is to not send a value.
		 */
		maxTimeMS?: number;
	}

	/** @public */
	type EventEmitterWithState = {
		/* Excluded from this release type: stateChanged */
	};

	/**
	 * Event description type
	 * @public
	 */
	type EventsDescription = Record<string, GenericListener>;

	/* Excluded from this release type: Explain */

	/**
	 * @public
	 *
	 * A base class for any cursors that have `explain()` methods.
	 */
	abstract class ExplainableCursor<TSchema> extends AbstractCursor<TSchema> {
		/** Execute the explain for the cursor */
		abstract explain(): Promise<Document>;
		abstract explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;
		abstract explain(options: { timeoutMS?: number }): Promise<Document>;
		abstract explain(
			verbosity: ExplainVerbosityLike | ExplainCommandOptions,
			options: {
				timeoutMS?: number;
			}
		): Promise<Document>;
		abstract explain(
			verbosity?:
				| ExplainVerbosityLike
				| ExplainCommandOptions
				| {
						timeoutMS?: number;
				  },
			options?: {
				timeoutMS?: number;
			}
		): Promise<Document>;
		protected resolveExplainTimeoutOptions(
			verbosity?:
				| ExplainVerbosityLike
				| ExplainCommandOptions
				| {
						timeoutMS?: number;
				  },
			options?: {
				timeoutMS?: number;
			}
		): {
			timeout?: {
				timeoutMS?: number;
			};
			explain?: ExplainVerbosityLike | ExplainCommandOptions;
		};
	}

	/** @public */
	interface ExplainCommandOptions {
		/** The explain verbosity for the command. */
		verbosity: ExplainVerbosity;
		/** The maxTimeMS setting for the command. */
		maxTimeMS?: number;
	}

	/**
	 * @public
	 *
	 * When set, this configures an explain command.  Valid values are boolean (for legacy compatibility,
	 * see {@link ExplainVerbosityLike}), a string containing the explain verbosity, or an object containing the verbosity and
	 * an optional maxTimeMS.
	 *
	 * Examples of valid usage:
	 *
	 * ```typescript
	 * collection.find({ name: 'john doe' }, { explain: true });
	 * collection.find({ name: 'john doe' }, { explain: false });
	 * collection.find({ name: 'john doe' }, { explain: 'queryPlanner' });
	 * collection.find({ name: 'john doe' }, { explain: { verbosity: 'queryPlanner' } });
	 * ```
	 *
	 * maxTimeMS can be configured to limit the amount of time the server
	 * spends executing an explain by providing an object:
	 *
	 * ```typescript
	 * // limits the `explain` command to no more than 2 seconds
	 * collection.find({ name: 'john doe' }, {
	 *   explain:  {
	 *    verbosity: 'queryPlanner',
	 *    maxTimeMS: 2000
	 *  }
	 * });
	 * ```
	 */
	interface ExplainOptions {
		/** Specifies the verbosity mode for the explain output. */
		explain?: ExplainVerbosityLike | ExplainCommandOptions;
	}

	/** @public */
	const ExplainVerbosity: Readonly<{
		readonly queryPlanner: "queryPlanner";
		readonly queryPlannerExtended: "queryPlannerExtended";
		readonly executionStats: "executionStats";
		readonly allPlansExecution: "allPlansExecution";
	}>;

	/** @public */
	type ExplainVerbosity = string;

	/**
	 * For backwards compatibility, true is interpreted as "allPlansExecution"
	 * and false as "queryPlanner".
	 * @public
	 */
	type ExplainVerbosityLike = ExplainVerbosity | boolean;

	/** A MongoDB filter can be some portion of the schema or a set of operators @public */
	type Filter<TSchema> = {
		[P in keyof WithId<TSchema>]?: Condition<WithId<TSchema>[P]>;
	} & RootFilterOperators<WithId<TSchema>>;

	/** @public */
	type FilterOperations<T> = T extends Record<string, any>
		? {
				[key in keyof T]?: FilterOperators<T[key]>;
		  }
		: FilterOperators<T>;

	/** @public */
	interface FilterOperators<TValue> extends NonObjectIdLikeDocument {
		$eq?: TValue;
		$gt?: TValue;
		$gte?: TValue;
		$in?: ReadonlyArray<TValue>;
		$lt?: TValue;
		$lte?: TValue;
		$ne?: TValue;
		$nin?: ReadonlyArray<TValue>;
		$not?: TValue extends string ? FilterOperators<TValue> | RegExp : FilterOperators<TValue>;
		/**
		 * When `true`, `$exists` matches the documents that contain the field,
		 * including documents where the field value is null.
		 */
		$exists?: boolean;
		$type?: BSONType | BSONTypeAlias;
		$expr?: Record<string, any>;
		$jsonSchema?: Record<string, any>;
		$mod?: TValue extends number ? [number, number] : never;
		$regex?: TValue extends string ? RegExp | BSONRegExp | string : never;
		$options?: TValue extends string ? string : never;
		$geoIntersects?: {
			$geometry: Document;
		};
		$geoWithin?: Document;
		$near?: Document;
		$nearSphere?: Document;
		$maxDistance?: number;
		$all?: ReadonlyArray<any>;
		$elemMatch?: Document;
		$size?: TValue extends ReadonlyArray<any> ? number : never;
		$bitsAllClear?: BitwiseFilter;
		$bitsAllSet?: BitwiseFilter;
		$bitsAnyClear?: BitwiseFilter;
		$bitsAnySet?: BitwiseFilter;
		$rand?: Record<string, never>;
	}

	/** @public */
	class FindCursor<TSchema = any> extends ExplainableCursor<TSchema> {
		/* Excluded from this release type: cursorFilter */
		/* Excluded from this release type: numReturned */
		/* Excluded from this release type: findOptions */
		/* Excluded from this release type: __constructor */
		clone(): FindCursor<TSchema>;
		map<T>(transform: (doc: TSchema) => T): FindCursor<T>;
		/* Excluded from this release type: _initialize */
		/* Excluded from this release type: getMore */
		/**
		 * Get the count of documents for this cursor
		 * @deprecated Use `collection.estimatedDocumentCount` or `collection.countDocuments` instead
		 */
		count(options?: CountOptions): Promise<number>;
		/** Execute the explain for the cursor */
		explain(): Promise<Document>;
		explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Promise<Document>;
		explain(options: { timeoutMS?: number }): Promise<Document>;
		explain(
			verbosity: ExplainVerbosityLike | ExplainCommandOptions,
			options: {
				timeoutMS?: number;
			}
		): Promise<Document>;
		/** Set the cursor query */
		filter(filter: Document): this;
		/**
		 * Set the cursor hint
		 *
		 * @param hint - If specified, then the query system will only consider plans using the hinted index.
		 */
		hint(hint: Hint): this;
		/**
		 * Set the cursor min
		 *
		 * @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.
		 */
		min(min: Document): this;
		/**
		 * Set the cursor max
		 *
		 * @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.
		 */
		max(max: Document): this;
		/**
		 * Set the cursor returnKey.
		 * If set to true, modifies the cursor to only return the index field or fields for the results of the query, rather than documents.
		 * 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.
		 *
		 * @param value - the returnKey value.
		 */
		returnKey(value: boolean): this;
		/**
		 * 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.
		 *
		 * @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.
		 */
		showRecordId(value: boolean): this;
		/**
		 * Add a query modifier to the cursor query
		 *
		 * @param name - The query modifier (must start with $, such as $orderby etc)
		 * @param value - The modifier value.
		 */
		addQueryModifier(name: string, value: string | boolean | number | Document): this;
		/**
		 * Add a comment to the cursor query allowing for tracking the comment in the log.
		 *
		 * @param value - The comment attached to this query.
		 */
		comment(value: string): this;
		/**
		 * 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)
		 *
		 * @param value - Number of milliseconds to wait before aborting the tailed query.
		 */
		maxAwaitTimeMS(value: number): this;
		/**
		 * Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
		 *
		 * @param value - Number of milliseconds to wait before aborting the query.
		 */
		maxTimeMS(value: number): this;
		/**
		 * Add a project stage to the aggregation pipeline
		 *
		 * @remarks
		 * In order to strictly type this function you must provide an interface
		 * that represents the effect of your projection on the result documents.
		 *
		 * By default chaining a projection to your cursor changes the returned type to the generic
		 * {@link Document} type.
		 * You should specify a parameterized type to have assertions on your final results.
		 *
		 * @example
		 * ```typescript
		 * // Best way
		 * const docs: FindCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
		 * // Flexible way
		 * const docs: FindCursor<Document> = cursor.project({ _id: 0, a: true });
		 * ```
		 *
		 * @remarks
		 *
		 * **Note for Typescript Users:** adding a transform changes the return type of the iteration of this cursor,
		 * it **does not** return a new instance of a cursor. This means when calling project,
		 * you should always assign the result to a new variable in order to get a correctly typed cursor variable.
		 * Take note of the following example:
		 *
		 * @example
		 * ```typescript
		 * const cursor: FindCursor<{ a: number; b: string }> = coll.find();
		 * const projectCursor = cursor.project<{ a: number }>({ _id: 0, a: true });
		 * const aPropOnlyArray: {a: number}[] = await projectCursor.toArray();
		 *
		 * // or always use chaining and save the final cursor
		 *
		 * const cursor = coll.find().project<{ a: string }>({
		 *   _id: 0,
		 *   a: { $convert: { input: '$a', to: 'string' }
		 * }});
		 * ```
		 */
		project<T extends Document = Document>(value: Document): FindCursor<T>;
		/**
		 * Sets the sort order of the cursor query.
		 *
		 * @param sort - The key or keys set for the sort.
		 * @param direction - The direction of the sorting (1 or -1).
		 */
		sort(sort: Sort | string, direction?: SortDirection): this;
		/**
		 * Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher)
		 *
		 * @remarks
		 * {@link https://www.mongodb.com/docs/manual/reference/command/find/#find-cmd-allowdiskuse | find command allowDiskUse documentation}
		 */
		allowDiskUse(allow?: boolean): this;
		/**
		 * Set the collation options for the cursor.
		 *
		 * @param value - The cursor collation options (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
		 */
		collation(value: CollationOptions): this;
		/**
		 * Set the limit for the cursor.
		 *
		 * @param value - The limit for the cursor query.
		 */
		limit(value: number): this;
		/**
		 * Set the skip for the cursor.
		 *
		 * @param value - The skip for the cursor query.
		 */
		skip(value: number): this;
	}

	/** @public */
	interface FindOneAndDeleteOptions extends CommandOperationOptions {
		/** 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.*/
		hint?: Document;
		/** Limits the fields to return for all matching documents. */
		projection?: Document;
		/** Determines which document the operation modifies if the query selects multiple documents. */
		sort?: Sort;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		/**
		 * Return the ModifyResult instead of the modified document. Defaults to false
		 */
		includeResultMetadata?: boolean;
	}

	/** @public */
	interface FindOneAndReplaceOptions extends CommandOperationOptions {
		/** Allow driver to bypass schema validation. */
		bypassDocumentValidation?: boolean;
		/** 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.*/
		hint?: Document;
		/** Limits the fields to return for all matching documents. */
		projection?: Document;
		/** When set to 'after', returns the updated document rather than the original. The default is 'before'.  */
		returnDocument?: ReturnDocument;
		/** Determines which document the operation modifies if the query selects multiple documents. */
		sort?: Sort;
		/** Upsert the document if it does not exist. */
		upsert?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		/**
		 * Return the ModifyResult instead of the modified document. Defaults to false
		 */
		includeResultMetadata?: boolean;
	}

	/** @public */
	interface FindOneAndUpdateOptions extends CommandOperationOptions {
		/** Optional list of array filters referenced in filtered positional operators */
		arrayFilters?: Document[];
		/** Allow driver to bypass schema validation. */
		bypassDocumentValidation?: boolean;
		/** 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.*/
		hint?: Document;
		/** Limits the fields to return for all matching documents. */
		projection?: Document;
		/** When set to 'after', returns the updated document rather than the original. The default is 'before'.  */
		returnDocument?: ReturnDocument;
		/** Determines which document the operation modifies if the query selects multiple documents. */
		sort?: Sort;
		/** Upsert the document if it does not exist. */
		upsert?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		/**
		 * Return the ModifyResult instead of the modified document. Defaults to false
		 */
		includeResultMetadata?: boolean;
	}

	/**
	 * A builder object that is returned from {@link BulkOperationBase#find}.
	 * Is used to build a write operation that involves a query filter.
	 *
	 * @public
	 */
	class FindOperators {
		bulkOperation: BulkOperationBase;
		/* Excluded from this release type: __constructor */
		/** Add a multiple update operation to the bulk operation */
		update(updateDocument: Document | Document[]): BulkOperationBase;
		/** Add a single update operation to the bulk operation */
		updateOne(updateDocument: Document | Document[]): BulkOperationBase;
		/** Add a replace one operation to the bulk operation */
		replaceOne(replacement: Document): BulkOperationBase;
		/** Add a delete one operation to the bulk operation */
		deleteOne(): BulkOperationBase;
		/** Add a delete many operation to the bulk operation */
		delete(): BulkOperationBase;
		/** Upsert modifier for update bulk operation, noting that this operation is an upsert. */
		upsert(): this;
		/** Specifies the collation for the query condition. */
		collation(collation: CollationOptions): this;
		/** Specifies arrayFilters for UpdateOne or UpdateMany bulk operations. */
		arrayFilters(arrayFilters: Document[]): this;
		/** Specifies hint for the bulk operation. */
		hint(hint: Hint): this;
	}

	/**
	 * @public
	 * @typeParam TSchema - Unused schema definition, deprecated usage, only specify `FindOptions` with no generic
	 */
	interface FindOptions<TSchema extends Document = Document> extends Omit<CommandOperationOptions, "writeConcern" | "explain">, AbstractCursorOptions {
		/** Sets the limit of documents returned in the query. */
		limit?: number;
		/** Set to sort the documents coming back from the query. Array of indexes, `[['a', 1]]` etc. */
		sort?: Sort;
		/** 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}` */
		projection?: Document;
		/** Set to skip N documents ahead in your query (useful for pagination). */
		skip?: number;
		/** Tell the query to use specific indexes in the query. Object of indexes to use, `{'_id':1}` */
		hint?: Hint;
		/** Specify if the cursor can timeout. */
		timeout?: boolean;
		/** Specify if the cursor is tailable. */
		tailable?: boolean;
		/** Specify if the cursor is a tailable-await cursor. Requires `tailable` to be true */
		awaitData?: boolean;
		/** Set the batchSize for the getMoreCommand when iterating over the query results. */
		batchSize?: number;
		/** If true, returns only the index keys in the resulting documents. */
		returnKey?: boolean;
		/** The inclusive lower bound for a specific index */
		min?: Document;
		/** The exclusive upper bound for a specific index */
		max?: Document;
		/** Number of milliseconds to wait before aborting the query. */
		maxTimeMS?: number;
		/** 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 */
		maxAwaitTimeMS?: number;
		/** The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. */
		noCursorTimeout?: boolean;
		/** Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). */
		collation?: CollationOptions;
		/** Allows disk use for blocking sort operations exceeding 100MB memory. (MongoDB 3.2 or higher) */
		allowDiskUse?: boolean;
		/** Determines whether to close the cursor after the first batch. Defaults to false. */
		singleBatch?: boolean;
		/** 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. */
		allowPartialResults?: boolean;
		/** Determines whether to return the record identifier for each document. If true, adds a field $recordId to the returned documents. */
		showRecordId?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
		/**
		 * 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.
		 * @deprecated Starting from MongoDB 4.4 this flag is not needed and will be ignored.
		 */
		oplogReplay?: boolean;
		/**
		 * Specifies the verbosity mode for the explain output.
		 * @deprecated This API is deprecated in favor of `collection.find().explain()`.
		 */
		explain?: ExplainOptions["explain"];
		/* Excluded from this release type: timeoutMode */
	}

	/** @public */
	type Flatten<Type> = Type extends ReadonlyArray<infer Item> ? Item : Type;

	/**
	 * @public
	 * Configuration options for making an AWS encryption key
	 */
	interface GCPEncryptionKeyOptions {
		/**
		 * GCP project ID
		 */
		projectId: string;
		/**
		 * Location name (e.g. "global")
		 */
		location: string;
		/**
		 * Key ring name
		 */
		keyRing: string;
		/**
		 * Key name
		 */
		keyName: string;
		/**
		 * Key version
		 */
		keyVersion?: string | undefined;
		/**
		 * KMS URL, defaults to `https://www.googleapis.com/auth/cloudkms`
		 */
		endpoint?: string | undefined;
	}

	/** @public */
	type GCPKMSProviderConfiguration =
		| {
				/**
				 * The service account email to authenticate
				 */
				email: string;
				/**
				 * A PKCS#8 encrypted key. This can either be a base64 string or a binary representation
				 */
				privateKey: string | Buffer;
				/**
				 * If present, a host with optional port. E.g. "example.com" or "example.com:443".
				 * Defaults to "oauth2.googleapis.com"
				 */
				endpoint?: string | undefined;
		  }
		| {
				/**
				 * If present, an access token to authenticate with GCP.
				 */
				accessToken: string;
		  };

	/** @public */
	type GenericListener = (...args: any[]) => void;

	/**
	 * Constructor for a streaming GridFS interface
	 * @public
	 */
	class GridFSBucket extends TypedEventEmitter<GridFSBucketEvents> {
		/* Excluded from this release type: s */
		/**
		 * When the first call to openUploadStream is made, the upload stream will
		 * check to see if it needs to create the proper indexes on the chunks and
		 * files collections. This event is fired either when 1) it determines that
		 * no index creation is necessary, 2) when it successfully creates the
		 * necessary indexes.
		 * @event
		 */
		static readonly INDEX: "index";
		constructor(db: Db, options?: GridFSBucketOptions);
		/**
		 * Deletes a file with the given id
		 *
		 * @param id - The id of the file doc
		 */
		delete(
			id: ObjectId,
			options?: {
				timeoutMS: number;
			}
		): Promise<void>;
		/** Convenience wrapper around find on the files collection */
		find(filter?: Filter<GridFSFile>, options?: FindOptions): FindCursor<GridFSFile>;
		/**
		 * Renames the file with the given _id to the given string
		 *
		 * @param id - the id of the file to rename
		 * @param filename - new name for the file
		 */
		rename(
			id: ObjectId,
			filename: string,
			options?: {
				timeoutMS: number;
			}
		): Promise<void>;
		/** Removes this bucket's files collection, followed by its chunks collection. */
		drop(options?: { timeoutMS: number }): Promise<void>;
	}

	/** @public */
	type GridFSBucketEvents = {
		index(): void;
	};

	/** @public */
	interface GridFSBucketOptions extends WriteConcernOptions {
		/** The 'files' and 'chunks' collections will be prefixed with the bucket name followed by a dot. */
		bucketName?: string;
		/** Number of bytes stored in each chunk. Defaults to 255KB */
		chunkSizeBytes?: number;
		/** Read preference to be passed to read operations */
		readPreference?: ReadPreference;
		/**
		 * @experimental
		 * Specifies the lifetime duration of a gridFS stream. If any async operations are in progress
		 * when this timeout expires, the stream will throw a timeout error.
		 */
		timeoutMS?: number;
	}

	/** @public */
	interface GridFSBucketReadStreamOptions {
		sort?: Sort;
		skip?: number;
		/**
		 * 0-indexed non-negative byte offset from the beginning of the file
		 */
		start?: number;
		/**
		 * 0-indexed non-negative byte offset to the end of the file contents
		 * to be returned by the stream. `end` is non-inclusive
		 */
		end?: number;
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
	}

	/** @public */
	interface GridFSBucketReadStreamOptionsWithRevision extends GridFSBucketReadStreamOptions {
		/** The revision number relative to the oldest file with the given filename. 0
		 * gets you the oldest file, 1 gets you the 2nd oldest, -1 gets you the
		 * newest. */
		revision?: number;
	}

	/* Excluded from this release type: GridFSBucketReadStreamPrivate */

	/** @public */
	interface GridFSBucketWriteStreamOptions extends WriteConcernOptions {
		/** Overwrite this bucket's chunkSizeBytes for this file */
		chunkSizeBytes?: number;
		/** Custom file id for the GridFS file. */
		id?: ObjectId;
		/** Object to store in the file document's `metadata` field */
		metadata?: Document;
		/**
		 * String to store in the file document's `contentType` field.
		 * @deprecated Will be removed in the next major version. Add a contentType field to the metadata document instead.
		 */
		contentType?: string;
		/**
		 * Array of strings to store in the file document's `aliases` field.
		 * @deprecated Will be removed in the next major version. Add an aliases field to the metadata document instead.
		 */
		aliases?: string[];
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
	}

	/** @public */
	interface GridFSChunk {
		_id: ObjectId;
		files_id: ObjectId;
		n: number;
		data: Buffer | Uint8Array;
	}

	/** @public */
	interface GridFSFile {
		_id: ObjectId;
		length: number;
		chunkSize: number;
		filename: string;
		metadata?: Document;
		uploadDate: Date;
		/** @deprecated Will be removed in the next major version. */
		contentType?: string;
		/** @deprecated Will be removed in the next major version. */
		aliases?: string[];
	}

	/** @public */
	const GSSAPICanonicalizationValue: Readonly<{
		readonly on: true;
		readonly off: false;
		readonly none: "none";
		readonly forward: "forward";
		readonly forwardAndReverse: "forwardAndReverse";
	}>;

	/** @public */
	type GSSAPICanonicalizationValue = (typeof GSSAPICanonicalizationValue)[keyof typeof GSSAPICanonicalizationValue];

	/* Excluded from this release type: HandshakeDocument */

	/** @public */
	interface HedgeOptions {
		/** Explicitly enable or disable hedged reads. */
		enabled?: boolean;
	}

	/** @public */
	type Hint = string | Document;

	/**
	 * The information returned by the server on the IDP server.
	 * @public
	 */
	interface IdPInfo {
		/**
		 * A URL which describes the Authentication Server. This identifier should
		 * be the iss of provided access tokens, and be viable for RFC8414 metadata
		 * discovery and RFC9207 identification.
		 */
		issuer: string;
		/** A unique client ID for this OIDC client. */
		clientId: string;
		/** A list of additional scopes to request from IdP. */
		requestScopes?: string[];
	}

	/**
	 * The response from the IdP server with the access token and
	 * optional expiration time and refresh token.
	 * @public
	 */
	interface IdPServerResponse {
		/** The OIDC access token. */
		accessToken: string;
		/** The time when the access token expires. For future use. */
		expiresInSeconds?: number;
		/** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
		refreshToken?: string;
	}

	/** @public */
	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"> {
		collation?: CollationOptions;
		name?: string;
		key:
			| {
					[key: string]: IndexDirection;
			  }
			| Map<string, IndexDirection>;
	}

	/** @public */
	type IndexDescriptionCompact = Record<string, [name: string, direction: IndexDirection][]>;

	/**
	 * @public
	 * The index information returned by the listIndexes command. https://www.mongodb.com/docs/manual/reference/command/listIndexes/#mongodb-dbcommand-dbcmd.listIndexes
	 */
	type IndexDescriptionInfo = Omit<IndexDescription, "key" | "version"> & {
		key: {
			[key: string]: IndexDirection;
		};
		v?: IndexDescription["version"];
	} & Document;

	/** @public */
	type IndexDirection = -1 | 1 | "2d" | "2dsphere" | "text" | "geoHaystack" | "hashed" | number;

	/** @public */
	interface IndexInformationOptions extends ListIndexesOptions {
		/**
		 * When `true`, an array of index descriptions is returned.
		 * When `false`, the driver returns an object that with keys corresponding to index names with values
		 * corresponding to the entries of the indexes' key.
		 *
		 * For example, the given the following indexes:
		 * ```
		 * [ { name: 'a_1', key: { a: 1 } }, { name: 'b_1_c_1' , key: { b: 1, c: 1 } }]
		 * ```
		 *
		 * When `full` is `true`, the above array is returned.  When `full` is `false`, the following is returned:
		 * ```
		 * {
		 *   'a_1': [['a', 1]],
		 *   'b_1_c_1': [['b', 1], ['c', 1]],
		 * }
		 * ```
		 */
		full?: boolean;
	}

	/** @public */
	type IndexSpecification = OneOrMore<
		| string
		| [string, IndexDirection]
		| {
				[key: string]: IndexDirection;
		  }
		| Map<string, IndexDirection>
	>;

	/** Given an object shaped type, return the type of the _id field or default to ObjectId @public */
	type InferIdType<TSchema> = TSchema extends {
		_id: infer IdType;
	}
		? Record<any, never> extends IdType
			? never
			: IdType
		: TSchema extends {
				_id?: infer IdType;
		  }
		? unknown extends IdType
			? ObjectId
			: IdType
		: ObjectId;

	/* Excluded from this release type: InitialCursorResponse */

	/** @public */
	interface InsertManyResult<TSchema = Document> {
		/** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
		acknowledged: boolean;
		/** The number of inserted documents for this operations */
		insertedCount: number;
		/** Map of the index of the inserted document to the id of the inserted document */
		insertedIds: {
			[key: number]: InferIdType<TSchema>;
		};
	}

	/** @public */
	interface InsertOneModel<TSchema extends Document = Document> {
		/** The document to insert. */
		document: OptionalId<TSchema>;
	}

	/** @public */
	interface InsertOneOptions extends CommandOperationOptions {
		/** Allow driver to bypass schema validation. */
		bypassDocumentValidation?: boolean;
		/** Force server to assign _id values instead of driver. */
		forceServerObjectId?: boolean;
	}

	/** @public */
	interface InsertOneResult<TSchema = Document> {
		/** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
		acknowledged: boolean;
		/** 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 */
		insertedId: InferIdType<TSchema>;
	}

	/** @public */
	type IntegerType = number | Int32 | Long | bigint;

	/* Excluded from this release type: InternalAbstractCursorOptions */

	/** @public */
	type IsAny<Type, ResultIfAny, ResultIfNotAny> = true extends false & Type ? ResultIfAny : ResultIfNotAny;

	/**
	 * Helper types for dot-notation filter attributes
	 */
	/** @public */
	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;

	/* Excluded from this release type: JSTypeOf */

	/* Excluded from this release type: kBeforeHandshake */

	/* Excluded from this release type: kCancellationToken */

	/* Excluded from this release type: kCancellationToken_2 */

	/* Excluded from this release type: kCancelled */

	/* Excluded from this release type: kCancelled_2 */

	/* Excluded from this release type: kCheckedOut */

	/* Excluded from this release type: kClosed */

	/* Excluded from this release type: kConnectionCounter */

	/* Excluded from this release type: kConnections */

	/* Excluded from this release type: kCursorStream */

	/* Excluded from this release type: kDecorateResult */

	/* Excluded from this release type: kErrorLabels */

	/** @public */
	type KeysOfAType<TSchema, Type> = {
		[key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? key : never;
	}[keyof TSchema];

	/** @public */
	type KeysOfOtherType<TSchema, Type> = {
		[key in keyof TSchema]: NonNullable<TSchema[key]> extends Type ? never : key;
	}[keyof TSchema];

	/* Excluded from this release type: kGeneration */

	/* Excluded from this release type: kInternalClient */

	/* Excluded from this release type: kMetrics */

	/* Excluded from this release type: kMinPoolSizeTimer */

	/**
	 * @public
	 * Configuration options for making a KMIP encryption key
	 */
	interface KMIPEncryptionKeyOptions {
		/**
		 * keyId is the KMIP Unique Identifier to a 96 byte KMIP Secret Data managed object.
		 *
		 * If keyId is omitted, a random 96 byte KMIP Secret Data managed object will be created.
		 */
		keyId?: string;
		/**
		 * Host with optional port.
		 */
		endpoint?: string;
		/**
		 * If true, this key should be decrypted by the KMIP server.
		 *
		 * Requires `mongodb-client-encryption>=6.0.1`.
		 */
		delegated?: boolean;
	}

	/** @public */
	interface KMIPKMSProviderConfiguration {
		/**
		 * The output endpoint string.
		 * The endpoint consists of a hostname and port separated by a colon.
		 * E.g. "example.com:123". A port is always present.
		 */
		endpoint?: string;
	}

	/* Excluded from this release type: kMode */

	/* Excluded from this release type: kMonitorId */

	/**
	 * @public
	 * Configuration options that are used by specific KMS providers during key generation, encryption, and decryption.
	 *
	 * Named KMS providers _are not supported_ for automatic KMS credential fetching.
	 */
	interface KMSProviders {
		/**
		 * Configuration options for using 'aws' as your KMS provider
		 */
		aws?: AWSKMSProviderConfiguration | Record<string, never>;
		[key: `aws:${string}`]: AWSKMSProviderConfiguration;
		/**
		 * Configuration options for using 'local' as your KMS provider
		 */
		local?: LocalKMSProviderConfiguration;
		[key: `local:${string}`]: LocalKMSProviderConfiguration;
		/**
		 * Configuration options for using 'kmip' as your KMS provider
		 */
		kmip?: KMIPKMSProviderConfiguration;
		[key: `kmip:${string}`]: KMIPKMSProviderConfiguration;
		/**
		 * Configuration options for using 'azure' as your KMS provider
		 */
		azure?: AzureKMSProviderConfiguration | Record<string, never>;
		[key: `azure:${string}`]: AzureKMSProviderConfiguration;
		/**
		 * Configuration options for using 'gcp' as your KMS provider
		 */
		gcp?: GCPKMSProviderConfiguration | Record<string, never>;
		[key: `gcp:${string}`]: GCPKMSProviderConfiguration;
	}

	/* Excluded from this release type: kOptions */

	/* Excluded from this release type: kPending */

	/* Excluded from this release type: kPinnedConnection */

	/* Excluded from this release type: kPoolState */

	/* Excluded from this release type: kProcessingWaitQueue */

	/* Excluded from this release type: kServer */

	/* Excluded from this release type: kServer_2 */

	/* Excluded from this release type: kServerError */

	/* Excluded from this release type: kServerSession */

	/* Excluded from this release type: kServiceGenerations */

	/* Excluded from this release type: kSession */

	/* Excluded from this release type: kSnapshotEnabled */

	/* Excluded from this release type: kSnapshotTime */

	/* Excluded from this release type: kTxnNumberIncrement */

	/* Excluded from this release type: kWaitQueue */

	/* Excluded from this release type: kWaitQueue_2 */

	/* Excluded from this release type: LegacyTimeoutContext */

	/* Excluded from this release type: LegacyTimeoutContextOptions */

	/** @public */
	const LEGAL_TCP_SOCKET_OPTIONS: readonly ["autoSelectFamily", "autoSelectFamilyAttemptTimeout", "family", "hints", "localAddress", "localPort", "lookup"];

	/** @public */
	const LEGAL_TLS_SOCKET_OPTIONS: readonly ["allowPartialTrustChain", "ALPNProtocols", "ca", "cert", "checkServerIdentity", "ciphers", "crl", "ecdhCurve", "key", "minDHSize", "passphrase", "pfx", "rejectUnauthorized", "secureContext", "secureProtocol", "servername", "session"];

	/* Excluded from this release type: List */

	/** @public */
	class ListCollectionsCursor<T extends Pick<CollectionInfo, "name" | "type"> | CollectionInfo = Pick<CollectionInfo, "name" | "type"> | CollectionInfo> extends AbstractCursor<T> {
		parent: Db;
		filter: Document;
		options?: ListCollectionsOptions;
		constructor(db: Db, filter: Document, options?: ListCollectionsOptions);
		clone(): ListCollectionsCursor<T>;
		/* Excluded from this release type: _initialize */
	}

	/** @public */
	interface ListCollectionsOptions extends Omit<CommandOperationOptions, "writeConcern"> {
		/** Since 4.0: If true, will only return the collection name in the response, and will omit additional info */
		nameOnly?: boolean;
		/** 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. */
		authorizedCollections?: boolean;
		/** The batchSize for the returned command cursor or if pre 2.8 the systems batch collection */
		batchSize?: number;
		/* Excluded from this release type: timeoutMode */
		/* Excluded from this release type: timeoutContext */
	}

	/** @public */
	interface ListDatabasesOptions extends CommandOperationOptions {
		/** A query predicate that determines which databases are listed */
		filter?: Document;
		/** A flag to indicate whether the command should return just the database names, or return both database names and size information */
		nameOnly?: boolean;
		/** A flag that determines which databases are returned based on the user privileges when access control is enabled */
		authorizedDatabases?: boolean;
	}

	/** @public */
	interface ListDatabasesResult {
		databases: ({
			name: string;
			sizeOnDisk?: number;
			empty?: boolean;
		} & Document)[];
		totalSize?: number;
		totalSizeMb?: number;
		ok: 1 | 0;
	}

	/** @public */
	class ListIndexesCursor extends AbstractCursor {
		parent: Collection;
		options?: ListIndexesOptions;
		constructor(collection: Collection, options?: ListIndexesOptions);
		clone(): ListIndexesCursor;
		/* Excluded from this release type: _initialize */
	}

	/** @public */
	type ListIndexesOptions = AbstractCursorOptions & {
		/* Excluded from this release type: omitMaxTimeMS */
	};

	/** @public */
	class ListSearchIndexesCursor extends AggregationCursor<{
		name: string;
	}> {
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	type ListSearchIndexesOptions = Omit<AggregateOptions, "readConcern" | "writeConcern">;

	/** @public */
	interface LocalKMSProviderConfiguration {
		/**
		 * The master key used to encrypt/decrypt data keys.
		 * A 96-byte long Buffer or base64 encoded string.
		 */
		key: Binary | Uint8Array | string;
	}

	/* Excluded from this release type: Log */

	/* Excluded from this release type: LogComponentSeveritiesClientOptions */

	/* Excluded from this release type: LogConvertible */

	/* Excluded from this release type: Loggable */

	/* Excluded from this release type: LoggableCommandFailedEvent */

	/* Excluded from this release type: LoggableCommandSucceededEvent */

	/* Excluded from this release type: LoggableEvent */

	/* Excluded from this release type: LoggableServerHeartbeatFailedEvent */

	/* Excluded from this release type: LoggableServerHeartbeatStartedEvent */

	/* Excluded from this release type: LoggableServerHeartbeatSucceededEvent */

	/** @public */
	type MatchKeysAndValues<TSchema> = Readonly<Partial<TSchema>> & Record<string, any>;

	/* Excluded from this release type: MessageHeader */

	/** @public */
	interface ModifyResult<TSchema = Document> {
		value: WithId<TSchema> | null;
		lastErrorObject?: Document;
		ok: 0 | 1;
	}

	/** @public */
	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"];

	/**
	 * An error generated when the driver API is used incorrectly
	 *
	 * @privateRemarks
	 * Should **never** be directly instantiated
	 *
	 * @public
	 * @category Error
	 */
	class MongoAPIError extends MongoDriverError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * A error generated when the user attempts to authenticate
	 * via AWS, but fails
	 *
	 * @public
	 * @category Error
	 */
	class MongoAWSError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * A error generated when the user attempts to authenticate
	 * via Azure, but fails.
	 *
	 * @public
	 * @category Error
	 */
	class MongoAzureError extends MongoOIDCError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated when a batch command is re-executed after one of the commands in the batch
	 * has failed
	 *
	 * @public
	 * @category Error
	 */
	class MongoBatchReExecutionError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * An error indicating an unsuccessful Bulk Write
	 * @public
	 * @category Error
	 */
	class MongoBulkWriteError extends MongoServerError {
		result: BulkWriteResult;
		writeErrors: OneOrMore<WriteError>;
		err?: WriteConcernError;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			error:
				| {
						message: string;
						code: number;
						writeErrors?: WriteError[];
				  }
				| WriteConcernError
				| AnyError,
			result: BulkWriteResult
		);
		get name(): string;
		/** Number of documents inserted. */
		get insertedCount(): number;
		/** Number of documents matched for update. */
		get matchedCount(): number;
		/** Number of documents modified. */
		get modifiedCount(): number;
		/** Number of documents deleted. */
		get deletedCount(): number;
		/** Number of documents upserted. */
		get upsertedCount(): number;
		/** Inserted document generated Id's, hash key is the index of the originating operation */
		get insertedIds(): {
			[key: number]: any;
		};
		/** Upserted document generated Id's, hash key is the index of the originating operation */
		get upsertedIds(): {
			[key: number]: any;
		};
	}

	/**
	 * An error generated when a ChangeStream operation fails to execute.
	 *
	 * @public
	 * @category Error
	 */
	class MongoChangeStreamError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * The **MongoClient** class is a class that allows for making Connections to MongoDB.
	 * @public
	 *
	 * @remarks
	 * The programmatically provided options take precedence over the URI options.
	 *
	 * @example
	 * ```ts
	 * import { MongoClient } from 'mongodb';
	 *
	 * // Enable command monitoring for debugging
	 * const client = new MongoClient('mongodb://localhost:27017', { monitorCommands: true });
	 *
	 * client.on('commandStarted', started => console.log(started));
	 * client.db().collection('pets');
	 * await client.insertOne({ name: 'spot', kind: 'dog' });
	 * ```
	 */
	class MongoClient extends TypedEventEmitter<MongoClientEvents> implements AsyncDisposable_2 {
		/* Excluded from this release type: s */
		/* Excluded from this release type: topology */
		/* Excluded from this release type: mongoLogger */
		/* Excluded from this release type: connectionLock */
		/* Excluded from this release type: [kOptions] */
		constructor(url: string, options?: MongoClientOptions);
		/* Excluded from this release type: [Symbol.asyncDispose] */
		/* Excluded from this release type: asyncDispose */
		/* Excluded from this release type: checkForNonGenuineHosts */
		/** @see MongoOptions */
		get options(): Readonly<MongoOptions>;
		get serverApi(): Readonly<ServerApi | undefined>;
		/* Excluded from this release type: monitorCommands */
		/* Excluded from this release type: monitorCommands */
		/* Excluded from this release type: autoEncrypter */
		get readConcern(): ReadConcern | undefined;
		get writeConcern(): WriteConcern | undefined;
		get readPreference(): ReadPreference;
		get bsonOptions(): BSONSerializeOptions;
		get timeoutMS(): number | undefined;
		/**
		 * Executes a client bulk write operation, available on server 8.0+.
		 * @param models - The client bulk write models.
		 * @param options - The client bulk write options.
		 * @returns A ClientBulkWriteResult for acknowledged writes and ok: 1 for unacknowledged writes.
		 */
		bulkWrite<SchemaMap extends Record<string, Document> = Record<string, Document>>(models: ReadonlyArray<ClientBulkWriteModel<SchemaMap>>, options?: ClientBulkWriteOptions): Promise<ClientBulkWriteResult>;
		/**
		 * Connect to MongoDB using a url
		 *
		 * @remarks
		 * Calling `connect` is optional since the first operation you perform will call `connect` if it's needed.
		 * `timeoutMS` will bound the time any operation can take before throwing a timeout error.
		 * However, when the operation being run is automatically connecting your `MongoClient` the `timeoutMS` will not apply to the time taken to connect the MongoClient.
		 * This means the time to setup the `MongoClient` does not count against `timeoutMS`.
		 * If you are using `timeoutMS` we recommend connecting your client explicitly in advance of any operation to avoid this inconsistent execution time.
		 *
		 * @see docs.mongodb.org/manual/reference/connection-string/
		 */
		connect(): Promise<this>;
		/* Excluded from this release type: _connect */
		/**
		 * Cleans up client-side resources used by the MongoCLient and .  This includes:
		 *
		 * - Closes all open, unused connections (see note).
		 * - Ends all in-use sessions with {@link ClientSession#endSession|ClientSession.endSession()}.
		 * - Ends all unused sessions server-side.
		 * - Cleans up any resources being used for auto encryption if auto encryption is enabled.
		 *
		 * @remarks Any in-progress operations are not killed and any connections used by in progress operations
		 * will be cleaned up lazily as operations finish.
		 *
		 * @param force - Force close, emitting no events
		 */
		close(force?: boolean): Promise<void>;
		/**
		 * Create a new Db instance sharing the current socket connections.
		 *
		 * @param dbName - The name of the database we want to use. If not provided, use database name from connection string.
		 * @param options - Optional settings for Db construction
		 */
		db(dbName?: string, options?: DbOptions): Db;
		/**
		 * Connect to MongoDB using a url
		 *
		 * @remarks
		 * Calling `connect` is optional since the first operation you perform will call `connect` if it's needed.
		 * `timeoutMS` will bound the time any operation can take before throwing a timeout error.
		 * However, when the operation being run is automatically connecting your `MongoClient` the `timeoutMS` will not apply to the time taken to connect the MongoClient.
		 * This means the time to setup the `MongoClient` does not count against `timeoutMS`.
		 * If you are using `timeoutMS` we recommend connecting your client explicitly in advance of any operation to avoid this inconsistent execution time.
		 *
		 * @remarks
		 * The programmatically provided options take precedence over the URI options.
		 *
		 * @see https://www.mongodb.com/docs/manual/reference/connection-string/
		 */
		static connect(url: string, options?: MongoClientOptions): Promise<MongoClient>;
		/**
		 * Creates a new ClientSession. When using the returned session in an operation
		 * a corresponding ServerSession will be created.
		 *
		 * @remarks
		 * A ClientSession instance may only be passed to operations being performed on the same
		 * MongoClient it was started from.
		 */
		startSession(options?: ClientSessionOptions): ClientSession;
		/**
		 * A convenience method for creating and handling the clean up of a ClientSession.
		 * The session will always be ended when the executor finishes.
		 *
		 * @param executor - An executor function that all operations using the provided session must be invoked in
		 * @param options - optional settings for the session
		 */
		withSession<T = any>(executor: WithSessionCallback<T>): Promise<T>;
		withSession<T = any>(options: ClientSessionOptions, executor: WithSessionCallback<T>): Promise<T>;
	}

	/* Excluded from this release type: MongoClientAuthProviders */

	/**
	 * An error indicating that an error occurred when processing bulk write results.
	 *
	 * @public
	 * @category Error
	 */
	class MongoClientBulkWriteCursorError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error indicating that an error occurred when executing the bulk write.
	 *
	 * @public
	 * @category Error
	 */
	class MongoClientBulkWriteError extends MongoServerError {
		/**
		 * Write concern errors that occurred while executing the bulk write. This list may have
		 * multiple items if more than one server command was required to execute the bulk write.
		 */
		writeConcernErrors: Document[];
		/**
		 * Errors that occurred during the execution of individual write operations. This map will
		 * contain at most one entry if the bulk write was ordered.
		 */
		writeErrors: Map<number, ClientBulkWriteError>;
		/**
		 * The results of any successful operations that were performed before the error was
		 * encountered.
		 */
		partialResult?: ClientBulkWriteResult;
		/**
		 * Initialize the client bulk write error.
		 * @param message - The error message.
		 */
		constructor(message: ErrorDescription);
		get name(): string;
	}

	/**
	 * An error indicating that an error occurred on the client when executing a client bulk write.
	 *
	 * @public
	 * @category Error
	 */
	class MongoClientBulkWriteExecutionError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/** @public */
	type MongoClientEvents = Pick<TopologyEvents, (typeof MONGO_CLIENT_EVENTS)[number]> & {
		open(mongoClient: MongoClient): void;
	};

	/**
	 * Describes all possible URI query options for the mongo client
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/connection-string
	 */

	/* Excluded from this release type: MongoClientPrivate */

	/**
	 * An error generated when a feature that is not enabled or allowed for the current server
	 * configuration is used
	 *
	 *
	 * @public
	 * @category Error
	 */
	class MongoCompatibilityError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * A representation of the credentials used by MongoDB
	 * @public
	 */
	class MongoCredentials {
		/** The username used for authentication */
		readonly username: string;
		/** The password used for authentication */
		readonly password: string;
		/** The database that the user should authenticate against */
		readonly source: string;
		/** The method used to authenticate */
		readonly mechanism: AuthMechanism;
		/** Special properties used by some types of auth mechanisms */
		readonly mechanismProperties: AuthMechanismProperties;
		constructor(options: MongoCredentialsOptions);
		/** Determines if two MongoCredentials objects are equivalent */
		equals(other: MongoCredentials): boolean;
		/**
		 * If the authentication mechanism is set to "default", resolves the authMechanism
		 * based on the server version and server supported sasl mechanisms.
		 *
		 * @param hello - A hello response from the server
		 */
		resolveAuthMechanism(hello: Document | null): MongoCredentials;
		validate(): void;
		static merge(creds: MongoCredentials | undefined, options: Partial<MongoCredentialsOptions>): MongoCredentials;
	}

	/** @public */
	interface MongoCredentialsOptions {
		username?: string;
		password: string;
		source: string;
		db?: string;
		mechanism?: AuthMechanism;
		mechanismProperties: AuthMechanismProperties;
	}

	/**
	 * @public
	 * An error indicating that mongodb-client-encryption failed to auto-refresh Azure KMS credentials.
	 */
	class MongoCryptAzureKMSRequestError extends MongoCryptError {
		/** The body of the http response that failed, if present. */
		body?: Document;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string, body?: Document);
		get name(): string;
	}

	/**
	 * @public
	 * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create data keys
	 */
	class MongoCryptCreateDataKeyError extends MongoCryptError {
		encryptedFields: Document;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			encryptedFields: Document,
			{
				cause,
			}: {
				cause: Error;
			}
		);
		get name(): string;
	}

	/**
	 * @public
	 * An error indicating that `ClientEncryption.createEncryptedCollection()` failed to create a collection
	 */
	class MongoCryptCreateEncryptedCollectionError extends MongoCryptError {
		encryptedFields: Document;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			encryptedFields: Document,
			{
				cause,
			}: {
				cause: Error;
			}
		);
		get name(): string;
	}

	/* Excluded from this release type: MongocryptdManager */

	/**
	 * @public
	 * An error indicating that something went wrong specifically with MongoDB Client Encryption
	 */
	class MongoCryptError extends MongoError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * @public
	 *
	 * An error indicating an invalid argument was provided to an encryption API.
	 */
	class MongoCryptInvalidArgumentError extends MongoCryptError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/** @public */
	class MongoCryptKMSRequestNetworkTimeoutError extends MongoCryptError {
		get name(): string;
	}

	/**
	 * An error thrown when an attempt is made to read from a cursor that has been exhausted
	 *
	 * @public
	 * @category Error
	 */
	class MongoCursorExhaustedError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * An error thrown when the user attempts to add options to a cursor that has already been
	 * initialized
	 *
	 * @public
	 * @category Error
	 */
	class MongoCursorInUseError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * @public
	 *
	 * A class representing a collection's namespace.  This class enforces (through Typescript) that
	 * the `collection` portion of the namespace is defined and should only be
	 * used in scenarios where this can be guaranteed.
	 */
	class MongoDBCollectionNamespace extends MongoDBNamespace {
		collection: string;
		constructor(db: string, collection: string);
		static fromString(namespace?: string): MongoDBCollectionNamespace;
	}

	/* Excluded from this release type: MongoDBLogWritable */

	/** @public */
	class MongoDBNamespace {
		db: string;
		collection?: string | undefined;
		/**
		 * Create a namespace object
		 *
		 * @param db - database name
		 * @param collection - collection name
		 */
		constructor(db: string, collection?: string | undefined);
		toString(): string;
		withCollection(collection: string): MongoDBCollectionNamespace;
		static fromString(namespace?: string): MongoDBNamespace;
	}

	/* Excluded from this release type: MongoDBResponse */

	/* Excluded from this release type: MongoDBResponseConstructor */

	/**
	 * An error generated when the driver fails to decompress
	 * data received from the server.
	 *
	 * @public
	 * @category Error
	 */
	class MongoDecompressionError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated by the driver
	 *
	 * @public
	 * @category Error
	 */
	class MongoDriverError extends MongoError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * @public
	 * @category Error
	 *
	 * @privateRemarks
	 * mongodb-client-encryption has a dependency on this error, it uses the constructor with a string argument
	 */
	class MongoError extends Error {
		/* Excluded from this release type: [kErrorLabels] */
		/**
		 * This is a number in MongoServerError and a string in MongoDriverError
		 * @privateRemarks
		 * Define the type override on the subclasses when we can use the override keyword
		 */
		code?: number | string;
		topologyVersion?: TopologyVersion;
		connectionGeneration?: number;
		cause?: Error;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		/* Excluded from this release type: buildErrorMessage */
		get name(): string;
		/** Legacy name for server error responses */
		get errmsg(): string;
		/**
		 * Checks the error to see if it has an error label
		 *
		 * @param label - The error label to check for
		 * @returns returns true if the error has the provided error label
		 */
		hasErrorLabel(label: string): boolean;
		addErrorLabel(label: string): void;
		get errorLabels(): string[];
	}

	/** @public */
	const MongoErrorLabel: Readonly<{
		readonly RetryableWriteError: "RetryableWriteError";
		readonly TransientTransactionError: "TransientTransactionError";
		readonly UnknownTransactionCommitResult: "UnknownTransactionCommitResult";
		readonly ResumableChangeStreamError: "ResumableChangeStreamError";
		readonly HandshakeError: "HandshakeError";
		readonly ResetPool: "ResetPool";
		readonly PoolRequstedRetry: "PoolRequstedRetry";
		readonly InterruptInUseConnections: "InterruptInUseConnections";
		readonly NoWritesPerformed: "NoWritesPerformed";
	}>;

	/** @public */
	type MongoErrorLabel = (typeof MongoErrorLabel)[keyof typeof MongoErrorLabel];

	/**
	 * An error generated when the user attempts to operate
	 * on a session that has expired or has been closed.
	 *
	 * @public
	 * @category Error
	 */
	class MongoExpiredSessionError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * A error generated when the user attempts to authenticate
	 * via GCP, but fails.
	 *
	 * @public
	 * @category Error
	 */
	class MongoGCPError extends MongoOIDCError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated when a malformed or invalid chunk is
	 * encountered when reading from a GridFSStream.
	 *
	 * @public
	 * @category Error
	 */
	class MongoGridFSChunkError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/** An error generated when a GridFSStream operation fails to execute.
	 *
	 * @public
	 * @category Error
	 */
	class MongoGridFSStreamError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated when the user supplies malformed or unexpected arguments
	 * or when a required argument or field is not provided.
	 *
	 *
	 * @public
	 * @category Error
	 */
	class MongoInvalidArgumentError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * A error generated when the user attempts to authenticate
	 * via Kerberos, but fails to connect to the Kerberos client.
	 *
	 * @public
	 * @category Error
	 */
	class MongoKerberosError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/* Excluded from this release type: MongoLoggableComponent */

	/* Excluded from this release type: MongoLogger */

	/* Excluded from this release type: MongoLoggerEnvOptions */

	/* Excluded from this release type: MongoLoggerMongoClientOptions */

	/* Excluded from this release type: MongoLoggerOptions */

	/**
	 * An error generated when the user fails to provide authentication credentials before attempting
	 * to connect to a mongo server instance.
	 *
	 *
	 * @public
	 * @category Error
	 */
	class MongoMissingCredentialsError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated when a required module or dependency is not present in the local environment
	 *
	 * @public
	 * @category Error
	 */
	class MongoMissingDependencyError extends MongoAPIError {
		dependencyName: string;
		/** @remarks This property is assigned in the `Error` constructor. */
		cause: Error;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options: {
				cause: Error;
				dependencyName: string;
			}
		);
		get name(): string;
	}

	/**
	 * An error indicating an issue with the network, including TCP errors and timeouts.
	 * @public
	 * @category Error
	 */
	class MongoNetworkError extends MongoError {
		/* Excluded from this release type: [kBeforeHandshake] */
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string, options?: MongoNetworkErrorOptions);
		get name(): string;
	}

	/** @public */
	interface MongoNetworkErrorOptions {
		/** Indicates the timeout happened before a connection handshake completed */
		beforeHandshake?: boolean;
		cause?: Error;
	}

	/**
	 * An error indicating a network timeout occurred
	 * @public
	 * @category Error
	 *
	 * @privateRemarks
	 * mongodb-client-encryption has a dependency on this error with an instanceof check
	 */
	class MongoNetworkTimeoutError extends MongoNetworkError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string, options?: MongoNetworkErrorOptions);
		get name(): string;
	}

	/**
	 * An error thrown when the user attempts to operate on a database or collection through a MongoClient
	 * that has not yet successfully called the "connect" method
	 *
	 * @public
	 * @category Error
	 */
	class MongoNotConnectedError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * A error generated when the user attempts to authenticate
	 * via OIDC callbacks, but fails.
	 *
	 * @public
	 * @category Error
	 */
	class MongoOIDCError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * @public
	 * @category Error
	 *
	 * The `MongoOperationTimeoutError` class represents an error that occurs when an operation could not be completed within the specified `timeoutMS`.
	 * It is generated by the driver in support of the "client side operation timeout" feature so inherits from `MongoDriverError`.
	 * When `timeoutMS` is enabled `MongoServerError`s relating to `MaxTimeExpired` errors will be converted to `MongoOperationTimeoutError`
	 *
	 * @example
	 * ```ts
	 * try {
	 *   await blogs.insertOne(blogPost, { timeoutMS: 60_000 })
	 * } catch (error) {
	 *   if (error instanceof MongoOperationTimeoutError) {
	 *     console.log(`Oh no! writer's block!`, error);
	 *   }
	 * }
	 * ```
	 */
	class MongoOperationTimeoutError extends MongoDriverError {
		get name(): string;
	}

	/**
	 * Parsed Mongo Client Options.
	 *
	 * User supplied options are documented by `MongoClientOptions`.
	 *
	 * **NOTE:** The client's options parsing is subject to change to support new features.
	 * This type is provided to aid with inspection of options after parsing, it should not be relied upon programmatically.
	 *
	 * Options are sourced from:
	 * - connection string
	 * - options object passed to the MongoClient constructor
	 * - file system (ex. tls settings)
	 * - environment variables
	 * - DNS SRV records and TXT records
	 *
	 * Not all options may be present after client construction as some are obtained from asynchronous operations.
	 *
	 * @public
	 */
	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">> {
		appName?: string;
		srvHost?: string;
		credentials?: MongoCredentials;
		readPreference: ReadPreference;
		readConcern: ReadConcern;
		loadBalanced: boolean;
		directConnection: boolean;
		serverApi: ServerApi;
		compressors: CompressorName[];
		writeConcern: WriteConcern;
		dbName: string;
		metadata: ClientMetadata;
		/* Excluded from this release type: extendedMetadata */
		/* Excluded from this release type: autoEncrypter */
		/* Excluded from this release type: tokenCache */
		proxyHost?: string;
		proxyPort?: number;
		proxyUsername?: string;
		proxyPassword?: string;
		serverMonitoringMode: ServerMonitoringMode;
		/* Excluded from this release type: connectionType */
		/* Excluded from this release type: authProviders */
		/* Excluded from this release type: encrypter */
		/* Excluded from this release type: userSpecifiedAuthSource */
		/* Excluded from this release type: userSpecifiedReplicaSet */
		/**
		 * # NOTE ABOUT TLS Options
		 *
		 * If `tls` is provided as an option, it is equivalent to setting the `ssl` option.
		 *
		 * NodeJS native TLS options are passed through to the socket and retain their original types.
		 *
		 * ### Additional options:
		 *
		 * | nodejs native option  | driver spec equivalent option name            | driver option type |
		 * |:----------------------|:----------------------------------------------|:-------------------|
		 * | `ca`                  | `tlsCAFile`                                   | `string`           |
		 * | `crl`                 | `tlsCRLFile`                                  | `string`           |
		 * | `cert`                | `tlsCertificateKeyFile`                       | `string`           |
		 * | `key`                 | `tlsCertificateKeyFile`                       | `string`           |
		 * | `passphrase`          | `tlsCertificateKeyFilePassword`               | `string`           |
		 * | `rejectUnauthorized`  | `tlsAllowInvalidCertificates`                 | `boolean`          |
		 * | `checkServerIdentity` | `tlsAllowInvalidHostnames`                    | `boolean`          |
		 * | see note below        | `tlsInsecure`                                 | `boolean`          |
		 *
		 * If `tlsInsecure` is set to `true`, then it will set the node native options `checkServerIdentity`
		 * to a no-op and `rejectUnauthorized` to `false`.
		 *
		 * If `tlsInsecure` is set to `false`, then it will set the node native options `checkServerIdentity`
		 * to a no-op and `rejectUnauthorized` to the inverse value of `tlsAllowInvalidCertificates`. If
		 * `tlsAllowInvalidCertificates` is not set, then `rejectUnauthorized` will be set to `true`.
		 *
		 * ### Note on `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile`
		 *
		 * The files specified by the paths passed in to the `tlsCAFile`, `tlsCertificateKeyFile` and `tlsCRLFile`
		 * fields are read lazily on the first call to `MongoClient.connect`. Once these files have been read and
		 * the `ca`, `cert`, `crl` and `key` fields are populated, they will not be read again on subsequent calls to
		 * `MongoClient.connect`. As a result, until the first call to `MongoClient.connect`, the `ca`,
		 * `cert`, `crl` and `key` fields will be undefined.
		 */
		tls: boolean;
		tlsCAFile?: string;
		tlsCRLFile?: string;
		tlsCertificateKeyFile?: string;
		/* Excluded from this release type: __index */
		/* Excluded from this release type: mongoLoggerOptions */
		/* Excluded from this release type: mongodbLogPath */
		timeoutMS?: number;
	}

	/**
	 * An error used when attempting to parse a value (like a connection string)
	 * @public
	 * @category Error
	 */
	class MongoParseError extends MongoDriverError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated when the driver encounters unexpected input
	 * or reaches an unexpected/invalid internal state.
	 *
	 * @privateRemarks
	 * Should **never** be directly instantiated.
	 *
	 * @public
	 * @category Error
	 */
	class MongoRuntimeError extends MongoDriverError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * An error generated when an attempt is made to operate
	 * on a closed/closing server.
	 *
	 * @public
	 * @category Error
	 */
	class MongoServerClosedError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * An error coming from the mongo server
	 *
	 * @public
	 * @category Error
	 */
	class MongoServerError extends MongoError {
		/** Raw error result document returned by server. */
		errorResponse: ErrorDescription;
		codeName?: string;
		writeConcernError?: Document;
		errInfo?: Document;
		ok?: number;
		[key: string]: any;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: ErrorDescription);
		get name(): string;
	}

	/**
	 * An error signifying a client-side server selection error
	 * @public
	 * @category Error
	 */
	class MongoServerSelectionError extends MongoSystemError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string, reason: TopologyDescription);
		get name(): string;
	}

	/**
	 * An error generated when a primary server is marked stale, never directly thrown
	 *
	 * @public
	 * @category Error
	 */
	class MongoStalePrimaryError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			serverDescription: ServerDescription,
			maxSetVersion: number | null,
			maxElectionId: ObjectId | null,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * An error signifying a general system issue
	 * @public
	 * @category Error
	 */
	class MongoSystemError extends MongoError {
		/** An optional reason context, such as an error saved during flow of monitoring and selecting servers */
		reason?: TopologyDescription;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string, reason: TopologyDescription);
		get name(): string;
	}

	/**
	 * An error thrown when the user calls a function or method not supported on a tailable cursor
	 *
	 * @public
	 * @category Error
	 */
	class MongoTailableCursorError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * An error generated when an attempt is made to operate on a
	 * dropped, or otherwise unavailable, database.
	 *
	 * @public
	 * @category Error
	 */
	class MongoTopologyClosedError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message?: string);
		get name(): string;
	}

	/**
	 * An error generated when the user makes a mistake in the usage of transactions.
	 * (e.g. attempting to commit a transaction with a readPreference other than primary)
	 *
	 * @public
	 * @category Error
	 */
	class MongoTransactionError extends MongoAPIError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(message: string);
		get name(): string;
	}

	/**
	 * An error generated when a **parsable** unexpected response comes from the server.
	 * This is generally an error where the driver in a state expecting a certain behavior to occur in
	 * the next message from MongoDB but it receives something else.
	 * This error **does not** represent an issue with wire message formatting.
	 *
	 * #### Example
	 * When an operation fails, it is the driver's job to retry it. It must perform serverSelection
	 * again to make sure that it attempts the operation against a server in a good state. If server
	 * selection returns a server that does not support retryable operations, this error is used.
	 * This scenario is unlikely as retryable support would also have been determined on the first attempt
	 * but it is possible the state change could report a selectable server that does not support retries.
	 *
	 * @public
	 * @category Error
	 */
	class MongoUnexpectedServerResponseError extends MongoRuntimeError {
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(
			message: string,
			options?: {
				cause?: Error;
			}
		);
		get name(): string;
	}

	/**
	 * An error thrown when the server reports a writeConcernError
	 * @public
	 * @category Error
	 */
	class MongoWriteConcernError extends MongoServerError {
		/** The result document */
		result: Document;
		/**
		 * **Do not use this constructor!**
		 *
		 * Meant for internal use only.
		 *
		 * @remarks
		 * This class is only meant to be constructed within the driver. This constructor is
		 * not subject to semantic versioning compatibility guarantees and may change at any time.
		 *
		 * @public
		 **/
		constructor(result: WriteConcernErrorResult);
		get name(): string;
	}

	/* Excluded from this release type: Monitor */

	/** @public */
	type MonitorEvents = {
		serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
		serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
		serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
		resetServer(error?: MongoError): void;
		resetConnectionPool(): void;
		close(): void;
	} & EventEmitterWithState;

	/* Excluded from this release type: MonitorInterval */

	/* Excluded from this release type: MonitorIntervalOptions */

	/** @public */
	interface MonitorOptions extends Omit<ConnectionOptions, "id" | "generation" | "hostAddress"> {
		connectTimeoutMS: number;
		heartbeatFrequencyMS: number;
		minHeartbeatFrequencyMS: number;
		serverMonitoringMode: ServerMonitoringMode;
	}

	/* Excluded from this release type: MonitorPrivate */

	/**
	 * @public
	 * returns tuple of strings (keys to be joined on '.') that represent every path into a schema
	 * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
	 *
	 * @remarks
	 * Through testing we determined that a depth of 8 is safe for the typescript compiler
	 * and provides reasonable compilation times. This number is otherwise not special and
	 * should be changed if issues are found with this level of checking. Beyond this
	 * depth any helpers that make use of NestedPaths should devolve to not asserting any
	 * type safety on the input.
	 */
	type NestedPaths<Type, Depth extends number[]> = Depth["length"] extends 8
		? []
		: Type extends
				| string
				| number
				| bigint
				| boolean
				| Date
				| RegExp
				| Buffer
				| Uint8Array
				| ((...args: any[]) => any)
				| {
						_bsontype: string;
				  }
		? []
		: Type extends ReadonlyArray<infer ArrayType>
		? [] | [number, ...NestedPaths<ArrayType, [...Depth, 1]>]
		: Type extends Map<string, any>
		? [string]
		: Type extends object
		? {
				[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]
						: [Key, ...NestedPaths<Type[Key], [...Depth, 1]>] // child is not structured the same as the parent
					: [Key, ...NestedPaths<Type[Key], [...Depth, 1]>] | [Key];
		  }[Extract<keyof Type, string>]
		: [];

	/**
	 * @public
	 * returns keys (strings) for every path into a schema with a value of type
	 * https://www.mongodb.com/docs/manual/tutorial/query-embedded-documents/
	 */
	type NestedPathsOfType<TSchema, Type> = KeysOfAType<
		{
			[Property in Join<NestedPaths<TSchema, []>, ".">]: PropertyType<TSchema, Property>;
		},
		Type
	>;

	/**
	 * @public
	 * A type that extends Document but forbids anything that "looks like" an object id.
	 */
	type NonObjectIdLikeDocument = {
		[key in keyof ObjectIdLike]?: never;
	} & Document;

	/** It avoids using fields with not acceptable types @public */
	type NotAcceptedFields<TSchema, FieldType> = {
		readonly [key in KeysOfOtherType<TSchema, FieldType>]?: never;
	};

	/** @public */
	type NumericType = IntegerType | Decimal128 | Double;

	/**
	 * The signature of the human or machine callback functions.
	 * @public
	 */
	type OIDCCallbackFunction = (params: OIDCCallbackParams) => Promise<OIDCResponse>;

	/**
	 * The parameters that the driver provides to the user supplied
	 * human or machine callback.
	 *
	 * The version number is used to communicate callback API changes that are not breaking but that
	 * users may want to know about and review their implementation. Users may wish to check the version
	 * number and throw an error if their expected version number and the one provided do not match.
	 * @public
	 */
	interface OIDCCallbackParams {
		/** Optional username. */
		username?: string;
		/** The context in which to timeout the OIDC callback. */
		timeoutContext: AbortSignal;
		/** The current OIDC API version. */
		version: 1;
		/** The IdP information returned from the server. */
		idpInfo?: IdPInfo;
		/** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
		refreshToken?: string;
	}

	/**
	 * The response required to be returned from the machine or
	 * human callback workflows' callback.
	 * @public
	 */
	interface OIDCResponse {
		/** The OIDC access token. */
		accessToken: string;
		/** The time when the access token expires. For future use. */
		expiresInSeconds?: number;
		/** The refresh token, if applicable, to be used by the callback to request a new token from the issuer. */
		refreshToken?: string;
	}

	/* Excluded from this release type: OnDemandDocument */

	/* Excluded from this release type: OnDemandDocumentDeserializeOptions */

	/** @public */
	type OneOrMore<T> = T | ReadonlyArray<T>;

	/** @public */
	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>>;

	/* Excluded from this release type: OpCompressedRequest */

	/** @public */
	interface OperationOptions extends BSONSerializeOptions {
		/** Specify ClientSession for this command */
		session?: ClientSession;
		willRetryWrite?: boolean;
		/** The preferred read preference (ReadPreference.primary, ReadPreference.primary_preferred, ReadPreference.secondary, ReadPreference.secondary_preferred, ReadPreference.nearest). */
		readPreference?: ReadPreferenceLike;
		/* Excluded from this release type: bypassPinningCheck */
		omitReadPreference?: boolean;
		/* Excluded from this release type: omitMaxTimeMS */
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
	}

	/* Excluded from this release type: OperationParent */

	/**
	 * Represents a specific point in time on a server. Can be retrieved by using `db.command()`
	 * @public
	 * @see https://www.mongodb.com/docs/manual/reference/method/db.runCommand/#response
	 */
	type OperationTime = Timestamp;

	/* Excluded from this release type: OpMsgOptions */

	/* Excluded from this release type: OpMsgRequest */

	/* Excluded from this release type: OpMsgResponse */

	/* Excluded from this release type: OpQueryOptions */

	/* Excluded from this release type: OpQueryRequest */

	/* Excluded from this release type: OpReply */

	/**
	 * Add an optional _id field to an object shaped type
	 * @public
	 */
	type OptionalId<TSchema> = EnhancedOmit<TSchema, "_id"> & {
		_id?: InferIdType<TSchema>;
	};

	/**
	 * Adds an optional _id field to an object shaped type, unless the _id field is required on that type.
	 * In the case _id is required, this method continues to require_id.
	 *
	 * @public
	 *
	 * @privateRemarks
	 * `ObjectId extends TSchema['_id']` is a confusing ordering at first glance. Rather than ask
	 * `TSchema['_id'] extends ObjectId` which translated to "Is the _id property ObjectId?"
	 * we instead ask "Does ObjectId look like (have the same shape) as the _id?"
	 */
	type OptionalUnlessRequiredId<TSchema> = TSchema extends {
		_id: any;
	}
		? TSchema
		: OptionalId<TSchema>;

	/** @public */
	class OrderedBulkOperation extends BulkOperationBase {
		/* Excluded from this release type: __constructor */
		addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
	}

	/** @public */
	interface PkFactory {
		createPk(): any;
	}

	/* Excluded from this release type: PoolState */

	/** @public */
	const ProfilingLevel: Readonly<{
		readonly off: "off";
		readonly slowOnly: "slow_only";
		readonly all: "all";
	}>;

	/** @public */
	type ProfilingLevel = (typeof ProfilingLevel)[keyof typeof ProfilingLevel];

	/** @public */
	type ProfilingLevelOptions = CommandOperationOptions;

	/** @public */
	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;

	/** @public */
	interface ProxyOptions {
		proxyHost?: string;
		proxyPort?: number;
		proxyUsername?: string;
		proxyPassword?: string;
	}

	/** @public */
	type PullAllOperator<TSchema> = ({
		readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: TSchema[key];
	} & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
		readonly [key: string]: ReadonlyArray<any>;
	};

	/** @public */
	type PullOperator<TSchema> = ({
		readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: Partial<Flatten<TSchema[key]>> | FilterOperations<Flatten<TSchema[key]>>;
	} & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
		readonly [key: string]: FilterOperators<any> | any;
	};

	/** @public */
	type PushOperator<TSchema> = ({
		readonly [key in KeysOfAType<TSchema, ReadonlyArray<any>>]?: Flatten<TSchema[key]> | ArrayOperator<Array<Flatten<TSchema[key]>>>;
	} & NotAcceptedFields<TSchema, ReadonlyArray<any>>) & {
		readonly [key: string]: ArrayOperator<any> | any;
	};

	/**
	 * @public
	 * RangeOptions specifies index options for a Queryable Encryption field supporting "range" queries.
	 * min, max, sparsity, trimFactor and range must match the values set in the encryptedFields of the destination collection.
	 * For double and decimal128, min/max/precision must all be set, or all be unset.
	 */
	interface RangeOptions {
		/** min is the minimum value for the encrypted index. Required if precision is set. */
		min?: any;
		/** max is the minimum value for the encrypted index. Required if precision is set. */
		max?: any;
		/** sparsity may be used to tune performance. must be non-negative. When omitted, a default value is used. */
		sparsity?: Long | bigint;
		/** trimFactor may be used to tune performance. must be non-negative. When omitted, a default value is used. */
		trimFactor?: Int32 | number;
		precision?: number;
	}

	/**
	 * The MongoDB ReadConcern, which allows for control of the consistency and isolation properties
	 * of the data read from replica sets and replica set shards.
	 * @public
	 *
	 * @see https://www.mongodb.com/docs/manual/reference/read-concern/index.html
	 */
	class ReadConcern {
		level: ReadConcernLevel | string;
		/** Constructs a ReadConcern from the read concern level.*/
		constructor(level: ReadConcernLevel);
		/**
		 * Construct a ReadConcern given an options object.
		 *
		 * @param options - The options object from which to extract the write concern.
		 */
		static fromOptions(options?: { readConcern?: ReadConcernLike; level?: ReadConcernLevel }): ReadConcern | undefined;
		static get MAJORITY(): "majority";
		static get AVAILABLE(): "available";
		static get LINEARIZABLE(): "linearizable";
		static get SNAPSHOT(): "snapshot";
		toJSON(): Document;
	}

	/** @public */
	const ReadConcernLevel: Readonly<{
		readonly local: "local";
		readonly majority: "majority";
		readonly linearizable: "linearizable";
		readonly available: "available";
		readonly snapshot: "snapshot";
	}>;

	/** @public */
	type ReadConcernLevel = (typeof ReadConcernLevel)[keyof typeof ReadConcernLevel];

	/** @public */
	type ReadConcernLike =
		| ReadConcern
		| {
				level: ReadConcernLevel;
		  }
		| ReadConcernLevel;

	/**
	 * The **ReadPreference** class is a class that represents a MongoDB ReadPreference and is
	 * used to construct connections.
	 * @public
	 *
	 * @see https://www.mongodb.com/docs/manual/core/read-preference/
	 */
	class ReadPreference {
		mode: ReadPreferenceMode;
		tags?: TagSet[];
		hedge?: HedgeOptions;
		maxStalenessSeconds?: number;
		minWireVersion?: number;
		static PRIMARY: "primary";
		static PRIMARY_PREFERRED: "primaryPreferred";
		static SECONDARY: "secondary";
		static SECONDARY_PREFERRED: "secondaryPreferred";
		static NEAREST: "nearest";
		static primary: ReadPreference;
		static primaryPreferred: ReadPreference;
		static secondary: ReadPreference;
		static secondaryPreferred: ReadPreference;
		static nearest: ReadPreference;
		/**
		 * @param mode - A string describing the read preference mode (primary|primaryPreferred|secondary|secondaryPreferred|nearest)
		 * @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.
		 * @param options - Additional read preference options
		 */
		constructor(mode: ReadPreferenceMode, tags?: TagSet[], options?: ReadPreferenceOptions);
		get preference(): ReadPreferenceMode;
		static fromString(mode: string): ReadPreference;
		/**
		 * Construct a ReadPreference given an options object.
		 *
		 * @param options - The options object from which to extract the read preference.
		 */
		static fromOptions(options?: ReadPreferenceFromOptions): ReadPreference | undefined;
		/**
		 * Replaces options.readPreference with a ReadPreference instance
		 */
		static translate(options: ReadPreferenceLikeOptions): ReadPreferenceLikeOptions;
		/**
		 * Validate if a mode is legal
		 *
		 * @param mode - The string representing the read preference mode.
		 */
		static isValid(mode: string): boolean;
		/**
		 * Validate if a mode is legal
		 *
		 * @param mode - The string representing the read preference mode.
		 */
		isValid(mode?: string): boolean;
		/**
		 * Indicates that this readPreference needs the "SecondaryOk" bit when sent over the wire
		 * @see https://www.mongodb.com/docs/manual/reference/mongodb-wire-protocol/#op-query
		 */
		secondaryOk(): boolean;
		/**
		 * Check if the two ReadPreferences are equivalent
		 *
		 * @param readPreference - The read preference with which to check equality
		 */
		equals(readPreference: ReadPreference): boolean;
		/** Return JSON representation */
		toJSON(): Document;
	}

	/** @public */
	interface ReadPreferenceFromOptions extends ReadPreferenceLikeOptions {
		session?: ClientSession;
		readPreferenceTags?: TagSet[];
		hedge?: HedgeOptions;
	}

	/** @public */
	type ReadPreferenceLike = ReadPreference | ReadPreferenceMode;

	/** @public */
	interface ReadPreferenceLikeOptions extends ReadPreferenceOptions {
		readPreference?:
			| ReadPreferenceLike
			| {
					mode?: ReadPreferenceMode;
					preference?: ReadPreferenceMode;
					tags?: TagSet[];
					maxStalenessSeconds?: number;
			  };
	}

	/** @public */
	const ReadPreferenceMode: Readonly<{
		readonly primary: "primary";
		readonly primaryPreferred: "primaryPreferred";
		readonly secondary: "secondary";
		readonly secondaryPreferred: "secondaryPreferred";
		readonly nearest: "nearest";
	}>;

	/** @public */
	type ReadPreferenceMode = (typeof ReadPreferenceMode)[keyof typeof ReadPreferenceMode];

	/** @public */
	interface ReadPreferenceOptions {
		/** Max secondary read staleness in seconds, Minimum value is 90 seconds.*/
		maxStalenessSeconds?: number;
		/** Server mode in which the same query is dispatched in parallel to multiple replica set members. */
		hedge?: HedgeOptions;
	}

	/** @public */
	type RegExpOrString<T> = T extends string ? BSONRegExp | RegExp | T : T;

	/** @public */
	type RemoveUserOptions = CommandOperationOptions;

	/** @public */
	interface RenameOptions extends CommandOperationOptions {
		/** Drop the target name collection if it previously exists. */
		dropTarget?: boolean;
		/** Unclear */
		new_collection?: boolean;
	}

	/** @public */
	interface ReplaceOneModel<TSchema extends Document = Document> {
		/** The filter to limit the replaced document. */
		filter: Filter<TSchema>;
		/** The document with which to replace the matched document. */
		replacement: WithoutId<TSchema>;
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query. */
		upsert?: boolean;
	}

	/** @public */
	interface ReplaceOptions extends CommandOperationOptions {
		/** If true, allows the write to opt-out of document level validation */
		bypassDocumentValidation?: boolean;
		/** Specifies a collation */
		collation?: CollationOptions;
		/** Specify that the update query should only consider plans using the hinted index */
		hint?: string | Document;
		/** When true, creates a new document if no document matches the query */
		upsert?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
	}

	/**
	 * @public
	 * @deprecated Please use the ChangeStreamCursorOptions type instead.
	 */
	interface ResumeOptions {
		startAtOperationTime?: Timestamp;
		batchSize?: number;
		maxAwaitTimeMS?: number;
		collation?: CollationOptions;
		readPreference?: ReadPreference;
		resumeAfter?: ResumeToken;
		startAfter?: ResumeToken;
		fullDocument?: string;
	}

	/**
	 * Represents the logical starting point for a new ChangeStream or resuming a ChangeStream on the server.
	 * @see https://www.mongodb.com/docs/manual/changeStreams/#std-label-change-stream-resume
	 * @public
	 */
	type ResumeToken = unknown;

	/** @public */
	const ReturnDocument: Readonly<{
		readonly BEFORE: "before";
		readonly AFTER: "after";
	}>;

	/** @public */
	type ReturnDocument = (typeof ReturnDocument)[keyof typeof ReturnDocument];

	/** @public */
	interface RootFilterOperators<TSchema> extends Document {
		$and?: Filter<TSchema>[];
		$nor?: Filter<TSchema>[];
		$or?: Filter<TSchema>[];
		$text?: {
			$search: string;
			$language?: string;
			$caseSensitive?: boolean;
			$diacriticSensitive?: boolean;
		};
		$where?: string | ((this: TSchema) => boolean);
		$comment?: string | Document;
	}

	/* Excluded from this release type: RTTPinger */

	/* Excluded from this release type: RTTPingerOptions */

	/* Excluded from this release type: RTTSampler */

	/** @public */
	class RunCommandCursor extends AbstractCursor {
		readonly command: Readonly<Record<string, any>>;
		readonly getMoreOptions: {
			comment?: any;
			maxAwaitTimeMS?: number;
			batchSize?: number;
		};
		/**
		 * Controls the `getMore.comment` field
		 * @param comment - any BSON value
		 */
		setComment(comment: any): this;
		/**
		 * Controls the `getMore.maxTimeMS` field. Only valid when cursor is tailable await
		 * @param maxTimeMS - the number of milliseconds to wait for new data
		 */
		setMaxTimeMS(maxTimeMS: number): this;
		/**
		 * Controls the `getMore.batchSize` field
		 * @param batchSize - the number documents to return in the `nextBatch`
		 */
		setBatchSize(batchSize: number): this;
		/** Unsupported for RunCommandCursor */
		clone(): never;
		/** Unsupported for RunCommandCursor: readConcern must be configured directly on command document */
		withReadConcern(_: ReadConcernLike): never;
		/** Unsupported for RunCommandCursor: various cursor flags must be configured directly on command document */
		addCursorFlag(_: string, __: boolean): never;
		/**
		 * Unsupported for RunCommandCursor: maxTimeMS must be configured directly on command document
		 */
		maxTimeMS(_: number): never;
		/** Unsupported for RunCommandCursor: batchSize must be configured directly on command document */
		batchSize(_: number): never;
		/* Excluded from this release type: db */
		/* Excluded from this release type: __constructor */
		/* Excluded from this release type: _initialize */
		/* Excluded from this release type: getMore */
	}

	/** @public */
	type RunCommandOptions = {
		/** Specify ClientSession for this command */
		session?: ClientSession;
		/** The read preference */
		readPreference?: ReadPreferenceLike;
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
		/* Excluded from this release type: omitMaxTimeMS */
	} & BSONSerializeOptions;

	/** @public */
	type RunCursorCommandOptions = {
		readPreference?: ReadPreferenceLike;
		session?: ClientSession;
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error. Note that if
		 * `maxTimeMS` is provided in the command in addition to setting `timeoutMS` in the options, then
		 * the original value of `maxTimeMS` will be overwritten.
		 */
		timeoutMS?: number;
		/**
		 * @public
		 * @experimental
		 * Specifies how `timeoutMS` is applied to the cursor. Can be either `'cursorLifeTime'` or `'iteration'`
		 * When set to `'iteration'`, the deadline specified by `timeoutMS` applies to each call of
		 * `cursor.next()`.
		 * When set to `'cursorLifetime'`, the deadline applies to the life of the entire cursor.
		 *
		 * Depending on the type of cursor being used, this option has different default values.
		 * For non-tailable cursors, this value defaults to `'cursorLifetime'`
		 * For tailable cursors, this value defaults to `'iteration'` since tailable cursors, by
		 * definition can have an arbitrarily long lifetime.
		 *
		 * @example
		 * ```ts
		 * const cursor = collection.find({}, {timeoutMS: 100, timeoutMode: 'iteration'});
		 * for await (const doc of cursor) {
		 *  // process doc
		 *  // This will throw a timeout error if any of the iterator's `next()` calls takes more than 100ms, but
		 *  // will continue to iterate successfully otherwise, regardless of the number of batches.
		 * }
		 * ```
		 *
		 * @example
		 * ```ts
		 * const cursor = collection.find({}, { timeoutMS: 1000, timeoutMode: 'cursorLifetime' });
		 * const docs = await cursor.toArray(); // This entire line will throw a timeout error if all batches are not fetched and returned within 1000ms.
		 * ```
		 */
		timeoutMode?: CursorTimeoutMode;
		tailable?: boolean;
		awaitData?: boolean;
	} & BSONSerializeOptions;

	/** @public */
	type SchemaMember<T, V> =
		| {
				[P in keyof T]?: V;
		  }
		| {
				[key: string]: V;
		  };

	/**
	 * @public
	 */
	interface SearchIndexDescription extends Document {
		/** The name of the index. */
		name?: string;
		/** The index definition. */
		definition: Document;
		/** The type of the index.  Currently `search` or `vectorSearch` are supported. */
		type?: string;
	}

	/** @public */
	interface SelectServerOptions {
		readPreference?: ReadPreferenceLike;
		/** How long to block for server selection before throwing an error */
		serverSelectionTimeoutMS?: number;
		session?: ClientSession;
		operationName: string;
		previousServer?: ServerDescription;
		/* Excluded from this release type: timeoutContext */
	}

	/* Excluded from this release type: Server */

	/* Excluded from this release type: SERVER_CLOSED */

	/* Excluded from this release type: SERVER_DESCRIPTION_CHANGED */

	/* Excluded from this release type: SERVER_HEARTBEAT_FAILED */

	/* Excluded from this release type: SERVER_HEARTBEAT_STARTED */

	/* Excluded from this release type: SERVER_HEARTBEAT_SUCCEEDED */

	/* Excluded from this release type: SERVER_OPENING */

	/* Excluded from this release type: SERVER_SELECTION_FAILED */

	/* Excluded from this release type: SERVER_SELECTION_STARTED */

	/* Excluded from this release type: SERVER_SELECTION_SUCCEEDED */

	/** @public */
	interface ServerApi {
		version: ServerApiVersion;
		strict?: boolean;
		deprecationErrors?: boolean;
	}

	/** @public */
	const ServerApiVersion: Readonly<{
		readonly v1: "1";
	}>;

	/** @public */
	type ServerApiVersion = (typeof ServerApiVersion)[keyof typeof ServerApiVersion];

	/** @public */
	class ServerCapabilities {
		maxWireVersion: number;
		minWireVersion: number;
		constructor(hello: Document);
		get hasAggregationCursor(): boolean;
		get hasWriteCommands(): boolean;
		get hasTextSearch(): boolean;
		get hasAuthCommands(): boolean;
		get hasListCollectionsCommand(): boolean;
		get hasListIndexesCommand(): boolean;
		get supportsSnapshotReads(): boolean;
		get commandsTakeWriteConcern(): boolean;
		get commandsTakeCollation(): boolean;
	}

	/**
	 * Emitted when server is closed.
	 * @public
	 * @category Event
	 */
	class ServerClosedEvent {
		/** A unique identifier for the topology */
		topologyId: number;
		/** The address (host/port pair) of the server */
		address: string;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/* Excluded from this release type: ServerCommandOptions */

	/**
	 * The client's view of a single server, based on the most recent hello outcome.
	 *
	 * Internal type, not meant to be directly instantiated
	 * @public
	 */
	class ServerDescription {
		address: string;
		type: ServerType;
		hosts: string[];
		passives: string[];
		arbiters: string[];
		tags: TagSet;
		error: MongoError | null;
		topologyVersion: TopologyVersion | null;
		minWireVersion: number;
		maxWireVersion: number;
		roundTripTime: number;
		/** The minimum measurement of the last 10 measurements of roundTripTime that have been collected */
		minRoundTripTime: number;
		lastUpdateTime: number;
		lastWriteDate: number;
		me: string | null;
		primary: string | null;
		setName: string | null;
		setVersion: number | null;
		electionId: ObjectId | null;
		logicalSessionTimeoutMinutes: number | null;
		/** The max message size in bytes for the server. */
		maxMessageSizeBytes: number | null;
		/** The max number of writes in a bulk write command. */
		maxWriteBatchSize: number | null;
		/** The max bson object size. */
		maxBsonObjectSize: number | null;
		/** Indicates server is a mongocryptd instance. */
		iscryptd: boolean;
		$clusterTime?: ClusterTime;
		/* Excluded from this release type: __constructor */
		get allHosts(): string[];
		/** Is this server available for reads*/
		get isReadable(): boolean;
		/** Is this server data bearing */
		get isDataBearing(): boolean;
		/** Is this server available for writes */
		get isWritable(): boolean;
		get host(): string;
		get port(): number;
		/**
		 * Determines if another `ServerDescription` is equal to this one per the rules defined in the SDAM specification.
		 * @see https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.md
		 */
		equals(other?: ServerDescription | null): boolean;
	}

	/**
	 * Emitted when server description changes, but does NOT include changes to the RTT.
	 * @public
	 * @category Event
	 */
	class ServerDescriptionChangedEvent {
		/** A unique identifier for the topology */
		topologyId: number;
		/** The address (host/port pair) of the server */
		address: string;
		/** The previous server description */
		previousDescription: ServerDescription;
		/** The new server description */
		newDescription: ServerDescription;
		name: "serverDescriptionChanged";
		/* Excluded from this release type: __constructor */
	}

	/* Excluded from this release type: ServerDescriptionOptions */

	/** @public */
	type ServerEvents = {
		serverHeartbeatStarted(event: ServerHeartbeatStartedEvent): void;
		serverHeartbeatSucceeded(event: ServerHeartbeatSucceededEvent): void;
		serverHeartbeatFailed(event: ServerHeartbeatFailedEvent): void;
		/* Excluded from this release type: connect */
		descriptionReceived(description: ServerDescription): void;
		closed(): void;
		ended(): void;
	} & ConnectionPoolEvents &
		EventEmitterWithState;

	/**
	 * Emitted when the server monitor’s hello fails, either with an “ok: 0” or a socket exception.
	 * @public
	 * @category Event
	 */
	class ServerHeartbeatFailedEvent {
		/** The connection id for the command */
		connectionId: string;
		/** The execution time of the event in ms */
		duration: number;
		/** The command failure */
		failure: Error;
		/** Is true when using the streaming protocol */
		awaited: boolean;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * Emitted when the server monitor’s hello command is started - immediately before
	 * the hello command is serialized into raw BSON and written to the socket.
	 *
	 * @public
	 * @category Event
	 */
	class ServerHeartbeatStartedEvent {
		/** The connection id for the command */
		connectionId: string;
		/** Is true when using the streaming protocol */
		awaited: boolean;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * Emitted when the server monitor’s hello succeeds.
	 * @public
	 * @category Event
	 */
	class ServerHeartbeatSucceededEvent {
		/** The connection id for the command */
		connectionId: string;
		/** The execution time of the event in ms */
		duration: number;
		/** The command reply */
		reply: Document;
		/** Is true when using the streaming protocol */
		awaited: boolean;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	const ServerMonitoringMode: Readonly<{
		readonly auto: "auto";
		readonly poll: "poll";
		readonly stream: "stream";
	}>;

	/** @public */
	type ServerMonitoringMode = (typeof ServerMonitoringMode)[keyof typeof ServerMonitoringMode];

	/**
	 * Emitted when server is initialized.
	 * @public
	 * @category Event
	 */
	class ServerOpeningEvent {
		/** A unique identifier for the topology */
		topologyId: number;
		/** The address (host/port pair) of the server */
		address: string;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/* Excluded from this release type: ServerOptions */

	/* Excluded from this release type: ServerPrivate */

	/* Excluded from this release type: ServerSelectionCallback */

	/* Excluded from this release type: ServerSelectionEvent */

	/* Excluded from this release type: ServerSelectionFailedEvent */

	/* Excluded from this release type: ServerSelectionRequest */

	/* Excluded from this release type: ServerSelectionStartedEvent */

	/* Excluded from this release type: ServerSelectionSucceededEvent */

	/* Excluded from this release type: ServerSelector */

	/**
	 * Reflects the existence of a session on the server. Can be reused by the session pool.
	 * WARNING: not meant to be instantiated directly. For internal use only.
	 * @public
	 */
	class ServerSession {
		id: ServerSessionId;
		lastUse: number;
		txnNumber: number;
		isDirty: boolean;
		/* Excluded from this release type: __constructor */
		/**
		 * Determines if the server session has timed out.
		 *
		 * @param sessionTimeoutMinutes - The server's "logicalSessionTimeoutMinutes"
		 */
		hasTimedOut(sessionTimeoutMinutes: number): boolean;
	}

	/** @public */
	type ServerSessionId = {
		id: Binary;
	};

	/* Excluded from this release type: ServerSessionPool */

	/**
	 * An enumeration of server types we know about
	 * @public
	 */
	const ServerType: Readonly<{
		readonly Standalone: "Standalone";
		readonly Mongos: "Mongos";
		readonly PossiblePrimary: "PossiblePrimary";
		readonly RSPrimary: "RSPrimary";
		readonly RSSecondary: "RSSecondary";
		readonly RSArbiter: "RSArbiter";
		readonly RSOther: "RSOther";
		readonly RSGhost: "RSGhost";
		readonly Unknown: "Unknown";
		readonly LoadBalancer: "LoadBalancer";
	}>;

	/** @public */
	type ServerType = (typeof ServerType)[keyof typeof ServerType];

	/** @public */
	type SetFields<TSchema> = ({
		readonly [key in KeysOfAType<TSchema, ReadonlyArray<any> | undefined>]?: OptionalId<Flatten<TSchema[key]>> | AddToSetOperators<Array<OptionalId<Flatten<TSchema[key]>>>>;
	} & IsAny<TSchema[keyof TSchema], object, NotAcceptedFields<TSchema, ReadonlyArray<any> | undefined>>) & {
		readonly [key: string]: AddToSetOperators<any> | any;
	};

	/** @public */
	type SetProfilingLevelOptions = CommandOperationOptions;

	/* Excluded from this release type: SeverityLevel */

	/** @public */
	type Sort =
		| string
		| Exclude<
				SortDirection,
				{
					$meta: string;
				}
		  >
		| string[]
		| {
				[key: string]: SortDirection;
		  }
		| Map<string, SortDirection>
		| [string, SortDirection][]
		| [string, SortDirection];

	/** @public */
	type SortDirection =
		| 1
		| -1
		| "asc"
		| "desc"
		| "ascending"
		| "descending"
		| {
				$meta: string;
		  };

	/* Excluded from this release type: SortDirectionForCmd */

	/* Excluded from this release type: SortForCmd */

	/* Excluded from this release type: SrvPoller */

	/* Excluded from this release type: SrvPollerEvents */

	/* Excluded from this release type: SrvPollerOptions */

	/* Excluded from this release type: SrvPollingEvent */

	/* Excluded from this release type: StateMachineExecutable */

	/** @public */
	class StreamDescription {
		address: string;
		type: ServerType;
		minWireVersion?: number;
		maxWireVersion?: number;
		maxBsonObjectSize: number;
		maxMessageSizeBytes: number;
		maxWriteBatchSize: number;
		compressors: CompressorName[];
		compressor?: CompressorName;
		logicalSessionTimeoutMinutes?: number;
		loadBalanced: boolean;
		__nodejs_mock_server__?: boolean;
		zlibCompressionLevel?: number;
		serverConnectionId: bigint | null;
		hello: Document | null;
		constructor(address: string, options?: StreamDescriptionOptions);
		receiveResponse(response: Document | null): void;
		parseServerConnectionID(serverConnectionId: number | Double | bigint | Long): bigint;
	}

	/** @public */
	interface StreamDescriptionOptions {
		compressors?: CompressorName[];
		logicalSessionTimeoutMinutes?: number;
		loadBalanced: boolean;
	}

	/**
	 * @public
	 * @experimental
	 */
	type StrictFilter<TSchema> =
		| Partial<TSchema>
		| ({
				[Property in Join<NestedPaths<WithId<TSchema>, []>, ".">]?: Condition<PropertyType<WithId<TSchema>, Property>>;
		  } & RootFilterOperators<WithId<TSchema>>);

	/**
	 * @public
	 * @experimental
	 */
	type StrictMatchKeysAndValues<TSchema> = Readonly<
		{
			[Property in Join<NestedPaths<TSchema, []>, ".">]?: PropertyType<TSchema, Property>;
		} & {
			[Property in `${NestedPathsOfType<TSchema, any[]>}.$${`[${string}]` | ""}`]?: ArrayElement<PropertyType<TSchema, Property extends `${infer Key}.$${string}` ? Key : never>>;
		} & {
			[Property in `${NestedPathsOfType<TSchema, Record<string, any>[]>}.$${`[${string}]` | ""}.${string}`]?: any;
		} & Document
	>;

	/**
	 * @public
	 * @experimental
	 */
	type StrictUpdateFilter<TSchema> = {
		$currentDate?: OnlyFieldsOfType<
			TSchema,
			Date | Timestamp,
			| true
			| {
					$type: "date" | "timestamp";
			  }
		>;
		$inc?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
		$min?: StrictMatchKeysAndValues<TSchema>;
		$max?: StrictMatchKeysAndValues<TSchema>;
		$mul?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
		$rename?: Record<string, string>;
		$set?: StrictMatchKeysAndValues<TSchema>;
		$setOnInsert?: StrictMatchKeysAndValues<TSchema>;
		$unset?: OnlyFieldsOfType<TSchema, any, "" | true | 1>;
		$addToSet?: SetFields<TSchema>;
		$pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
		$pull?: PullOperator<TSchema>;
		$push?: PushOperator<TSchema>;
		$pullAll?: PullAllOperator<TSchema>;
		$bit?: OnlyFieldsOfType<
			TSchema,
			NumericType | undefined,
			| {
					and: IntegerType;
			  }
			| {
					or: IntegerType;
			  }
			| {
					xor: IntegerType;
			  }
		>;
	} & Document;

	/** @public */
	type TagSet = {
		[key: string]: string;
	};

	/* Excluded from this release type: Timeout */

	/* Excluded from this release type: TimeoutContext */

	/* Excluded from this release type: TimeoutContextOptions */

	/** @public
	 * Configuration options for timeseries collections
	 * @see https://www.mongodb.com/docs/manual/core/timeseries-collections/
	 */
	interface TimeSeriesCollectionOptions extends Document {
		timeField: string;
		metaField?: string;
		granularity?: "seconds" | "minutes" | "hours" | string;
		bucketMaxSpanSeconds?: number;
		bucketRoundingSeconds?: number;
	}

	/* Excluded from this release type: TokenCache */

	/* Excluded from this release type: Topology */

	/* Excluded from this release type: TOPOLOGY_CLOSED */

	/* Excluded from this release type: TOPOLOGY_DESCRIPTION_CHANGED */

	/* Excluded from this release type: TOPOLOGY_OPENING */

	/**
	 * Emitted when topology is closed.
	 * @public
	 * @category Event
	 */
	class TopologyClosedEvent {
		/** A unique identifier for the topology */
		topologyId: number;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/**
	 * Representation of a deployment of servers
	 * @public
	 */
	class TopologyDescription {
		type: TopologyType;
		setName: string | null;
		maxSetVersion: number | null;
		maxElectionId: ObjectId | null;
		servers: Map<string, ServerDescription>;
		stale: boolean;
		compatible: boolean;
		compatibilityError?: string;
		logicalSessionTimeoutMinutes: number | null;
		heartbeatFrequencyMS: number;
		localThresholdMS: number;
		commonWireVersion: number;
		/**
		 * Create a TopologyDescription
		 */
		constructor(topologyType: TopologyType, serverDescriptions?: Map<string, ServerDescription> | null, setName?: string | null, maxSetVersion?: number | null, maxElectionId?: ObjectId | null, commonWireVersion?: number | null, options?: TopologyDescriptionOptions | null);
		/* Excluded from this release type: updateFromSrvPollingEvent */
		/* Excluded from this release type: update */
		get error(): MongoError | null;
		/**
		 * Determines if the topology description has any known servers
		 */
		get hasKnownServers(): boolean;
		/**
		 * Determines if this topology description has a data-bearing server available.
		 */
		get hasDataBearingServers(): boolean;
		/* Excluded from this release type: hasServer */
		/**
		 * Returns a JSON-serializable representation of the TopologyDescription.  This is primarily
		 * intended for use with JSON.stringify().
		 *
		 * This method will not throw.
		 */
		toJSON(): Document;
	}

	/**
	 * Emitted when topology description changes.
	 * @public
	 * @category Event
	 */
	class TopologyDescriptionChangedEvent {
		/** A unique identifier for the topology */
		topologyId: number;
		/** The old topology description */
		previousDescription: TopologyDescription;
		/** The new topology description */
		newDescription: TopologyDescription;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/** @public */
	interface TopologyDescriptionOptions {
		heartbeatFrequencyMS?: number;
		localThresholdMS?: number;
	}

	/** @public */
	type TopologyEvents = {
		/* Excluded from this release type: connect */
		serverOpening(event: ServerOpeningEvent): void;
		serverClosed(event: ServerClosedEvent): void;
		serverDescriptionChanged(event: ServerDescriptionChangedEvent): void;
		topologyClosed(event: TopologyClosedEvent): void;
		topologyOpening(event: TopologyOpeningEvent): void;
		topologyDescriptionChanged(event: TopologyDescriptionChangedEvent): void;
		error(error: Error): void;
		/* Excluded from this release type: open */
		close(): void;
		timeout(): void;
	} & Omit<ServerEvents, "connect"> &
		ConnectionPoolEvents &
		ConnectionEvents &
		EventEmitterWithState;

	/**
	 * Emitted when topology is initialized.
	 * @public
	 * @category Event
	 */
	class TopologyOpeningEvent {
		/** A unique identifier for the topology */
		topologyId: number;
		/* Excluded from this release type: name */
		/* Excluded from this release type: __constructor */
	}

	/* Excluded from this release type: TopologyOptions */

	/* Excluded from this release type: TopologyPrivate */

	/**
	 * An enumeration of topology types we know about
	 * @public
	 */
	const TopologyType: Readonly<{
		readonly Single: "Single";
		readonly ReplicaSetNoPrimary: "ReplicaSetNoPrimary";
		readonly ReplicaSetWithPrimary: "ReplicaSetWithPrimary";
		readonly Sharded: "Sharded";
		readonly Unknown: "Unknown";
		readonly LoadBalanced: "LoadBalanced";
	}>;

	/** @public */
	type TopologyType = (typeof TopologyType)[keyof typeof TopologyType];

	/** @public */
	interface TopologyVersion {
		processId: ObjectId;
		counter: Long;
	}

	/**
	 * @public
	 * A class maintaining state related to a server transaction. Internal Only
	 */
	class Transaction {
		/* Excluded from this release type: state */
		options: TransactionOptions;
		/* Excluded from this release type: _pinnedServer */
		/* Excluded from this release type: _recoveryToken */
		/* Excluded from this release type: __constructor */
		/* Excluded from this release type: server */
		get recoveryToken(): Document | undefined;
		get isPinned(): boolean;
		/** @returns Whether the transaction has started */
		get isStarting(): boolean;
		/**
		 * @returns Whether this session is presently in a transaction
		 */
		get isActive(): boolean;
		get isCommitted(): boolean;
		/* Excluded from this release type: transition */
		/* Excluded from this release type: pinServer */
		/* Excluded from this release type: unpinServer */
	}

	/**
	 * Configuration options for a transaction.
	 * @public
	 */
	interface TransactionOptions extends Omit<CommandOperationOptions, "timeoutMS"> {
		/** A default read concern for commands in this transaction */
		readConcern?: ReadConcernLike;
		/** A default writeConcern for commands in this transaction */
		writeConcern?: WriteConcern;
		/** A default read preference for commands in this transaction */
		readPreference?: ReadPreferenceLike;
		/** Specifies the maximum amount of time to allow a commit action on a transaction to run in milliseconds */
		maxCommitTimeMS?: number;
	}

	/* Excluded from this release type: TxnState */

	/**
	 * Typescript type safe event emitter
	 * @public
	 */
	class TypedEventEmitter<Events extends EventsDescription> {
		/* Excluded from this release type: mongoLogger */
		/* Excluded from this release type: component */
		/* Excluded from this release type: emitAndLog */
		/* Excluded from this release type: emitAndLogHeartbeat */
		/* Excluded from this release type: emitAndLogCommand */
	}

	/** @public */
	class UnorderedBulkOperation extends BulkOperationBase {
		/* Excluded from this release type: __constructor */
		handleWriteError(writeResult: BulkWriteResult): void;
		addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
	}

	/** @public */
	interface UpdateDescription<TSchema extends Document = Document> {
		/**
		 * A document containing key:value pairs of names of the fields that were
		 * changed, and the new value for those fields.
		 */
		updatedFields?: Partial<TSchema>;
		/**
		 * An array of field names that were removed from the document.
		 */
		removedFields?: string[];
		/**
		 * An array of documents which record array truncations performed with pipeline-based updates using one or more of the following stages:
		 * - $addFields
		 * - $set
		 * - $replaceRoot
		 * - $replaceWith
		 */
		truncatedArrays?: Array<{
			/** The name of the truncated field. */
			field: string;
			/** The number of elements in the truncated array. */
			newSize: number;
		}>;
		/**
		 * A document containing additional information about any ambiguous update paths from the update event.  The document
		 * maps the full ambiguous update path to an array containing the actual resolved components of the path.  For example,
		 * given a document shaped like `{ a: { '0': 0 } }`, and an update of `{ $inc: 'a.0' }`, disambiguated paths would look like
		 * the following:
		 *
		 * ```
		 *   {
		 *     'a.0': ['a', '0']
		 *   }
		 * ```
		 *
		 * This field is only present when there are ambiguous paths that are updated as a part of the update event and `showExpandedEvents`
		 * is enabled for the change stream.
		 * @sinceServerVersion 6.1.0
		 */
		disambiguatedPaths?: Document;
	}

	/** @public */
	type UpdateFilter<TSchema> = {
		$currentDate?: OnlyFieldsOfType<
			TSchema,
			Date | Timestamp,
			| true
			| {
					$type: "date" | "timestamp";
			  }
		>;
		$inc?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
		$min?: MatchKeysAndValues<TSchema>;
		$max?: MatchKeysAndValues<TSchema>;
		$mul?: OnlyFieldsOfType<TSchema, NumericType | undefined>;
		$rename?: Record<string, string>;
		$set?: MatchKeysAndValues<TSchema>;
		$setOnInsert?: MatchKeysAndValues<TSchema>;
		$unset?: OnlyFieldsOfType<TSchema, any, "" | true | 1>;
		$addToSet?: SetFields<TSchema>;
		$pop?: OnlyFieldsOfType<TSchema, ReadonlyArray<any>, 1 | -1>;
		$pull?: PullOperator<TSchema>;
		$push?: PushOperator<TSchema>;
		$pullAll?: PullAllOperator<TSchema>;
		$bit?: OnlyFieldsOfType<
			TSchema,
			NumericType | undefined,
			| {
					and: IntegerType;
			  }
			| {
					or: IntegerType;
			  }
			| {
					xor: IntegerType;
			  }
		>;
	} & Document;

	/** @public */
	interface UpdateManyModel<TSchema extends Document = Document> {
		/** The filter to limit the updated documents. */
		filter: Filter<TSchema>;
		/**
		 * The modifications to apply. The value can be either:
		 * UpdateFilter<TSchema> - A document that contains update operator expressions,
		 * Document[] - an aggregation pipeline.
		 */
		update: UpdateFilter<TSchema> | Document[];
		/** A set of filters specifying to which array elements an update should apply. */
		arrayFilters?: Document[];
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query. */
		upsert?: boolean;
	}

	/** @public */
	interface UpdateOneModel<TSchema extends Document = Document> {
		/** The filter to limit the updated documents. */
		filter: Filter<TSchema>;
		/**
		 * The modifications to apply. The value can be either:
		 * UpdateFilter<TSchema> - A document that contains update operator expressions,
		 * Document[] - an aggregation pipeline.
		 */
		update: UpdateFilter<TSchema> | Document[];
		/** A set of filters specifying to which array elements an update should apply. */
		arrayFilters?: Document[];
		/** Specifies a collation. */
		collation?: CollationOptions;
		/** The index to use. If specified, then the query system will only consider plans using the hinted index. */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query. */
		upsert?: boolean;
	}

	/** @public */
	interface UpdateOptions extends CommandOperationOptions {
		/** A set of filters specifying to which array elements an update should apply */
		arrayFilters?: Document[];
		/** If true, allows the write to opt-out of document level validation */
		bypassDocumentValidation?: boolean;
		/** Specifies a collation */
		collation?: CollationOptions;
		/** Specify that the update query should only consider plans using the hinted index */
		hint?: Hint;
		/** When true, creates a new document if no document matches the query */
		upsert?: boolean;
		/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
		let?: Document;
	}

	/**
	 * @public
	 * `TSchema` is the schema of the collection
	 */
	interface UpdateResult<TSchema extends Document = Document> {
		/** Indicates whether this write result was acknowledged. If not, then all other members of this result will be undefined */
		acknowledged: boolean;
		/** The number of documents that matched the filter */
		matchedCount: number;
		/** The number of documents that were modified */
		modifiedCount: number;
		/** The number of documents that were upserted */
		upsertedCount: number;
		/** The identifier of the inserted document if an upsert took place */
		upsertedId: InferIdType<TSchema> | null;
	}

	/** @public */
	interface UpdateStatement {
		/** The query that matches documents to update. */
		q: Document;
		/** The modifications to apply. */
		u: Document | Document[];
		/**  If true, perform an insert if no documents match the query. */
		upsert?: boolean;
		/** If true, updates all documents that meet the query criteria. */
		multi?: boolean;
		/** Specifies the collation to use for the operation. */
		collation?: CollationOptions;
		/** An array of filter documents that determines which array elements to modify for an update operation on an array field. */
		arrayFilters?: Document[];
		/** A document or string that specifies the index to use to support the query predicate. */
		hint?: Hint;
	}

	/** @public */
	interface ValidateCollectionOptions extends CommandOperationOptions {
		/** Validates a collection in the background, without interrupting read or write traffic (only in MongoDB 4.4+) */
		background?: boolean;
	}

	/** @public */
	type W = number | "majority";

	/* Excluded from this release type: WAITING_FOR_SUITABLE_SERVER */

	/* Excluded from this release type: WaitingForSuitableServerEvent */

	/* Excluded from this release type: WaitQueueMember */

	/* Excluded from this release type: WithConnectionCallback */

	/** Add an _id field to an object shaped type @public */
	type WithId<TSchema> = EnhancedOmit<TSchema, "_id"> & {
		_id: InferIdType<TSchema>;
	};

	/** Remove the _id field from an object shaped type @public */
	type WithoutId<TSchema> = Omit<TSchema, "_id">;

	/** @public */
	type WithSessionCallback<T = unknown> = (session: ClientSession) => Promise<T>;

	/** @public */
	type WithTransactionCallback<T = any> = (session: ClientSession) => Promise<T>;

	/* Excluded from this release type: Workflow */

	/**
	 * A MongoDB WriteConcern, which describes the level of acknowledgement
	 * requested from MongoDB for write operations.
	 * @public
	 *
	 * @see https://www.mongodb.com/docs/manual/reference/write-concern/
	 */
	class WriteConcern {
		/**
		 * Request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
		 * If w is 0 and is set on a write operation, the server will not send a response.
		 */
		readonly w?: W;
		/** Request acknowledgment that the write operation has been written to the on-disk journal */
		readonly journal?: boolean;
		/**
		 * Specify a time limit to prevent write operations from blocking indefinitely.
		 */
		readonly wtimeoutMS?: number;
		/**
		 * Specify a time limit to prevent write operations from blocking indefinitely.
		 * @deprecated Will be removed in the next major version. Please use wtimeoutMS.
		 */
		wtimeout?: number;
		/**
		 * Request acknowledgment that the write operation has been written to the on-disk journal.
		 * @deprecated Will be removed in the next major version. Please use journal.
		 */
		j?: boolean;
		/**
		 * Equivalent to the j option.
		 * @deprecated Will be removed in the next major version. Please use journal.
		 */
		fsync?: boolean | 1;
		/**
		 * Constructs a WriteConcern from the write concern properties.
		 * @param w - request acknowledgment that the write operation has propagated to a specified number of mongod instances or to mongod instances with specified tags.
		 * @param wtimeoutMS - specify a time limit to prevent write operations from blocking indefinitely
		 * @param journal - request acknowledgment that the write operation has been written to the on-disk journal
		 * @param fsync - equivalent to the j option. Is deprecated and will be removed in the next major version.
		 */
		constructor(w?: W, wtimeoutMS?: number, journal?: boolean, fsync?: boolean | 1);
		/**
		 * Apply a write concern to a command document. Will modify and return the command.
		 */
		static apply(command: Document, writeConcern: WriteConcern): Document;
		/** Construct a WriteConcern given an options object. */
		static fromOptions(options?: WriteConcernOptions | WriteConcern | W, inherit?: WriteConcernOptions | WriteConcern): WriteConcern | undefined;
	}

	/**
	 * An error representing a failure by the server to apply the requested write concern to the bulk operation.
	 * @public
	 * @category Error
	 */
	class WriteConcernError {
		/* Excluded from this release type: [kServerError] */
		constructor(error: WriteConcernErrorData);
		/** Write concern error code. */
		get code(): number | undefined;
		/** Write concern error message. */
		get errmsg(): string | undefined;
		/** Write concern error info. */
		get errInfo(): Document | undefined;
		toJSON(): WriteConcernErrorData;
		toString(): string;
	}

	/** @public */
	interface WriteConcernErrorData {
		code: number;
		errmsg: string;
		errInfo?: Document;
	}

	/**
	 * The type of the result property of MongoWriteConcernError
	 * @public
	 */
	interface WriteConcernErrorResult {
		writeConcernError: {
			code: number;
			errmsg: string;
			codeName?: string;
			errInfo?: Document;
		};
		ok: number;
		code?: number;
		errorLabels?: string[];
		[x: string | number]: unknown;
	}

	/** @public */
	interface WriteConcernOptions {
		/** Write Concern as an object */
		writeConcern?: WriteConcern | WriteConcernSettings;
	}

	/** @public */
	interface WriteConcernSettings {
		/** The write concern */
		w?: W;
		/**
		 * The write concern timeout.
		 */
		wtimeoutMS?: number;
		/** The journal write concern */
		journal?: boolean;
		/**
		 * The journal write concern.
		 * @deprecated Will be removed in the next major version. Please use the journal option.
		 */
		j?: boolean;
		/**
		 * The write concern timeout.
		 */
		wtimeout?: number;
		/**
		 * The file sync write concern.
		 * @deprecated Will be removed in the next major version. Please use the journal option.
		 */
		fsync?: boolean | 1;
	}

	/**
	 * An error that occurred during a BulkWrite on the server.
	 * @public
	 * @category Error
	 */
	class WriteError {
		err: BulkWriteOperationError;
		constructor(err: BulkWriteOperationError);
		/** WriteError code. */
		get code(): number;
		/** WriteError original bulk operation index. */
		get index(): number;
		/** WriteError message. */
		get errmsg(): string | undefined;
		/** WriteError details. */
		get errInfo(): Document | undefined;
		/** Returns the underlying operation that caused the error */
		getOperation(): Document;
		toJSON(): {
			code: number;
			index: number;
			errmsg?: string;
			op: Document;
		};
		toString(): string;
	}

	interface MongoClientOptions extends BSONSerializeOptions {
		/** Specifies the name of the replica set, if the mongod is a member of a replica set. */
		replicaSet?: string;
		/**
		 * @experimental
		 * Specifies the time an operation will run until it throws a timeout error
		 */
		timeoutMS?: number;
		/** Enables or disables TLS/SSL for the connection. */
		tls?: boolean;
		/** A boolean to enable or disables TLS/SSL for the connection. (The ssl option is equivalent to the tls option.) */
		ssl?: boolean;
		/** Specifies the location of a local .pem file that contains either the client's TLS/SSL certificate and key. */
		tlsCertificateKeyFile?: string;
		/** Specifies the password to de-crypt the tlsCertificateKeyFile. */
		tlsCertificateKeyFilePassword?: string;
		/** 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. */
		tlsCAFile?: string;
		/** Specifies the location of a local CRL .pem file that contains the client revokation list. */
		tlsCRLFile?: string;
		/** Bypasses validation of the certificates presented by the mongod/mongos instance */
		tlsAllowInvalidCertificates?: boolean;
		/** Disables hostname validation of the certificate presented by the mongod/mongos instance. */
		tlsAllowInvalidHostnames?: boolean;
		/** Disables various certificate validations. */
		tlsInsecure?: boolean;
		/** The time in milliseconds to attempt a connection before timing out. */
		connectTimeoutMS?: number;
		/** The time in milliseconds to attempt a send or receive on a socket before the attempt times out. */
		socketTimeoutMS?: number;
		/** An array or comma-delimited string of compressors to enable network compression for communication between this client and a mongod/mongos instance. */
		compressors?: CompressorName[] | string;
		/** An integer that specifies the compression level if using zlib for network compression. */
		zlibCompressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | undefined;
		/** The maximum number of hosts to connect to when using an srv connection string, a setting of `0` means unlimited hosts */
		srvMaxHosts?: number;
		/**
		 * Modifies the srv URI to look like:
		 *
		 * `_{srvServiceName}._tcp.{hostname}.{domainname}`
		 *
		 * Querying this DNS URI is expected to respond with SRV records
		 */
		srvServiceName?: string;
		/** The maximum number of connections in the connection pool. */
		maxPoolSize?: number;
		/** The minimum number of connections in the connection pool. */
		minPoolSize?: number;
		/** The maximum number of connections that may be in the process of being established concurrently by the connection pool. */
		maxConnecting?: number;
		/** The maximum number of milliseconds that a connection can remain idle in the pool before being removed and closed. */
		maxIdleTimeMS?: number;
		/** The maximum time in milliseconds that a thread can wait for a connection to become available. */
		waitQueueTimeoutMS?: number;
		/** Specify a read concern for the collection (only MongoDB 3.2 or higher supported) */
		readConcern?: ReadConcernLike;
		/** The level of isolation */
		readConcernLevel?: ReadConcernLevel;
		/** Specifies the read preferences for this connection */
		readPreference?: ReadPreferenceMode | ReadPreference;
		/** Specifies, in seconds, how stale a secondary can be before the client stops using it for read operations. */
		maxStalenessSeconds?: number;
		/** Specifies the tags document as a comma-separated list of colon-separated key-value pairs.  */
		readPreferenceTags?: TagSet[];
		/** The auth settings for when connection to server. */
		auth?: Auth;
		/** Specify the database name associated with the user’s credentials. */
		authSource?: string;
		/** Specify the authentication mechanism that MongoDB will use to authenticate the connection. */
		authMechanism?: AuthMechanism;
		/** Specify properties for the specified authMechanism as a comma-separated list of colon-separated key-value pairs. */
		authMechanismProperties?: AuthMechanismProperties;
		/** The size (in milliseconds) of the latency window for selecting among multiple suitable MongoDB instances. */
		localThresholdMS?: number;
		/** Specifies how long (in milliseconds) to block for server selection before throwing an exception.  */
		serverSelectionTimeoutMS?: number;
		/** 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. */
		heartbeatFrequencyMS?: number;
		/** 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. */
		minHeartbeatFrequencyMS?: number;
		/** 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 */
		appName?: string;
		/** Enables retryable reads. */
		retryReads?: boolean;
		/** Enable retryable writes. */
		retryWrites?: boolean;
		/** Allow a driver to force a Single topology type with a connection string containing one host */
		directConnection?: boolean;
		/** Instruct the driver it is connecting to a load balancer fronting a mongos like service */
		loadBalanced?: boolean;
		/**
		 * The write concern w value
		 * @deprecated Please use the `writeConcern` option instead
		 */
		w?: W;
		/**
		 * The write concern timeout
		 * @deprecated Please use the `writeConcern` option instead
		 */
		wtimeoutMS?: number;
		/**
		 * The journal write concern
		 * @deprecated Please use the `writeConcern` option instead
		 */
		journal?: boolean;
		/**
		 * A MongoDB WriteConcern, which describes the level of acknowledgement
		 * requested from MongoDB for write operations.
		 *
		 * @see https://www.mongodb.com/docs/manual/reference/write-concern/
		 */
		writeConcern?: WriteConcern | WriteConcernSettings;
		/** TCP Connection no delay */
		noDelay?: boolean;
		/** Force server to assign `_id` values instead of driver */
		forceServerObjectId?: boolean;
		/** A primary key factory function for generation of custom `_id` keys */
		pkFactory?: PkFactory;
		/** Enable command monitoring for this client */
		monitorCommands?: boolean;
		/** Server API version */
		serverApi?: ServerApi | ServerApiVersion;
		/**
		 * Optionally enable in-use auto encryption
		 *
		 * @remarks
		 *  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
		 *  (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.
		 *
		 *  Automatic encryption requires the authenticated user to have the [listCollections privilege action](https://www.mongodb.com/docs/manual/reference/command/listCollections/#dbcmd.listCollections).
		 *
		 *  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:
		 *  - AutoEncryptionOptions.keyVaultClient is not passed.
		 *  - AutoEncryptionOptions.bypassAutomaticEncryption is false.
		 *
		 * 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.
		 */
		autoEncryption?: AutoEncryptionOptions;
		/** Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver */
		driverInfo?: DriverInfo;
		/** Configures a Socks5 proxy host used for creating TCP connections. */
		proxyHost?: string;
		/** Configures a Socks5 proxy port used for creating TCP connections. */
		proxyPort?: number;
		/** Configures a Socks5 proxy username when the proxy in proxyHost requires username/password authentication. */
		proxyUsername?: string;
		/** Configures a Socks5 proxy password when the proxy in proxyHost requires username/password authentication. */
		proxyPassword?: string;
		/** Instructs the driver monitors to use a specific monitoring mode */
		serverMonitoringMode?: ServerMonitoringMode;
		/* Excluded from this release type: srvPoller */
		/* Excluded from this release type: connectionType */
		/* Excluded from this release type: mongodbLogPath */
		/* Excluded from this release type: mongodbLogComponentSeverities */
		/* Excluded from this release type: mongodbLogMaxDocumentLength */
		/* Excluded from this release type: __index */
	}

	class Collection<TSchema extends Document = Document> {
		/* Excluded from this release type: s */
		/* Excluded from this release type: client */
		/* Excluded from this release type: __constructor */
		/**
		 * The name of the database this collection belongs to
		 */
		get dbName(): string;
		/**
		 * The name of this collection
		 */
		get collectionName(): string;
		/**
		 * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}`
		 */
		get namespace(): string;
		/* Excluded from this release type: fullNamespace */
		/**
		 * The current readConcern of the collection. If not explicitly defined for
		 * this collection, will be inherited from the parent DB
		 */
		get readConcern(): ReadConcern | undefined;
		/**
		 * The current readPreference of the collection. If not explicitly defined for
		 * this collection, will be inherited from the parent DB
		 */
		get readPreference(): ReadPreference | undefined;
		get bsonOptions(): BSONSerializeOptions;
		/**
		 * The current writeConcern of the collection. If not explicitly defined for
		 * this collection, will be inherited from the parent DB
		 */
		get writeConcern(): WriteConcern | undefined;
		/** The current index hint for the collection */
		get hint(): Hint | undefined;
		set hint(v: Hint | undefined);
		get timeoutMS(): number | undefined;
		/**
		 * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
		 * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
		 * can be overridden by setting the **forceServerObjectId** flag.
		 *
		 * @param doc - The document to insert
		 * @param options - Optional settings for the command
		 */
		insertOne(doc: OptionalUnlessRequiredId<TSchema>, options?: InsertOneOptions): Promise<InsertOneResult<TSchema>>;
		/**
		 * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
		 * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
		 * can be overridden by setting the **forceServerObjectId** flag.
		 *
		 * @param docs - The documents to insert
		 * @param options - Optional settings for the command
		 */
		insertMany(docs: ReadonlyArray<OptionalUnlessRequiredId<TSchema>>, options?: BulkWriteOptions): Promise<InsertManyResult<TSchema>>;
		/**
		 * Perform a bulkWrite operation without a fluent API
		 *
		 * Legal operation types are
		 * - `insertOne`
		 * - `replaceOne`
		 * - `updateOne`
		 * - `updateMany`
		 * - `deleteOne`
		 * - `deleteMany`
		 *
		 * If documents passed in do not contain the **_id** field,
		 * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
		 * can be overridden by setting the **forceServerObjectId** flag.
		 *
		 * @param operations - Bulk operations to perform
		 * @param options - Optional settings for the command
		 * @throws MongoDriverError if operations is not an array
		 */
		bulkWrite(operations: ReadonlyArray<AnyBulkWriteOperation<TSchema>>, options?: BulkWriteOptions): Promise<BulkWriteResult>;
		/**
		 * Update a single document in a collection
		 *
		 * The value of `update` can be either:
		 * - UpdateFilter<TSchema> - A document that contains update operator expressions,
		 * - Document[] - an aggregation pipeline.
		 *
		 * @param filter - The filter used to select the document to update
		 * @param update - The modifications to apply
		 * @param options - Optional settings for the command
		 */
		updateOne(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions): Promise<UpdateResult<TSchema>>;
		/**
		 * Replace a document in a collection with another document
		 *
		 * @param filter - The filter used to select the document to replace
		 * @param replacement - The Document that replaces the matching document
		 * @param options - Optional settings for the command
		 */
		replaceOne(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options?: ReplaceOptions): Promise<UpdateResult<TSchema> | Document>;
		/**
		 * Update multiple documents in a collection
		 *
		 * The value of `update` can be either:
		 * - UpdateFilter<TSchema> - A document that contains update operator expressions,
		 * - Document[] - an aggregation pipeline.
		 *
		 * @param filter - The filter used to select the document to update
		 * @param update - The modifications to apply
		 * @param options - Optional settings for the command
		 */
		updateMany(filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions): Promise<UpdateResult<TSchema>>;
		/**
		 * Delete a document from a collection
		 *
		 * @param filter - The filter used to select the document to remove
		 * @param options - Optional settings for the command
		 */
		deleteOne(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>;
		/**
		 * Delete multiple documents from a collection
		 *
		 * @param filter - The filter used to select the documents to remove
		 * @param options - Optional settings for the command
		 */
		deleteMany(filter?: Filter<TSchema>, options?: DeleteOptions): Promise<DeleteResult>;
		/**
		 * Rename the collection.
		 *
		 * @remarks
		 * This operation does not inherit options from the Db or MongoClient.
		 *
		 * @param newName - New name of of the collection.
		 * @param options - Optional settings for the command
		 */
		rename(newName: string, options?: RenameOptions): Promise<Collection>;
		/**
		 * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
		 *
		 * @param options - Optional settings for the command
		 */
		drop(options?: DropCollectionOptions): Promise<boolean>;
		/**
		 * Fetches the first document that matches the filter
		 *
		 * @param filter - Query for find Operation
		 * @param options - Optional settings for the command
		 */
		findOne(): Promise<WithId<TSchema> | null>;
		findOne(filter: Filter<TSchema>): Promise<WithId<TSchema> | null>;
		findOne(filter: Filter<TSchema>, options: Omit<FindOptions, "timeoutMode">): Promise<WithId<TSchema> | null>;
		findOne<T = TSchema>(): Promise<T | null>;
		findOne<T = TSchema>(filter: Filter<TSchema>): Promise<T | null>;
		findOne<T = TSchema>(filter: Filter<TSchema>, options?: Omit<FindOptions, "timeoutMode">): Promise<T | null>;
		/**
		 * Creates a cursor for a filter that can be used to iterate over results from MongoDB
		 *
		 * @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate
		 */
		find(): FindCursor<WithId<TSchema>>;
		find(filter: Filter<TSchema>, options?: FindOptions): FindCursor<WithId<TSchema>>;
		find<T extends Document>(filter: Filter<TSchema>, options?: FindOptions): FindCursor<T>;
		/**
		 * Returns the options of the collection.
		 *
		 * @param options - Optional settings for the command
		 */
		options(options?: OperationOptions): Promise<Document>;
		/**
		 * Returns if the collection is a capped collection
		 *
		 * @param options - Optional settings for the command
		 */
		isCapped(options?: OperationOptions): Promise<boolean>;
		/**
		 * Creates an index on the db and collection collection.
		 *
		 * @param indexSpec - The field name or index specification to create an index for
		 * @param options - Optional settings for the command
		 *
		 * @example
		 * ```ts
		 * const collection = client.db('foo').collection('bar');
		 *
		 * await collection.createIndex({ a: 1, b: -1 });
		 *
		 * // Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
		 * await collection.createIndex([ [c, 1], [d, -1] ]);
		 *
		 * // Equivalent to { e: 1 }
		 * await collection.createIndex('e');
		 *
		 * // Equivalent to { f: 1, g: 1 }
		 * await collection.createIndex(['f', 'g'])
		 *
		 * // Equivalent to { h: 1, i: -1 }
		 * await collection.createIndex([ { h: 1 }, { i: -1 } ]);
		 *
		 * // Equivalent to { j: 1, k: -1, l: 2d }
		 * await collection.createIndex(['j', ['k', -1], { l: '2d' }])
		 * ```
		 */
		createIndex(indexSpec: IndexSpecification, options?: CreateIndexesOptions): Promise<string>;
		/**
		 * Creates multiple indexes in the collection, this method is only supported for
		 * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
		 * error.
		 *
		 * **Note**: Unlike {@link Collection#createIndex| createIndex}, this function takes in raw index specifications.
		 * Index specifications are defined {@link https://www.mongodb.com/docs/manual/reference/command/createIndexes/| here}.
		 *
		 * @param indexSpecs - An array of index specifications to be created
		 * @param options - Optional settings for the command
		 *
		 * @example
		 * ```ts
		 * const collection = client.db('foo').collection('bar');
		 * await collection.createIndexes([
		 *   // Simple index on field fizz
		 *   {
		 *     key: { fizz: 1 },
		 *   }
		 *   // wildcard index
		 *   {
		 *     key: { '$**': 1 }
		 *   },
		 *   // named index on darmok and jalad
		 *   {
		 *     key: { darmok: 1, jalad: -1 }
		 *     name: 'tanagra'
		 *   }
		 * ]);
		 * ```
		 */
		createIndexes(indexSpecs: IndexDescription[], options?: CreateIndexesOptions): Promise<string[]>;
		/**
		 * Drops an index from this collection.
		 *
		 * @param indexName - Name of the index to drop.
		 * @param options - Optional settings for the command
		 */
		dropIndex(indexName: string, options?: DropIndexesOptions): Promise<Document>;
		/**
		 * Drops all indexes from this collection.
		 *
		 * @param options - Optional settings for the command
		 */
		dropIndexes(options?: DropIndexesOptions): Promise<boolean>;
		/**
		 * Get the list of all indexes information for the collection.
		 *
		 * @param options - Optional settings for the command
		 */
		listIndexes(options?: ListIndexesOptions): ListIndexesCursor;
		/**
		 * Checks if one or more indexes exist on the collection, fails on first non-existing index
		 *
		 * @param indexes - One or more index names to check.
		 * @param options - Optional settings for the command
		 */
		indexExists(indexes: string | string[], options?: ListIndexesOptions): Promise<boolean>;
		/**
		 * Retrieves this collections index info.
		 *
		 * @param options - Optional settings for the command
		 */
		indexInformation(
			options: IndexInformationOptions & {
				full: true;
			}
		): Promise<IndexDescriptionInfo[]>;
		indexInformation(
			options: IndexInformationOptions & {
				full?: false;
			}
		): Promise<IndexDescriptionCompact>;
		indexInformation(options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
		indexInformation(): Promise<IndexDescriptionCompact>;
		/**
		 * Gets an estimate of the count of documents in a collection using collection metadata.
		 * This will always run a count command on all server versions.
		 *
		 * due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command,
		 * which estimatedDocumentCount uses in its implementation, was not included in v1 of
		 * the Stable API, and so users of the Stable API with estimatedDocumentCount are
		 * recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid
		 * encountering errors.
		 *
		 * @see {@link https://www.mongodb.com/docs/manual/reference/command/count/#behavior|Count: Behavior}
		 * @param options - Optional settings for the command
		 */
		estimatedDocumentCount(options?: EstimatedDocumentCountOptions): Promise<number>;
		/**
		 * Gets the number of documents matching the filter.
		 * For a fast count of the total documents in a collection see {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
		 *
		 * 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.
		 *
		 * **Note**: When migrating from {@link Collection#count| count} to {@link Collection#countDocuments| countDocuments}
		 * the following query operators must be replaced:
		 *
		 * | Operator | Replacement |
		 * | -------- | ----------- |
		 * | `$where`   | [`$expr`][1] |
		 * | `$near`    | [`$geoWithin`][2] with [`$center`][3] |
		 * | `$nearSphere` | [`$geoWithin`][2] with [`$centerSphere`][4] |
		 *
		 * [1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/
		 * [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
		 * [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
		 * [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
		 *
		 * @param filter - The filter for the count
		 * @param options - Optional settings for the command
		 *
		 * @see https://www.mongodb.com/docs/manual/reference/operator/query/expr/
		 * @see https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
		 * @see https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
		 * @see https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
		 */
		countDocuments(filter?: Filter<TSchema>, options?: CountDocumentsOptions): Promise<number>;
		/**
		 * The distinct command returns a list of distinct values for the given key across a collection.
		 *
		 * @param key - Field of the document to find distinct values for
		 * @param filter - The filter for filtering the set of documents to which we apply the distinct filter.
		 * @param options - Optional settings for the command
		 */
		distinct<Key extends keyof WithId<TSchema>>(key: Key): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
		distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
		distinct<Key extends keyof WithId<TSchema>>(key: Key, filter: Filter<TSchema>, options: DistinctOptions): Promise<Array<Flatten<WithId<TSchema>[Key]>>>;
		distinct(key: string): Promise<any[]>;
		distinct(key: string, filter: Filter<TSchema>): Promise<any[]>;
		distinct(key: string, filter: Filter<TSchema>, options: DistinctOptions): Promise<any[]>;
		/**
		 * Retrieve all the indexes on the collection.
		 *
		 * @param options - Optional settings for the command
		 */
		indexes(
			options: IndexInformationOptions & {
				full?: true;
			}
		): Promise<IndexDescriptionInfo[]>;
		indexes(
			options: IndexInformationOptions & {
				full: false;
			}
		): Promise<IndexDescriptionCompact>;
		indexes(options: IndexInformationOptions): Promise<IndexDescriptionCompact | IndexDescriptionInfo[]>;
		indexes(options?: ListIndexesOptions): Promise<IndexDescriptionInfo[]>;
		/**
		 * Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
		 *
		 * @param filter - The filter used to select the document to remove
		 * @param options - Optional settings for the command
		 */
		findOneAndDelete(
			filter: Filter<TSchema>,
			options: FindOneAndDeleteOptions & {
				includeResultMetadata: true;
			}
		): Promise<ModifyResult<TSchema>>;
		findOneAndDelete(
			filter: Filter<TSchema>,
			options: FindOneAndDeleteOptions & {
				includeResultMetadata: false;
			}
		): Promise<WithId<TSchema> | null>;
		findOneAndDelete(filter: Filter<TSchema>, options: FindOneAndDeleteOptions): Promise<WithId<TSchema> | null>;
		findOneAndDelete(filter: Filter<TSchema>): Promise<WithId<TSchema> | null>;
		/**
		 * Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
		 *
		 * @param filter - The filter used to select the document to replace
		 * @param replacement - The Document that replaces the matching document
		 * @param options - Optional settings for the command
		 */
		findOneAndReplace(
			filter: Filter<TSchema>,
			replacement: WithoutId<TSchema>,
			options: FindOneAndReplaceOptions & {
				includeResultMetadata: true;
			}
		): Promise<ModifyResult<TSchema>>;
		findOneAndReplace(
			filter: Filter<TSchema>,
			replacement: WithoutId<TSchema>,
			options: FindOneAndReplaceOptions & {
				includeResultMetadata: false;
			}
		): Promise<WithId<TSchema> | null>;
		findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions): Promise<WithId<TSchema> | null>;
		findOneAndReplace(filter: Filter<TSchema>, replacement: WithoutId<TSchema>): Promise<WithId<TSchema> | null>;
		/**
		 * Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
		 *
		 * @param filter - The filter used to select the document to update
		 * @param update - Update operations to be performed on the document
		 * @param options - Optional settings for the command
		 */
		findOneAndUpdate(
			filter: Filter<TSchema>,
			update: UpdateFilter<TSchema>,
			options: FindOneAndUpdateOptions & {
				includeResultMetadata: true;
			}
		): Promise<ModifyResult<TSchema>>;
		findOneAndUpdate(
			filter: Filter<TSchema>,
			update: UpdateFilter<TSchema>,
			options: FindOneAndUpdateOptions & {
				includeResultMetadata: false;
			}
		): Promise<WithId<TSchema> | null>;
		findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options: FindOneAndUpdateOptions): Promise<WithId<TSchema> | null>;
		findOneAndUpdate(filter: Filter<TSchema>, update: UpdateFilter<TSchema>): Promise<WithId<TSchema> | null>;
		/**
		 * Execute an aggregation framework pipeline against the collection, needs MongoDB \>= 2.2
		 *
		 * @param pipeline - An array of aggregation pipelines to execute
		 * @param options - Optional settings for the command
		 */
		aggregate<T extends Document = Document>(pipeline?: Document[], options?: AggregateOptions): AggregationCursor<T>;
		/**
		 * Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
		 *
		 * @throws MongoNotConnectedError
		 * @remarks
		 * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
		 * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
		 */
		initializeUnorderedBulkOp(options?: BulkWriteOptions): UnorderedBulkOperation;
		/**
		 * 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.
		 *
		 * @throws MongoNotConnectedError
		 * @remarks
		 * **NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.
		 * However, `collection.bulkWrite()` provides an equivalent API that does not require prior connecting.
		 */
		initializeOrderedBulkOp(options?: BulkWriteOptions): OrderedBulkOperation;
		/**
		 * An estimated count of matching documents in the db to a filter.
		 *
		 * **NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents
		 * in a collection. To obtain an accurate count of documents in the collection, use {@link Collection#countDocuments| countDocuments}.
		 * To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.
		 *
		 * @deprecated use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead
		 *
		 * @param filter - The filter for the count.
		 * @param options - Optional settings for the command
		 */
		count(filter?: Filter<TSchema>, options?: CountOptions): Promise<number>;
		/**
		 * Returns all search indexes for the current collection.
		 *
		 * @param options - The options for the list indexes operation.
		 *
		 * @remarks Only available when used against a 7.0+ Atlas cluster.
		 */
		listSearchIndexes(options?: ListSearchIndexesOptions): ListSearchIndexesCursor;
		/**
		 * Returns all search indexes for the current collection.
		 *
		 * @param name - The name of the index to search for.  Only indexes with matching index names will be returned.
		 * @param options - The options for the list indexes operation.
		 *
		 * @remarks Only available when used against a 7.0+ Atlas cluster.
		 */
		listSearchIndexes(name: string, options?: ListSearchIndexesOptions): ListSearchIndexesCursor;
		/**
		 * Creates a single search index for the collection.
		 *
		 * @param description - The index description for the new search index.
		 * @returns A promise that resolves to the name of the new search index.
		 *
		 * @remarks Only available when used against a 7.0+ Atlas cluster.
		 */
		createSearchIndex(description: SearchIndexDescription): Promise<string>;
		/**
		 * Creates multiple search indexes for the current collection.
		 *
		 * @param descriptions - An array of `SearchIndexDescription`s for the new search indexes.
		 * @returns A promise that resolves to an array of the newly created search index names.
		 *
		 * @remarks Only available when used against a 7.0+ Atlas cluster.
		 * @returns
		 */
		createSearchIndexes(descriptions: SearchIndexDescription[]): Promise<string[]>;
		/**
		 * Deletes a search index by index name.
		 *
		 * @param name - The name of the search index to be deleted.
		 *
		 * @remarks Only available when used against a 7.0+ Atlas cluster.
		 */
		dropSearchIndex(name: string): Promise<void>;
		/**
		 * Updates a search index by replacing the existing index definition with the provided definition.
		 *
		 * @param name - The name of the search index to update.
		 * @param definition - The new search index definition.
		 *
		 * @remarks Only available when used against a 7.0+ Atlas cluster.
		 */
		updateSearchIndex(name: string, definition: Document): Promise<void>;
	}
}

interface CloudScriptDatabase {
	runtimeCollection(collectionName: string): mongodb.Collection<Document>;
	metaCollection(collectionName: string): mongodb.Collection<Document>;
	systemCollection(collectionName: string): mongodb.Collection<Document>;
	runtimeGameCollection(collectionName: string, gameId: string): mongodb.Collection<Document>;
	metaGameCollection(collectionName: string, gameId: string): mongodb.Collection<Document>;
	systemGameCollection(collectionName: string, gameId: string): mongodb.Collection<Document>;
	collection(fullCollectionName: string): mongodb.Collection<Document>;
}

declare const database: CloudScriptDatabase;
