///
import type { Abortable as Abortable_2 } from 'events';
import type { Agent } from 'https';
import type { AgentConnectOpts } from 'agent-base';
import { Binary } from 'bson';
import { BSON } from '@mongosh/shell-bson';
import { BSONRegExp } from 'bson';
import { BSONType } from 'bson';
import type { ClientRequest } from 'http';
import type { ConnectionOptions } from 'tls';
import { Decimal128 } from 'bson';
import type { DeserializeOptions } from 'bson';
import { Document as Document_2 } from 'bson';
import { Double } from 'bson';
import type { Duplex } from 'stream';
import { EventEmitter } from 'events';
import type { IncomingMessage } from 'http';
import { Int32 } from 'bson';
import { Long } from 'bson';
import { ObjectId } from 'bson';
import type { ObjectIdLike } from 'bson';
import { Readable } from 'stream';
import type { RequestOptions } from 'https';
import type { SecureContextOptions } from 'tls';
import type { SerializeOptions } from 'bson';
import type { ServerResponse } from 'http';
import { ShellBson } from '@mongosh/shell-bson';
import type { SrvRecord } from 'dns';
import type { TcpNetConnectOpts } from 'net';
import { Timestamp } from 'bson';
import type { TLSSocketOptions } from 'tls';
import { UUID } from 'bson';
/** @public */
declare type Abortable = {
/**
* @experimental
* When provided, the corresponding `AbortController` can be used to abort an asynchronous action.
*
* The `signal.reason` value is used as the error thrown.
*
* @remarks
* **NOTE:** If an abort signal aborts an operation while the driver is writing to the underlying
* socket or reading the response from the server, the socket will be closed.
* If signals are aborted at a high rate during socket read/writes this can lead to a high rate of connection reestablishment.
*
* We plan to mitigate this in a future release, please follow NODE-6062 (`timeoutMS` expiration suffers the same limitation).
*
* AbortSignals are likely a best fit for human interactive interruption (ex. ctrl-C) where the frequency
* of cancellation is reasonably low. If a signal is programmatically aborted for 100s of operations you can empty
* the driver's connection pool.
*
* @example
* ```js
* const controller = new AbortController();
* const { signal } = controller;
* process.on('SIGINT', () => controller.abort(new Error('^C pressed')));
*
* try {
* const res = await fetch('...', { signal });
* await collection.findOne(await res.json(), { signal });
* catch (error) {
* if (error === signal.reason) {
* // signal abort error handling
* }
* }
* ```
*/
signal?: AbortSignal | undefined;
};
/** @public */
declare abstract class AbstractCursor extends TypedEventEmitter implements AsyncDisposable {
/* 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 */
protected signal: AbortSignal | undefined;
private abortListener;
/* 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;
/**
* @experimental
* An alias for {@link AbstractCursor.close|AbstractCursor.close()}.
*/
[Symbol.asyncDispose](): Promise;
/** Adds cursor to client's tracking so it will be closed by MongoClient.close() */
private trackCursor;
/** Returns current buffered documents length */
bufferedCount(): number;
/** Returns current buffered documents */
readBufferedDocuments(number?: number): NonNullable[];
[Symbol.asyncIterator](): AsyncGenerator;
stream(): Readable & AsyncIterable;
hasNext(): Promise;
/** Get the next available document from the cursor, returns null if no more documents are available. */
next(): Promise;
/**
* Try to get the next available document from the cursor or `null` if an empty batch is returned
*/
tryNext(): Promise;
/**
* 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;
/**
* Frees any client-side resources used by the cursor.
*/
close(options?: {
timeoutMS?: number;
}): Promise;
/**
* 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;
/**
* 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 = coll.find();
* const mappedCursor: FindCursor = 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(transform: (doc: TSchema) => T): AbstractCursor;
/**
* 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;
/* 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 */
declare type AbstractCursorEvents = {
[AbstractCursor.CLOSE](): void;
};
/** @public */
declare 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 */
}
declare abstract class AbstractFiniteCursor extends BaseCursor {
_currentIterationResult: CursorIterationResult | null;
constructor(mongo: Mongo, cursor: CursorType, constructionOptionsWithChains?: CursorConstructionOptionsWithChains);
[asPrintable](): Promise;
_it(): Promise;
batchSize(size: number): this;
toArray(): Promise;
maxTimeMS(value: number): this;
objsLeftInBatch(): number;
}
/** @public */
declare type AcceptedFields = { readonly [key in KeysOfAType]?: AssignableType };
/** @public */
declare type AddToSetOperators = {
$each?: Array>;
};
/**
* 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);
* }
* ```
*/
declare 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_2, options?: RunCommandOptions): Promise;
/**
* Retrieve the server build information
*
* @param options - Optional settings for the command
*/
buildInfo(options?: CommandOperationOptions): Promise;
/**
* Retrieve the server build information
*
* @param options - Optional settings for the command
*/
serverInfo(options?: CommandOperationOptions): Promise;
/**
* Retrieve this db's server status.
*
* @param options - Optional settings for the command
*/
serverStatus(options?: CommandOperationOptions): Promise;
/**
* Ping the MongoDB server and retrieve results
*
* @param options - Optional settings for the command
*/
ping(options?: CommandOperationOptions): Promise;
/**
* 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;
/**
* 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;
/**
* List the available databases
*
* @param options - Optional settings for the command
*/
listDatabases(options?: ListDatabasesOptions): Promise;
/**
* Get ReplicaSet status
*
* @param options - Optional settings for the command
*/
replSetGetStatus(options?: CommandOperationOptions): Promise;
}
declare interface Admin_2 {
platform: ReplPlatform;
initialDb: string;
bsonLibrary: BSON;
computeLegacyHexMD5?(str: string): Promise;
listDatabases(database: string, options?: ListDatabasesOptions): Promise;
getNewConnection(uri: string, options: MongoClientOptions): Promise;
getURI(): string | undefined;
getConnectionInfo(): Promise;
authenticate(authDoc: ShellAuthOptions): Promise<{
ok: number;
}>;
createCollection(dbName: string, collName: string, options: CreateCollectionOptions, dbOptions?: DbOptions): Promise<{
ok: number;
}>;
getReadPreference(): ReadPreference;
getReadConcern(): ReadConcern | undefined;
getWriteConcern(): WriteConcern | undefined;
resetConnectionOptions(options: MongoClientOptions): Promise;
startSession(options: ClientSessionOptions): ClientSession;
getRawClient(): any;
createClientEncryption?(options: ClientEncryptionOptions): ClientEncryption;
getFleOptions?: () => AutoEncryptionOptions | undefined;
createEncryptedCollection?(dbName: string, collName: string, options: CreateEncryptedCollectionOptions, libmongocrypt: ClientEncryption): Promise<{
collection: Collection_2;
encryptedFields: Document_2;
}>;
}
declare type AgentWithInitialize = Agent & {
initialize?(): Promise;
logger?: ProxyLogEmitter;
readonly proxyOptions?: Readonly;
createSocket(req: ClientRequest, options: TcpNetConnectOpts | ConnectionOptions, cb: (err: Error | null, s?: Duplex) => void): void;
} & Partial;
/** @public */
declare interface AggregateOptions extends Omit {
/** 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_2;
/**
* 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_2;
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 */
}
declare abstract class AggregateOrFindCursor extends AbstractFiniteCursor {
projection(spec: Document_2): this;
skip(value: number): this;
sort(spec: Document_2): this;
explain(verbosity?: ExplainVerbosityLike): Promise;
}
/**
* 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
*/
declare class AggregationCursor extends ExplainableCursor {
readonly pipeline: Document_2[];
/* Excluded from this release type: aggregateOptions */
/* Excluded from this release type: __constructor */
clone(): AggregationCursor;
/*
Applies the first argument, a function, to each document visited by the cursor and collects the return values from successive application into an array.
*/
map(transform: (doc: TSchema) => T): AggregationCursor;
/* Excluded from this release type: _initialize */
/** Execute the explain for the cursor */
/*
Provides information on the query plan for db.collection.aggregate() method.
*/
explain(): Document_2;
/*
Provides information on the query plan for db.collection.aggregate() method.
*/
explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions): Document_2;
/*
Provides information on the query plan for db.collection.aggregate() method.
*/
explain(options: {
timeoutMS?: number;
}): Document_2;
/*
Provides information on the query plan for db.collection.aggregate() method.
*/
explain(verbosity: ExplainVerbosityLike | ExplainCommandOptions, options: {
timeoutMS?: number;
}): Document_2;
/** 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_2): this;
addStage(stage: Document_2): AggregationCursor;
/** Add a group stage to the aggregation pipeline */
group($group: Document_2): AggregationCursor;
/** Add a limit stage to the aggregation pipeline */
limit($limit: number): this;
/** Add a match stage to the aggregation pipeline */
match($match: Document_2): 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 = 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($project: Document_2): AggregationCursor;
/** Add a lookup stage to the aggregation pipeline */
lookup($lookup: Document_2): this;
/** Add a redact stage to the aggregation pipeline */
redact($redact: Document_2): this;
/** Add a skip stage to the aggregation pipeline */
/*
Call the cursor.skip() method on a cursor to control where MongoDB begins returning results. This approach may be useful in implementing paginated results.
*/
skip($skip: number): this;
/** Add a sort stage to the aggregation pipeline */
/*
Specifies the order in which the query returns matching documents. You must apply sort() to the cursor before retrieving any documents from the database.
*/
sort($sort: Sort): this;
/** Add a unwind stage to the aggregation pipeline */
unwind($unwind: Document_2 | string): this;
/** Add a geoNear stage to the aggregation pipeline */
geoNear($geoNear: Document_2): this;
}
declare class AggregationCursor_2 extends AggregateOrFindCursor {
constructor(mongo: Mongo, cursor: ServiceProviderAggregationCursor, constructionOptionsWithChains?: CursorConstructionOptionsWithChains);
}
declare const ALL_TOPOLOGIES: readonly ["ReplSet", "Standalone", "Sharded", "LoadBalanced"];
/**
* 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
*/
declare type AlternativeType = T extends ReadonlyArray ? T | RegExpOrString : RegExpOrString;
declare type AltNames = string[];
/** @public */
declare type AnyBulkWriteOperation = {
insertOne: InsertOneModel;
} | {
replaceOne: ReplaceOneModel;
} | {
updateOne: UpdateOneModel;
} | {
updateMany: UpdateManyModel;
} | {
deleteOne: DeleteOneModel;
} | {
deleteMany: DeleteManyModel;
};
/**
* Used to represent any of the client bulk write models that can be passed as an array
* to MongoClient#bulkWrite.
* @public
*/
declare type AnyClientBulkWriteModel = ClientInsertOneModel | ClientReplaceOneModel | ClientUpdateOneModel | ClientUpdateManyModel | ClientDeleteOneModel | ClientDeleteManyModel;
declare interface ApiEvent {
method: string;
class: string;
deprecated: boolean;
isAsync: boolean;
callDepth: number;
}
declare interface ApiEventArguments {
pipeline?: any[];
query?: object;
options?: object;
filter?: object;
}
declare interface ApiEventWithArguments {
method: string;
class?: string;
db?: string;
coll?: string;
uri?: string;
arguments?: ApiEventArguments;
}
declare interface ApiWarning {
method: string;
class: string;
message: string;
}
/** @public */
declare type ArrayOperator = {
$each?: Array>;
$slice?: number;
$position?: number;
$sort?: Sort;
};
declare const asPrintable: unique symbol;
/** @public */
declare interface Auth {
/** The username for auth */
username?: string;
/** The password for auth */
password?: string;
}
declare type AuthDoc = {
user: string;
pwd: string;
authDb?: string;
mechanism?: string;
};
/** @public */
declare type AuthFlowType = 'auth-code' | 'device-auth';
/** @public */
declare const AuthMechanism: Readonly<{
readonly MONGODB_AWS: "MONGODB-AWS";
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 */
declare type AuthMechanism = (typeof AuthMechanism)[keyof typeof AuthMechanism];
/** @public */
declare interface AuthMechanismProperties extends Document_2 {
SERVICE_HOST?: string;
SERVICE_NAME?: string;
SERVICE_REALM?: string;
CANONICALIZE_HOST_NAME?: GSSAPICanonicalizationValue;
/* Excluded from this release type: AWS_SESSION_TOKEN */
/** 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;
/**
* A custom AWS credential provider to use. An example using the AWS SDK default provider chain:
*
* ```ts
* const client = new MongoClient(process.env.MONGODB_URI, {
* authMechanismProperties: {
* AWS_CREDENTIAL_PROVIDER: fromNodeProviderChain()
* }
* });
* ```
*
* Using a custom function that returns AWS credentials:
*
* ```ts
* const client = new MongoClient(process.env.MONGODB_URI, {
* authMechanismProperties: {
* AWS_CREDENTIAL_PROVIDER: async () => {
* return {
* accessKeyId: process.env.ACCESS_KEY_ID,
* secretAccessKey: process.env.SECRET_ACCESS_KEY
* }
* }
* }
* });
* ```
*/
AWS_CREDENTIAL_PROVIDER?: AWSCredentialProvider;
}
declare interface AutocompleteParameters {
topology: () => Topologies | undefined;
apiVersionInfo: () => Required | undefined;
connectionInfo: () => ConnectionExtraInfo | undefined;
getCollectionCompletionsForCurrentDb: (collName: string) => Promise;
getDatabaseCompletions: (dbName: string) => Promise;
}
declare interface AutocompletionContext {
currentDatabaseAndConnection(): {
connectionId: string;
databaseName: string;
} | undefined;
databasesForConnection(connectionId: string): Promise;
collectionsForDatabase(connectionId: string, databaseName: string): Promise;
schemaInformationForCollection(connectionId: string, databaseName: string, collectionName: string): Promise;
cacheOptions?: Partial;
}
/** @public */
declare 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 |
*/
declare type AutoEncryptionLoggerLevel = (typeof AutoEncryptionLoggerLevel)[keyof typeof AutoEncryptionLoggerLevel];
/** @public */
declare 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;
/** Configuration options for custom credential providers. */
credentialProviders?: CredentialProviders;
/**
* 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_2;
/** Supply a schema for the encrypted fields in the document */
encryptedFieldsMap?: Document_2;
/** Allows the user to bypass auto encryption, maintaining implicit decryption */
bypassAutoEncryption?: boolean;
/** Allows users to bypass query analysis */
bypassQueryAnalysis?: boolean;
/**
* Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
*/
keyExpirationMS?: number;
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}mongocryptd${'.exe' | ''}`;
/** 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}mongo_crypt_v${number}.${'so' | 'dll' | 'dylib'}`;
/**
* 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 **/
declare type AWSCredentialProvider = () => Promise;
/**
* @public
* Copy of the AwsCredentialIdentityProvider interface from [`smithy/types`](https://socket.dev/npm/package/\@smithy/types/files/1.1.1/dist-types/identity/awsCredentialIdentity.d.ts),
* the return type of the aws-sdk's `fromNodeProviderChain().provider()`.
*/
declare interface AWSCredentials {
accessKeyId: string;
secretAccessKey: string;
sessionToken?: string;
expiration?: Date;
}
/**
* @public
* Configuration options for making an AWS encryption key
*/
declare 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 */
declare 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
*/
declare interface AzureEncryptionKeyOptions {
/**
* Key name
*/
keyName: string;
/**
* Key vault URL, typically `.vault.azure.net`
*/
keyVaultEndpoint: string;
/**
* Key version
*/
keyVersion?: string | undefined;
}
/** @public */
declare 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;
};
declare abstract class BaseCursor extends ShellApiWithMongoClass {
_mongo: Mongo;
_cursor: CursorType;
readonly _constructionOptions?: CursorConstructionOptions;
_chains: CursorChainOptions[];
_transform: ((doc: any) => any) | null;
_blockingWarningDisabled: boolean;
constructor(mongo: Mongo, cursor: CursorType, constructionOptionsWithChains?: CursorConstructionOptionsWithChains);
close(): Promise;
forEach(f: (doc: Document_2) => void | boolean | Promise | Promise): Promise;
hasNext(): Promise;
tryNext(): Promise;
_tryNext(): Promise;
_canDelegateIterationToUnderlyingCursor(): boolean;
[Symbol.asyncIterator](): AsyncGenerator;
isClosed(): boolean;
isExhausted(): boolean;
itcount(): Promise;
pretty(): this;
map(f: (doc: Document_2) => Document_2): this;
next(): Promise;
disableBlockWarnings(): this;
abstract batchSize(size: number): this;
abstract toArray(): Promise;
abstract maxTimeMS(value: number): this;
abstract objsLeftInBatch(): number;
abstract _it(): Promise;
}
declare interface BaseSocks5RequestMetadata {
srcAddr: string;
srcPort: number;
dstAddr: string;
dstPort: number;
}
/**
* Keeps the state of a unordered batch so we can rewrite the results
* correctly after command execution
*
* @public
*/
declare class Batch {
originalZeroIndex: number;
currentIndex: number;
originalIndexes: number[];
batchType: BatchType;
operations: T[];
size: number;
sizeBytes: number;
constructor(batchType: BatchType, originalZeroIndex: number);
}
/** @public */
declare const BatchType: Readonly<{
readonly INSERT: 1;
readonly UPDATE: 2;
readonly DELETE: 3;
}>;
/** @public */
declare type BatchType = (typeof BatchType)[keyof typeof BatchType];
/** @public */
declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray;
/**
* BSON Serialization options.
* @public
*/
declare interface BSONSerializeOptions extends Omit, Omit {
/**
* 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 */
declare type BSONTypeAlias = keyof typeof BSONType;
declare class Bulk extends ShellApiWithMongoClass {
_mongo: Mongo;
_collection: CollectionWithSchema;
_batchCounts: any;
_executed: boolean;
_serviceProviderBulkOp: OrderedBulkOperation | UnorderedBulkOperation;
_ordered: boolean;
constructor(collection: CollectionWithSchema, innerBulk: OrderedBulkOperation | UnorderedBulkOperation, ordered?: boolean);
[asPrintable](): any;
private _emitBulkApiCall;
/*
Executes the bulk operation.
*/
execute(writeConcern?: WriteConcern): BulkWriteResult_2;
/*
Adds a find to the bulk operation.
*/
find(query: MQLQuery): BulkFindOp;
/*
Adds an insert to the bulk operation.
*/
insert(document: MQLDocument): Bulk;
toJSON(): Record<'nInsertOps' | 'nUpdateOps' | 'nRemoveOps' | 'nBatches', number>;
/*
Returns as a string a JSON document that contains the number of operations and batches in the Bulk() object.
*/
toString(): string;
/*
Returns the batches executed by the bulk write.
*/
getOperations(): Pick[];
}
declare class BulkFindOp extends ShellApiWithMongoClass {
_serviceProviderBulkFindOp: FindOperators;
_parentBulk: Bulk;
constructor(innerFind: FindOperators, parentBulk: Bulk);
get _mongo(): Mongo;
[asPrintable](): string;
/*
Adds collation options to the bulk operation.
*/
collation(spec: CollationOptions): BulkFindOp;
/*
Adds an arrayFilter to the bulk operation.
*/
arrayFilters(filters: Document_2[]): BulkFindOp;
/*
Adds an hint to the bulk operation.
*/
hint(hintDoc: Document_2): BulkFindOp;
/*
Adds an delete to the bulk operation.
*/
delete(): Bulk;
/*
Adds an deleteOne to the bulk operation.
*/
deleteOne(): Bulk;
/*
Adds an remove to the bulk operation.
*/
remove(): Bulk;
/*
Adds an removeOne to the bulk operation.
*/
removeOne(): Bulk;
/*
Adds an replaceOne to the bulk operation.
*/
replaceOne(replacement: Document_2): Bulk;
/*
Adds an updateOne to the bulk operation.
*/
updateOne(update: Document_2 | Document_2[]): Bulk;
/*
Adds an update to the bulk operation.
*/
update(update: Document_2 | Document_2[]): Bulk;
/*
Adds an upsert to the bulk operation updates for this find(...).
*/
upsert(): BulkFindOp;
}
/** @public */
declare abstract class BulkOperationBase {
isOrdered: boolean;
/* Excluded from this release type: s */
operationId?: number;
private collection;
/* Excluded from this release type: retryWrites */
/* 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_2): 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_2): 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;
/* Excluded from this release type: handleWriteError */
abstract addToOperationsList(batchType: BatchType, document: Document_2 | UpdateStatement | DeleteStatement): this;
private shouldForceServerObjectId;
}
/** @public */
declare interface BulkWriteOperationError {
index: number;
code: number;
errmsg: string;
errInfo: Document_2;
op: Document_2 | UpdateStatement | DeleteStatement;
}
/** @public */
declare 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_2;
/* Excluded from this release type: timeoutContext */
}
/**
* @public
* The result of a bulk write.
*/
declare 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_2 | undefined;
/** Returns raw internal result */
getRawResponse(): Document_2;
/** Returns true if the bulk operation contains a write error */
hasWriteErrors(): boolean;
/** Returns the number of write errors from 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;
}
declare class BulkWriteResult_2 extends ShellApiValueClass {
acknowledged: boolean;
insertedCount: number;
insertedIds: {
[index: number]: ObjectId;
};
matchedCount: number;
modifiedCount: number;
deletedCount: number;
upsertedCount: number;
upsertedIds: {
[index: number]: ObjectId;
};
constructor(acknowledged: boolean, insertedCount: number, insertedIds: {
[index: number]: ObjectId;
}, matchedCount: number, modifiedCount: number, deletedCount: number, upsertedCount: number, upsertedIds: {
[index: number]: ObjectId;
});
}
declare type CacheOptions = {
databaseCollectionsTTL: number;
collectionSchemaTTL: number;
aggregationSchemaTTL: number;
};
/**
* Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
* @public
*/
declare class ChangeStream> extends TypedEventEmitter> implements AsyncDisposable {
/**
* @experimental
* An alias for {@link ChangeStream.close|ChangeStream.close()}.
*/
[Symbol.asyncDispose](): Promise;
pipeline: Document_2[];
/**
* @remarks WriteConcern can still be present on the options because
* we inherit options from the client/db/collection. The
* key must be present on the options in order to delete it.
* This allows typescript to delete the key but will
* not allow a writeConcern to be assigned as a property on options.
*/
options: ChangeStreamOptions & {
writeConcern?: never;
};
parent: MongoClient | Db | Collection_2;
namespace: MongoDBNamespace;
type: symbol;
/* Excluded from this release type: cursor */
/* Excluded from this release type: cursorStream */
/* Excluded from this release type: isClosed */
/* Excluded from this release type: mode */
/** @event */
static readonly RESPONSE: "response";
/** @event */
static readonly MORE: "more";
/** @event */
static readonly INIT: "init";
/** @event */
static readonly CLOSE: "close";
/**
* Fired for each new matching change in the specified namespace. Attaching a `change`
* event listener to a Change Stream will switch the stream into flowing mode. Data will
* then be passed as soon as it is available.
* @event
*/
static readonly CHANGE: "change";
/** @event */
static readonly END: "end";
/** @event */
static readonly ERROR: "error";
/**
* Emitted each time the change stream stores a new resume token.
* @event
*/
static readonly RESUME_TOKEN_CHANGED: "resumeTokenChanged";
private timeoutContext?;
/**
* Note that this property is here to uniquely identify a ChangeStream instance as the owner of
* the {@link CursorTimeoutContext} instance (see {@link ChangeStream._createChangeStreamCursor}) to ensure
* that {@link AbstractCursor.close} does not mutate the timeoutContext.
*/
private contextOwner;
/* Excluded from this release type: __constructor */
/** The cached resume token that is used to resume after the most recently returned change. */
get resumeToken(): ResumeToken;
/** Check if there is any document still available in the Change Stream */
hasNext(): Promise;
/** Get the next available document from the Change Stream. */
next(): Promise;
/**
* Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned
*/
tryNext(): Promise;
[Symbol.asyncIterator](): AsyncGenerator;
/** Is the cursor closed */
get closed(): boolean;
/**
* Frees the internal resources used by the change stream.
*/
close(): Promise;
/**
* Return a modified Readable stream including a possible transform method.
*
* NOTE: When using a Stream to process change stream events, the stream will
* NOT automatically resume in the case a resumable error is encountered.
*
* @throws MongoChangeStreamError if the underlying cursor or the change stream is closed
*/
stream(): Readable & AsyncIterable;
/* Excluded from this release type: _setIsEmitter */
/* Excluded from this release type: _setIsIterator */
/* Excluded from this release type: _createChangeStreamCursor */
/* Excluded from this release type: _closeEmitterModeWithError */
/* Excluded from this release type: _streamEvents */
/* Excluded from this release type: _endStream */
/* Excluded from this release type: _processChange */
/* Excluded from this release type: _processErrorStreamMode */
/* Excluded from this release type: _processErrorIteratorMode */
private _resume;
}
/**
* Only present when the `showExpandedEvents` flag is enabled.
* @public
* @see https://www.mongodb.com/docs/manual/reference/change-events/modify/#mongodb-data-modify
*/
declare interface ChangeStreamCollModDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** 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
*/
declare interface ChangeStreamCreateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** Describes the type of operation represented in this change notification */
operationType: 'create';
/**
* The type of the newly created object.
*
* @sinceServerVersion 8.1.0
*/
nsType?: 'collection' | 'timeseries' | 'view';
}
/**
* Only present when the `showExpandedEvents` flag is enabled.
* @public
* @see https://www.mongodb.com/docs/manual/reference/change-events/createIndexes/#mongodb-data-createIndexes
*/
declare interface ChangeStreamCreateIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription, ChangeStreamDocumentWallTime {
/** Describes the type of operation represented in this change notification */
operationType: 'createIndexes';
}
declare class ChangeStreamCursor extends BaseCursor {
_currentIterationResult: CursorIterationResult | null;
_on: string;
constructor(cursor: ServiceProviderChangeStream, on: string, mongo: Mongo);
_it(): Promise;
[asPrintable](): Promise;
/*
WARNING: on change streams this method will block unless the cursor is closed. Use tryNext to check if there are any documents in the batch. This is a breaking change
*/
hasNext(): boolean;
/*
If there is a document in the change stream, it will be returned. Otherwise returns null.
*/
tryNext(): Document_2 | null;
/*
This method is deprecated because because after closing a cursor, the remaining documents in the batch are no longer accessible. If you want to see if the cursor is closed use cursor.isClosed. If you want to see if there are documents left in the batch, use cursor.tryNext. This is a breaking change
*/
isExhausted(): never;
/*
WARNING: on change streams this method will block unless the cursor is closed. Use tryNext to get the next document in the batch. This is a breaking change
*/
next(): Document_2;
/*
Returns the ResumeToken of the change stream
*/
getResumeToken(): ResumeToken;
toArray(): never;
/*
Not available on change streams
*/
batchSize(): never;
objsLeftInBatch(): never;
/*
Not available on change streams
*/
maxTimeMS(): never;
}
/**
* @public
* @see https://www.mongodb.com/docs/manual/reference/change-events/#delete-event
*/
declare interface ChangeStreamDeleteDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** 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 */
declare type ChangeStreamDocument = ChangeStreamInsertDocument | ChangeStreamUpdateDocument | ChangeStreamReplaceDocument | ChangeStreamDeleteDocument | ChangeStreamDropDocument | ChangeStreamRenameDocument | ChangeStreamDropDatabaseDocument | ChangeStreamInvalidateDocument | ChangeStreamCreateIndexDocument | ChangeStreamCreateDocument | ChangeStreamCollModDocument | ChangeStreamDropIndexDocument | ChangeStreamShardCollectionDocument | ChangeStreamReshardCollectionDocument | ChangeStreamRefineCollectionShardKeyDocument;
/** @public */
declare 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 */
declare 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 */
declare interface ChangeStreamDocumentKey {
/**
* 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;
[shardKey: string]: any;
};
}
/** @public */
declare interface ChangeStreamDocumentOperationDescription {
/**
* An description of the operation.
*
* Only present when the `showExpandedEvents` flag is enabled.
*
* @sinceServerVersion 6.1.0
*/
operationDescription?: Document_2;
}
/** @public */
declare interface ChangeStreamDocumentWallTime {
/**
* The server date and time of the database operation.
* wallTime differs from clusterTime in that clusterTime is a timestamp taken from the oplog entry associated with the database operation event.
* @sinceServerVersion 6.0.0
*/
wallTime?: Date;
}
/**
* @public
* @see https://www.mongodb.com/docs/manual/reference/change-events/#dropdatabase-event
*/
declare interface ChangeStreamDropDatabaseDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentWallTime {
/** 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
*/
declare interface ChangeStreamDropDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** 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
*/
declare interface ChangeStreamDropIndexDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription, ChangeStreamDocumentWallTime {
/** Describes the type of operation represented in this change notification */
operationType: 'dropIndexes';
}
/** @public */
declare type ChangeStreamEvents> = {
resumeTokenChanged(token: ResumeToken): void;
init(response: any): void;
more(response?: any): void;
response(): void;
end(): void;
error(error: Error): void;
change(change: TChange): void;
/**
* @remarks Note that the `close` event is currently emitted whenever the internal `ChangeStreamCursor`
* instance is closed, which can occur multiple times for a given `ChangeStream` instance.
*
* TODO(NODE-6434): address this issue in NODE-6434
*/
close(): void;
};
/**
* @public
* @see https://www.mongodb.com/docs/manual/reference/change-events/#insert-event
*/
declare interface ChangeStreamInsertDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** 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
*/
declare interface ChangeStreamInvalidateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentWallTime {
/** Describes the type of operation represented in this change notification */
operationType: 'invalidate';
}
/** @public */
declare 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
*/
declare interface ChangeStreamOptions extends Omit {
/**
* 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
*/
declare 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
*/
declare interface ChangeStreamRenameDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** 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
*/
declare interface ChangeStreamReplaceDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentWallTime {
/** 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
*/
declare 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
*/
declare interface ChangeStreamShardCollectionDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentOperationDescription, ChangeStreamDocumentWallTime {
/** Describes the type of operation represented in this change notification */
operationType: 'shardCollection';
}
/** @public */
declare 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
*/
declare interface ChangeStreamUpdateDocument extends ChangeStreamDocumentCommon, ChangeStreamDocumentKey, ChangeStreamDocumentCollectionUUID, ChangeStreamDocumentWallTime {
/** 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;
/** 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;
}
declare interface CheckMetadataConsistencyOptions {
cursor?: {
batchSize: number;
};
checkIndexes?: 1;
}
/**
* A mapping of namespace strings to collections schemas.
* @public
*
* @example
* ```ts
* type MongoDBSchemas = {
* 'db.books': Book;
* 'db.authors': Author;
* }
*
* const model: ClientBulkWriteModel = {
* 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.
*
*/
declare type ClientBulkWriteModel = Record> = { [Namespace in keyof SchemaMap]: AnyClientBulkWriteModel & {
namespace: Namespace;
} }[keyof SchemaMap];
/** @public */
declare 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_2;
/**
* Whether detailed results for each successful operation should be included in the returned
* BulkWriteResult.
*/
verboseResults?: boolean;
}
/** @public */
declare 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;
/**
* The results of each individual update operation that was successfully performed.
*/
readonly updateResults?: ReadonlyMap;
/**
* The results of each individual delete operation that was successfully performed.
*/
readonly deleteResults?: ReadonlyMap;
}
declare class ClientBulkWriteResult_2 extends ShellApiValueClass {
acknowledged: boolean;
insertedCount: number;
matchedCount: number;
modifiedCount: number;
deletedCount: number;
upsertedCount: number;
insertResults?: ReadonlyMap;
updateResults?: ReadonlyMap;
deleteResults?: ReadonlyMap;
constructor({
acknowledged,
insertedCount,
matchedCount,
modifiedCount,
deletedCount,
upsertedCount,
insertResults,
updateResults,
deleteResults
}: {
acknowledged: boolean;
insertedCount: number;
matchedCount: number;
modifiedCount: number;
deletedCount: number;
upsertedCount: number;
insertResults?: ReadonlyMap;
updateResults?: ReadonlyMap;
deleteResults?: ReadonlyMap;
});
}
/** @public */
declare interface ClientDeleteManyModel 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;
/** 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 */
declare interface ClientDeleteOneModel 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;
/** 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 */
declare interface ClientDeleteResult {
/**
* The number of documents that were deleted.
*/
deletedCount: number;
}
declare type ClientDeleteResult_2 = {
deletedCount: number;
};
/**
* @public
* The public interface for explicit in-use encryption
*/
declare 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: _credentialProviders */
/* 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;
/**
* 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, 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;
/**
* 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;
/**
* 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;
/**
* 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 | 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 | 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 | 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.
*/
/*
Creates a new collection with a list of encrypted fields each with unique and auto-created data encryption keys (DEKs). This method should be invoked on a connection instantiated with queryable encryption options.
*/
createEncryptedCollection(db: Db, name: string, options: {
provider: ClientEncryptionDataKeyProvider;
createCollectionOptions: Omit & {
encryptedFields: Document_2;
};
masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions;
}): {
collection: Collection_2;
encryptedFields: Document_2;
};
/**
* 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' });
* }
* ```
*/
/*
Encrypts the value using the specified encryptionKeyId and encryptionAlgorithm. encrypt supports explicit (manual) encryption of field values.
*/
encrypt(value: unknown, options: ClientEncryptionEncryptOptions): 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: [{: {$gt: }}, {: {$lt: }}]}`
* 2. An Aggregate Expression of this form:
* `{$and: [{$gt: [, ]}, {$lt: [, ]}]}`
*
* `$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.
*/
/*
Encrypts an MQL expression using the specified encryptionKeyId and encryptionAlgorithm.
*/
encryptExpression(expression: Document_2, options: ClientEncryptionEncryptOptions): 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);
* }
* ```
*/
/*
decrypts the encryptionValue if the current database connection was configured with access to the Key Management Service (KMS) and key vault used to encrypt encryptionValue.
*/
decrypt(value: Binary): T;
/* Excluded from this release type: askForKMSCredentials */
static get libmongocryptVersion(): string;
/* Excluded from this release type: _encrypt */
}
declare class ClientEncryption_2 extends ShellApiWithMongoClass {
_mongo: Mongo;
_libmongocrypt: ClientEncryption;
constructor(mongo: Mongo);
[asPrintable](): string;
encrypt(keyId: Binary, value: any, algorithmOrEncryptionOptions: ClientEncryptionEncryptOptions['algorithm'] | ClientEncryptionEncryptOptions): Promise;
decrypt(encryptedValue: Binary): Promise;
encryptExpression(keyId: Binary, value: Document_2, options: ClientEncryptionEncryptOptions): Promise;
createEncryptedCollection(dbName: string, collName: string, options: CreateEncryptedCollectionOptions): Promise<{
collection: CollectionWithSchema;
encryptedFields: Document_2;
}>;
}
/**
* @public
* Options to provide when creating a new data key.
*/
declare 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:`, `gcp:`, `local:`, `kmip:`, `azure:`
* where `name` is an alphanumeric string, underscores allowed.
*/
declare type ClientEncryptionDataKeyProvider = keyof KMSProviders;
/**
* @public
* Options to provide when encrypting data.
*/
declare 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' | 'TextPreview';
/**
* 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' | 'prefixPreview' | 'suffixPreview' | 'substringPreview';
/** The index options for a Queryable Encryption field supporting "range" queries.*/
rangeOptions?: RangeOptions;
/**
* Options for a Queryable Encryption field supporting text queries. Only valid when `algorithm` is `TextPreview`.
*
* @experimental Public Technical Preview: `textPreview` is an experimental feature and may break at any time.
*/
textOptions?: TextQueryOptions;
}
/**
* @public
* Additional settings to provide when creating a new `ClientEncryption` instance.
*/
declare 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 user provided custom credential providers.
*/
credentialProviders?: CredentialProviders;
/**
* Options for specifying a Socks5 proxy to use for connecting to the KMS.
*/
proxyOptions?: ProxyOptions;
/**
* TLS options for kms providers to use.
*/
tlsOptions?: CSFLEKMSTlsOptions;
/**
* Sets the expiration time for the DEK in the cache in milliseconds. Defaults to 60000. 0 means no timeout.
*/
keyExpirationMS?: number;
/**
* @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: '' } }
* });
*
* // `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('', { timeoutMS: 2_000 });
*
* // timeoutMS is set to 1_000 on clientEncryption
* const clientEncryption = new ClientEncryption(client, {
* timeoutMS: 1_000
* kmsProviders: { local: { key: '' } }
* });
* ```
*/
timeoutMS?: number;
}
/**
* @public
* @experimental
*/
declare interface ClientEncryptionRewrapManyDataKeyProviderOptions {
provider: ClientEncryptionDataKeyProvider;
masterKey?: AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions | KMIPEncryptionKeyOptions | undefined;
}
/**
* @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.
*/
declare type ClientEncryptionTlsOptions = Pick;
/** @public */
declare interface ClientInsertOneModel extends ClientWriteModel {
name: 'insertOne';
/** The document to insert. */
document: OptionalId;
}
/** @public */
declare interface ClientInsertOneResult {
/**
* The _id of the inserted document.
*/
insertedId: any;
}
declare type ClientInsertResult = {
insertedId: any;
};
/** @public */
declare interface ClientReplaceOneModel 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;
/** The document with which to replace the matched document. */
replacement: WithoutId;
/** 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;
/** Specifies the sort order for the documents matched by the filter. */
sort?: Sort;
}
/**
* A class representing a client session on the server
*
* NOTE: not meant to be instantiated directly.
* @public
*/
declare class ClientSession extends TypedEventEmitter implements AsyncDisposable {
/* 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;
/* Excluded from this release type: transaction */
/* Excluded from this release type: commitAttempted */
readonly snapshotEnabled: boolean;
/* Excluded from this release type: _serverSession */
/* Excluded from this release type: snapshotTime */
/* Excluded from this release type: pinnedConnection */
/* Excluded from this release type: txnNumberIncrement */
/**
* @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;
get loadBalanced(): boolean;
/* 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;
/**
* @experimental
* An alias for {@link ClientSession.endSession|ClientSession.endSession()}.
*/
[Symbol.asyncDispose](): Promise;
/**
* 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;
/**
* Aborts the currently active transaction in this session.
*
* @param options - Optional options, can be used to override `defaultTimeoutMS`.
*/
abortTransaction(options?: {
timeoutMS?: number;
}): Promise;
/* 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(fn: WithTransactionCallback, 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;
}
/** @public */
declare type ClientSessionEvents = {
ended(session: ClientSession): void;
};
/** @public */
declare 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 */
}
declare interface ClientSideFieldLevelEncryptionOptions {
keyVaultClient?: Mongo;
keyVaultNamespace: string;
kmsProviders: KMSProviders;
schemaMap?: Document_2;
bypassAutoEncryption?: boolean;
explicitEncryptionOnly?: boolean;
tlsOptions?: { [k in keyof KMSProviders]?: ClientEncryptionTlsOptions };
encryptedFieldsMap?: Document_2;
bypassQueryAnalysis?: boolean;
}
/** @public */
declare interface ClientUpdateManyModel 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;
/**
* The modifications to apply. The value can be either:
* UpdateFilter - A document that contains update operator expressions,
* Document[] - an aggregation pipeline.
*/
update: UpdateFilter | Document_2[];
/** A set of filters specifying to which array elements an update should apply. */
arrayFilters?: Document_2[];
/** 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 */
declare interface ClientUpdateOneModel 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;
/**
* The modifications to apply. The value can be either:
* UpdateFilter - A document that contains update operator expressions,
* Document[] - an aggregation pipeline.
*/
update: UpdateFilter | Document_2[];
/** A set of filters specifying to which array elements an update should apply. */
arrayFilters?: Document_2[];
/** 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;
/** Specifies the sort order for the documents matched by the filter. */
sort?: Sort;
}
/** @public */
declare 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;
}
declare type ClientUpdateResult_2 = {
matchedCount: number;
modifiedCount: number;
upsertedId?: any;
didUpsert: boolean;
};
/** @public */
declare interface ClientWriteModel {
/**
* The namespace for the write.
*
* A namespace is a combination of the database name and the name of the collection: `.`.
* All documents belong to a namespace.
*
* @see https://www.mongodb.com/docs/manual/reference/limits/#std-label-faq-dev-namespace
*/
namespace: string;
}
declare interface Closable {
close(): Promise;
suspend(): Promise<() => Promise>;
}
/** @public
* Configuration options for clustered collections
* @see https://www.mongodb.com/docs/manual/core/clustered-collections/
*/
declare interface ClusteredCollectionOptions extends Document_2 {
name?: string;
key: Document_2;
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.
*/
declare interface ClusterTime {
clusterTime: Timestamp;
/** Used to validate the identity of a request or response's ClusterTime. */
signature?: {
hash: Binary;
keyId: Long;
};
}
/** @public */
declare interface CollationOptions {
locale: string;
caseLevel?: boolean;
caseFirst?: string;
strength?: number;
numericOrdering?: boolean;
alternate?: string;
maxVariable?: string;
backwards?: boolean;
normalization?: boolean;
}
declare class Collection = StringKey> extends ShellApiWithMongoClass {
_mongo: Mongo;
_database: DatabaseWithSchema;
_name: N;
_cachedSampleDocs: Document_2[];
constructor(mongo: Mongo, database: DatabaseWithSchema | Database, name: N);
[namespaceInfo](): Namespace;
[asPrintable](): string;
private _emitCollectionApiCall;
/*
Calculates aggregate values for the data in a collection or a view.
*/
aggregate(pipeline: MQLPipeline, options: AggregateOptions & {
explain: ExplainVerbosityLike;
} & Abortable_2): Document_2;
/*
Calculates aggregate values for the data in a collection or a view.
*/
aggregate(pipeline: MQLPipeline, options?: AggregateOptions & Abortable_2): AggregationCursor_2;
/*
Calculates aggregate values for the data in a collection or a view.
*/
aggregate(...stages: MQLPipeline): AggregationCursor_2;
/*
Performs multiple write operations with controls for order of execution.
*/
bulkWrite(operations: AnyBulkWriteOperation[], options?: BulkWriteOptions): BulkWriteResult_2;
/*
Returns the count of documents that would match a find() query for the collection or view.
*/
count(query?: {}, options?: CountOptions): number;
/*
Returns the count of documents that match the query for a collection or view.
*/
countDocuments(query?: MQLQuery, options?: CountDocumentsOptions & Abortable_2): number;
/*
Removes all documents that match the filter from a collection.
*/
deleteMany(filter: Document_2, options?: DeleteOptions): DeleteResult_2 | Document_2;
/*
Removes a single document from a collection.
*/
deleteOne(filter: Document_2, options?: DeleteOptions): DeleteResult_2 | Document_2;
/*
Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
*/
distinct(field: string): Document_2;
/*
Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
*/
distinct(field: string, query: MQLQuery): Document_2;
/*
Finds the distinct values for a specified field across a single collection or view and returns the results in an array.
*/
distinct(field: string, query: MQLQuery, options: DistinctOptions): Document_2;
/*
Returns the count of all documents in a collection or view.
*/
estimatedDocumentCount(options?: EstimatedDocumentCountOptions): number;
/*
Selects documents in a collection or view.
*/
find(query?: MQLQuery, projection?: Document_2, options?: FindOptions & {
explain?: ExplainVerbosityLike;
} & Abortable_2): Cursor;
/*
Modifies and returns a single document.
*/
findAndModify(options: FindAndModifyMethodShellOptions): Document_2 | null;
/*
Selects documents in a collection or view.
*/
findOne(query?: MQLQuery, projection?: Document_2, options?: FindOptions & Abortable_2): MQLDocument | null;
/*
Renames a collection.
*/
renameCollection(newName: string, dropTarget?: boolean): Document_2;
/*
Deletes a single document based on the filter and sort criteria, returning the deleted document.
*/
findOneAndDelete(filter: Document_2, options?: FindOneAndDeleteOptions): Document_2 | null;
/*
Modifies and replaces a single document based on the filter and sort criteria.
*/
findOneAndReplace(filter: Document_2, replacement: Document_2, options?: FindAndModifyShellOptions): Document_2;
/*
Updates a single document based on the filter and sort criteria.
*/
findOneAndUpdate(filter: Document_2, update: Document_2 | Document_2[], options?: FindAndModifyShellOptions): Document_2;
/*
Inserts a document or documents into a collection.
*/
insert(docs: MQLDocument | MQLDocument[], options?: BulkWriteOptions): InsertManyResult_2;
/*
Inserts multiple documents into a collection.
*/
insertMany(docs: MQLDocument[], options?: BulkWriteOptions): InsertManyResult_2;
/*
Inserts a document into a collection.
*/
insertOne(doc: MQLDocument, options?: InsertOneOptions): InsertOneResult_2;
/*
Checks if a collection is capped
*/
isCapped(): boolean;
/*
Removes documents from a collection.
*/
remove(query: MQLQuery, options?: boolean | RemoveShellOptions): DeleteResult_2 | Document_2;
/*
Replaces a single document within the collection based on the filter.
*/
replaceOne(filter: Document_2, replacement: Document_2, options?: ReplaceOptions): UpdateResult_2;
/*
Modifies an existing document or documents in a collection.
*/
update(filter: Document_2, update: Document_2, options?: UpdateOptions & {
multi?: boolean;
}): UpdateResult_2 | Document_2;
/*
Updates all documents that match the specified filter for a collection.
*/
updateMany(filter: Document_2, update: Document_2, options?: UpdateOptions): UpdateResult_2 | Document_2;
/*
Updates a single document within the collection based on the filter.
*/
updateOne(filter: Document_2, update: Document_2, options?: UpdateOptions & {
sort?: Document_2;
}): UpdateResult_2 | Document_2;
/*
Compacts structured encryption data
*/
compactStructuredEncryptionData(): Document_2;
/*
calls {convertToCapped:'coll', size:maxBytes}} command
*/
convertToCapped(size: number): Document_2;
_createIndexes(keyPatterns: Document_2[], options?: CreateIndexesOptions, commitQuorum?: number | string): Promise;
/*
Creates one or more indexes on a collection
*/
createIndexes(keyPatterns: Document_2[], options?: CreateIndexesOptions, commitQuorum?: number | string): string[];
/*
Creates one index on a collection
*/
createIndex(keys: Document_2, options?: CreateIndexesOptions, commitQuorum?: number | string): string;
/*
Creates one index on a collection
*/
ensureIndex(keys: Document_2, options?: CreateIndexesOptions, commitQuorum?: number | string): Document_2;
/*
Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
*/
getIndexes(): Document_2[];
/*
Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
*/
getIndexSpecs(): Document_2[];
/*
Alias for getIndexes. Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.
*/
getIndices(): Document_2[];
/*
Return an array of key patterns for indexes defined on collection
*/
getIndexKeys(): Document_2[];
/*
Drops the specified index or indexes (except the index on the _id field) from a collection.
*/
dropIndexes(indexes?: string | string[] | Document_2 | Document_2[]): Document_2;
/*
Drops or removes the specified index from a collection.
*/
dropIndex(index: string | Document_2): Document_2;
_getSingleStorageStatValue(key: string): Promise;
/*
Reports the total size used by the indexes on a collection.
*/
totalIndexSize(...args: any[]): number;
/*
Rebuilds all existing indexes on a collection.
*/
reIndex(): Document_2;
/*
Get current database.
*/
getDB(): DatabaseWithSchema;
/*
Returns the Mongo object.
*/
getMongo(): Mongo;
/*
This method provides a wrapper around the size output of the collStats (i.e. db.collection.stats()) command.
*/
dataSize(): number;
/*
The total amount of storage allocated to this collection for document storage.
*/
storageSize(): number;
/*
The total size in bytes of the data in the collection plus the size of every index on the collection.
*/
totalSize(): number;
/*
Removes a collection or view from the database.
*/
drop(options?: DropCollectionOptions): boolean;
/*
Returns collection infos if the collection exists or null otherwise.
*/
exists(): Document_2;
/*
Returns the name of the collection prefixed with the database name.
*/
getFullName(): string;
/*
Returns the name of the collection.
*/
getName(): N;
/*
Runs a db command with the given name where the first param is the collection name.
*/
runCommand(commandName: string | Document_2, options?: RunCommandOptions): Document_2;
/*
Returns information on the query plan.
*/
explain(verbosity?: ExplainVerbosityLike): Explainable;
_getLegacyCollStats(scale: number): Promise;
_aggregateAndScaleCollStats(collStats: Document_2[], scale: number): Promise;
_getAggregatedCollStats(scale: number): Promise;
/*
Returns statistics about the collection.
*/
stats(originalOptions?: Document_2 | number): Document_2;
/*
returns the $latencyStats aggregation for the collection. Takes an options document with an optional boolean 'histograms' field.
*/
latencyStats(options?: Document_2): Document_2[];
/*
Initializes an ordered bulk command. Returns an instance of Bulk
*/
initializeOrderedBulkOp(): Bulk;
/*
Initializes an unordered bulk command. Returns an instance of Bulk
*/
initializeUnorderedBulkOp(): Bulk;
/*
Returns an interface to access the query plan cache for a collection. The interface provides methods to view and clear the query plan cache.
*/
getPlanCache(): PlanCache;
/*
Calls the mapReduce command
*/
mapReduce(map: Function | string, reduce: Function | string, optionsOrOutString: MapReduceShellOptions): Document_2;
/*
Calls the validate command. Default full value is false
*/
validate(options?: boolean | Document_2): Document_2;
/*
Calls the getShardVersion command
*/
getShardVersion(): Document_2;
_getShardedCollectionInfo(config: DatabaseWithSchema, collStats: Document_2[]): Promise;
/*
Prints the data distribution statistics for a sharded collection.
*/
getShardDistribution(): CommandResult;
/*
Returns a document containing the shards where this collection is located as well as whether the collection itself is sharded.
*/
getShardLocation(): {
shards: string[];
sharded: boolean;
};
/*
Opens a change stream cursor on the collection
*/
watch(pipeline?: MQLPipeline | ChangeStreamOptions, options?: ChangeStreamOptions): ChangeStreamCursor;
/*
Hides an existing index from the query planner.
*/
hideIndex(index: string | Document_2): Document_2;
/*
Unhides an existing index from the query planner.
*/
unhideIndex(index: string | Document_2): Document_2;
/*
Returns metrics for evaluating a shard key. That is, ‘key’ can be a candidate shard key for an unsharded or sharded collection, or the current shard key for a sharded collection.
*/
analyzeShardKey(key: Document_2, options?: Document_2): Document_2;
/*
Starts or stops collecting metrics about reads and writes against an unsharded or sharded collection.
*/
configureQueryAnalyzer(options: Document_2): Document_2;
/*
Returns a cursor with information about metadata inconsistencies
*/
checkMetadataConsistency(options?: CheckMetadataConsistencyOptions): RunCommandCursor_2;
/*
Returns an array that holds a list of documents that identify and describe the existing search indexes on the collection.
*/
getSearchIndexes(indexName?: string | Document_2, options?: Document_2): Document_2[];
/*
Creates one search indexes on a collection
*/
createSearchIndex(name: string, definition: SearchIndexDefinition): string;
/*
Creates one search indexes on a collection
*/
createSearchIndex(name: string, type: 'search' | 'vectorSearch', definition: SearchIndexDefinition): string;
/*
Creates one search indexes on a collection
*/
createSearchIndex(definition: SearchIndexDefinition, type?: 'search' | 'vectorSearch'): string;
/*
Creates one search indexes on a collection
*/
createSearchIndex(description: SearchIndexDescription): string;
/*
Creates one or more search indexes on a collection
*/
createSearchIndexes(specs: SearchIndexDescription[]): string[];
/*
Drops or removes the specified search index from a collection.
*/
dropSearchIndex(indexName: string): void;
/*
Updates the sepecified search index.
*/
updateSearchIndex(indexName: string, definition: Document_2): void;
_getSampleDocs(): Promise;
_getSampleDocsForCompletion(): Promise;
}
/**
* 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('pets');
*
* const petCursor = pets.find();
*
* for await (const pet of petCursor) {
* console.log(`${pet.name} is a ${pet.kind}!`);
* }
* ```
*/
declare class Collection_2 {
/* Excluded from this release type: s */
/* Excluded from this release type: client */
/**
* Get the database object for the collection.
*/
readonly db: Db;
/* 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, options?: InsertOneOptions): Promise>;
/**
* 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>, options?: BulkWriteOptions): Promise>;
/**
* 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>, options?: BulkWriteOptions): Promise;
/**
* Update a single document in a collection
*
* The value of `update` can be either:
* - UpdateFilter - 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, update: UpdateFilter | Document_2[], options?: UpdateOptions & {
sort?: Sort;
}): Promise>;
/**
* 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, replacement: WithoutId, options?: ReplaceOptions): Promise>;
/**
* Update multiple documents in a collection
*
* The value of `update` can be either:
* - UpdateFilter - 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, update: UpdateFilter | Document_2[], options?: UpdateOptions): Promise>;
/**
* 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, options?: DeleteOptions): Promise;
/**
* 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