///
import { Binary } from 'bson';
import { BSONRegExp } from 'bson';
import { BSONSymbol } from 'bson';
import { Code } from 'bson';
import type { ConnectionOptions as ConnectionOptions_2 } from 'tls';
import { DBRef } from 'bson';
import { Decimal128 } from 'bson';
import Denque = require('denque');
import type { deserialize as deserialize_2 } from 'bson';
import type { DeserializeOptions } from 'bson';
import * as dns from 'dns';
import { Document } from 'bson';
import { Double } from 'bson';
import { Duplex } from 'stream';
import { DuplexOptions } from 'stream';
import { EventEmitter } from 'events';
import { Int32 } from 'bson';
import { Long } from 'bson';
import { Map as Map_2 } from 'bson';
import { MaxKey } from 'bson';
import { MinKey } from 'bson';
import { ObjectId } from 'bson';
import type { ObjectIdLike } from 'bson';
import { Readable } from 'stream';
import type { serialize as serialize_2 } from 'bson';
import type { SerializeOptions } from 'bson';
import type { Socket } from 'net';
import type { SrvRecord } from 'dns';
import type { TcpNetConnectOpts } from 'net';
import { Timestamp } from 'bson';
import type { TLSSocket } from 'tls';
import type { TLSSocketOptions } from 'tls';
import { Writable } from 'stream';
/** @public */
export declare abstract class AbstractCursor extends TypedEventEmitter {
/* Excluded from this release type: [kId] */
/* Excluded from this release type: [kSession] */
/* Excluded from this release type: [kServer] */
/* Excluded from this release type: [kNamespace] */
/* Excluded from this release type: [kDocuments] */
/* Excluded from this release type: [kTopology] */
/* Excluded from this release type: [kTransform] */
/* Excluded from this release type: [kInitialized] */
/* Excluded from this release type: [kClosed] */
/* Excluded from this release type: [kKilled] */
/* Excluded from this release type: [kOptions] */
/** @event */
static readonly CLOSE: "close";
/* Excluded from this release type: __constructor */
get id(): Long | undefined;
/* Excluded from this release type: topology */
/* 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 */
/* Excluded from this release type: cursorOptions */
get closed(): boolean;
get killed(): boolean;
get loadBalanced(): boolean;
/** Returns current buffered documents length */
bufferedCount(): number;
/** Returns current buffered documents */
readBufferedDocuments(number?: number): TSchema[];
[Symbol.asyncIterator](): AsyncIterator;
stream(options?: CursorStreamOptions): Readable;
hasNext(): Promise;
hasNext(callback: Callback): void;
/** Get the next available document from the cursor, returns null if no more documents are available. */
next(): Promise;
next(callback: Callback): void;
next(callback?: Callback): Promise | void;
/**
* Try to get the next available document from the cursor or `null` if an empty batch is returned
*/
tryNext(): Promise;
tryNext(callback: Callback): void;
/**
* Iterates over all the documents for this cursor using the iterator, callback pattern.
*
* @param iterator - The iteration callback.
* @param callback - The end callback.
*/
forEach(iterator: (doc: TSchema) => boolean | void): Promise;
forEach(iterator: (doc: TSchema) => boolean | void, callback: Callback): void;
close(): void;
close(callback: Callback): void;
/**
* @deprecated options argument is deprecated
*/
close(options: CursorCloseOptions): Promise;
/**
* @deprecated options argument is deprecated
*/
close(options: CursorCloseOptions, callback: Callback): void;
/**
* Returns an array of documents. The caller is responsible for making sure that there
* is enough memory to store the results. Note that the array only contains partial
* results when this cursor had been previously accessed. In that case,
* cursor.rewind() can be used to reset the cursor.
*
* @param callback - The result callback.
*/
toArray(): Promise;
toArray(callback: Callback): void;
/**
* 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 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://docs.mongodb.com/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 */
}
/** @public */
export declare type AbstractCursorEvents = {
[AbstractCursor.CLOSE](): void;
};
/** @public */
export declare interface AbstractCursorOptions extends BSONSerializeOptions {
session?: ClientSession;
readPreference?: ReadPreferenceLike;
readConcern?: ReadConcernLike;
batchSize?: number;
maxTimeMS?: number;
comment?: Document | string;
tailable?: boolean;
awaitData?: boolean;
noCursorTimeout?: boolean;
}
/* Excluded from this release type: AbstractOperation */
/** @public */
export declare type AcceptedFields = {
readonly [key in KeysOfAType]?: AssignableType;
};
/** @public */
export declare type AddToSetOperators = {
$each?: Array>;
};
/** @public */
export declare interface AddUserOptions extends CommandOperationOptions {
/** @deprecated Please use db.command('createUser', ...) instead for this option */
digestPassword?: null;
/** Roles associated with the created user */
roles?: string | string[] | RoleSpecification | RoleSpecification[];
/** Custom data associated with the user (only Mongodb 2.6 or higher) */
customData?: Document;
}
/**
* 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
* ```js
* const MongoClient = require('mongodb').MongoClient;
* const test = require('assert');
* // Connection url
* const url = 'mongodb://localhost:27017';
* // Database Name
* const dbName = 'test';
*
* // Connect using MongoClient
* MongoClient.connect(url, function(err, client) {
* // Use the admin database for the operation
* const adminDb = client.db(dbName).admin();
*
* // List all the available databases
* adminDb.listDatabases(function(err, dbs) {
* expect(err).to.not.exist;
* test.ok(dbs.databases.length > 0);
* client.close();
* });
* });
* ```
*/
export declare class Admin {
/* Excluded from this release type: s */
/* Excluded from this release type: __constructor */
/**
* Execute a command
*
* @param command - The command to execute
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
command(command: Document): Promise;
command(command: Document, callback: Callback): void;
command(command: Document, options: RunCommandOptions): Promise;
command(command: Document, options: RunCommandOptions, callback: Callback): void;
/**
* Retrieve the server build information
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
buildInfo(): Promise;
buildInfo(callback: Callback): void;
buildInfo(options: CommandOperationOptions): Promise;
buildInfo(options: CommandOperationOptions, callback: Callback): void;
/**
* Retrieve the server build information
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
serverInfo(): Promise;
serverInfo(callback: Callback): void;
serverInfo(options: CommandOperationOptions): Promise;
serverInfo(options: CommandOperationOptions, callback: Callback): void;
/**
* Retrieve this db's server status.
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
serverStatus(): Promise;
serverStatus(callback: Callback): void;
serverStatus(options: CommandOperationOptions): Promise;
serverStatus(options: CommandOperationOptions, callback: Callback): void;
/**
* Ping the MongoDB server and retrieve results
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
ping(): Promise;
ping(callback: Callback): void;
ping(options: CommandOperationOptions): Promise;
ping(options: CommandOperationOptions, callback: Callback): void;
/**
* Add a user to the database
*
* @param username - The username for the new user
* @param password - An optional password for the new user
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
addUser(username: string): Promise;
addUser(username: string, callback: Callback): void;
addUser(username: string, password: string): Promise;
addUser(username: string, password: string, callback: Callback): void;
addUser(username: string, options: AddUserOptions): Promise;
addUser(username: string, options: AddUserOptions, callback: Callback): void;
addUser(username: string, password: string, options: AddUserOptions): Promise;
addUser(username: string, password: string, options: AddUserOptions, callback: Callback): void;
/**
* Remove a user from a database
*
* @param username - The username to remove
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
removeUser(username: string): Promise;
removeUser(username: string, callback: Callback): void;
removeUser(username: string, options: RemoveUserOptions): Promise;
removeUser(username: string, options: RemoveUserOptions, callback: Callback): void;
/**
* Validate an existing collection
*
* @param collectionName - The name of the collection to validate.
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
validateCollection(collectionName: string): Promise;
validateCollection(collectionName: string, callback: Callback): void;
validateCollection(collectionName: string, options: ValidateCollectionOptions): Promise;
validateCollection(collectionName: string, options: ValidateCollectionOptions, callback: Callback): void;
/**
* List the available databases
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
listDatabases(): Promise;
listDatabases(callback: Callback): void;
listDatabases(options: ListDatabasesOptions): Promise;
listDatabases(options: ListDatabasesOptions, callback: Callback): void;
/**
* Get ReplicaSet status
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
replSetGetStatus(): Promise;
replSetGetStatus(callback: Callback): void;
replSetGetStatus(options: CommandOperationOptions): Promise;
replSetGetStatus(options: CommandOperationOptions, callback: Callback): void;
}
/* Excluded from this release type: AdminPrivate */
/* Excluded from this release type: AggregateOperation */
/** @public */
export declare interface AggregateOptions extends CommandOperationOptions {
/** 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://docs.mongodb.com/manual/reference/command/aggregate). */
batchSize?: number;
/** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
bypassDocumentValidation?: boolean;
/** Return the query as cursor, on 2.6 \> it returns as a real cursor on pre 2.6 it returns as an emulated cursor. */
cursor?: Document;
/** specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. */
maxTimeMS?: number;
/** The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. */
maxAwaitTimeMS?: number;
/** Specify collation. */
collation?: CollationOptions;
/** Add an index selection hint to an aggregation command */
hint?: Hint;
/** Map of parameter names and values that can be accessed using $$var (requires MongoDB 5.0). */
let?: Document;
out?: string;
}
/**
* 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
*/
export declare class AggregationCursor extends AbstractCursor {
/* Excluded from this release type: [kPipeline] */
/* Excluded from this release type: [kOptions] */
/* Excluded from this release type: __constructor */
get pipeline(): Document[];
clone(): AggregationCursor;
map(transform: (doc: TSchema) => T): AggregationCursor;
/* Excluded from this release type: _initialize */
/** Execute the explain for the cursor */
explain(): Promise;
explain(callback: Callback): void;
explain(verbosity: ExplainVerbosityLike): Promise;
/** Add a group stage to the aggregation pipeline */
group($group: Document): AggregationCursor;
/** Add a limit stage to the aggregation pipeline */
limit($limit: number): this;
/** Add a match stage to the aggregation pipeline */
match($match: Document): this;
/** Add an out stage to the aggregation pipeline */
out($out: {
db: string;
coll: string;
} | string): this;
/**
* Add a project stage to the aggregation pipeline
*
* @remarks
* In order to strictly type this function you must provide an interface
* that represents the effect of your projection on the result documents.
*
* By default chaining a projection to your cursor changes the returned type to the generic {@link Document} type.
* You should specify a parameterized type to have assertions on your final results.
*
* @example
* ```typescript
* // Best way
* const docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });
* // Flexible way
* const docs: AggregationCursor = 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): AggregationCursor;
/** Add a lookup stage to the aggregation pipeline */
lookup($lookup: Document): this;
/** Add a redact stage to the aggregation pipeline */
redact($redact: Document): this;
/** Add a skip stage to the aggregation pipeline */
skip($skip: number): this;
/** Add a sort stage to the aggregation pipeline */
sort($sort: Sort): this;
/** Add a unwind stage to the aggregation pipeline */
unwind($unwind: Document | string): this;
/** @deprecated Add a geoNear stage to the aggregation pipeline */
geoNear($geoNear: Document): this;
}
/** @public */
export declare interface AggregationCursorOptions extends AbstractCursorOptions, AggregateOptions {
}
/**
* It is possible to search using alternative types in mongodb e.g.
* string types can be searched using a regex in mongo
* array types can be searched using their element type
* @public
*/
export declare type AlternativeType = T extends ReadonlyArray ? T | RegExpOrString : RegExpOrString;
/** @public */
export declare type AnyBulkWriteOperation = {
insertOne: InsertOneModel;
} | {
replaceOne: ReplaceOneModel;
} | {
updateOne: UpdateOneModel;
} | {
updateMany: UpdateManyModel;
} | {
deleteOne: DeleteOneModel;
} | {
deleteMany: DeleteManyModel;
};
/** @public */
export declare type AnyError = MongoError | Error;
/** @public */
export declare type ArrayOperator = {
$each?: Array>;
$slice?: number;
$position?: number;
$sort?: Sort;
};
/** @public */
export declare interface Auth {
/** The username for auth */
username?: string;
/** The password for auth */
password?: string;
}
/** @public */
export declare const AuthMechanism: Readonly<{
readonly MONGODB_AWS: "MONGODB-AWS";
readonly MONGODB_CR: "MONGODB-CR";
readonly MONGODB_DEFAULT: "DEFAULT";
readonly MONGODB_GSSAPI: "GSSAPI";
readonly MONGODB_PLAIN: "PLAIN";
readonly MONGODB_SCRAM_SHA1: "SCRAM-SHA-1";
readonly MONGODB_SCRAM_SHA256: "SCRAM-SHA-256";
readonly MONGODB_X509: "MONGODB-X509";
}>;
/** @public */
export declare type AuthMechanism = typeof AuthMechanism[keyof typeof AuthMechanism];
/** @public */
export declare interface AuthMechanismProperties extends Document {
SERVICE_NAME?: string;
SERVICE_REALM?: string;
CANONICALIZE_HOST_NAME?: boolean;
AWS_SESSION_TOKEN?: string;
}
/** @public */
export declare interface AutoEncrypter {
new (client: MongoClient, options: AutoEncryptionOptions): AutoEncrypter;
init(cb: Callback): void;
teardown(force: boolean, callback: Callback): void;
encrypt(ns: string, cmd: Document, options: any, callback: Callback): void;
decrypt(cmd: Document, options: any, callback: Callback): void;
}
/** @public */
export declare const AutoEncryptionLoggerLevel: Readonly<{
readonly FatalError: 0;
readonly Error: 1;
readonly Warning: 2;
readonly Info: 3;
readonly Trace: 4;
}>;
/** @public */
export declare type AutoEncryptionLoggerLevel = typeof AutoEncryptionLoggerLevel[keyof typeof AutoEncryptionLoggerLevel];
/** @public */
export declare interface AutoEncryptionOptions {
/* Excluded from this release type: bson */
/* 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?: {
/** Configuration options for using 'aws' as your KMS provider */
aws?: {
/** 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;
};
/** Configuration options for using 'local' as your KMS provider */
local?: {
/**
* The master key used to encrypt/decrypt data keys.
* A 96-byte long Buffer or base64 encoded string.
*/
key: Buffer | string;
};
/** Configuration options for using 'azure' as your KMS provider */
azure?: {
/** 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;
};
/** Configuration options for using 'gcp' as your KMS provider */
gcp?: {
/** The service account email to authenticate */
email: string;
/** A PKCS#8 encrypted key. This can either be a base64 string or a binary representation */
privateKey: string | Buffer;
/**
* If present, a host with optional port. E.g. "example.com" or "example.com:443".
* Defaults to "oauth2.googleapis.com"
*/
endpoint?: string | undefined;
};
};
/**
* 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 encryption.
* Other validation rules in the JSON schema will not be enforced by the driver and will result in an error.
*/
schemaMap?: Document;
/** Allows the user to bypass auto encryption, maintaining implicit decryption */
bypassAutoEncryption?: boolean;
options?: {
/** An optional hook to catch logging messages from the underlying encryption engine */
logger?: (level: AutoEncryptionLoggerLevel, message: string) => void;
};
extraOptions?: {
/**
* A local process the driver communicates with to determine how to encrypt values in a command.
* Defaults to "mongodb://%2Fvar%2Fmongocryptd.sock" if domain sockets are available or "mongodb://localhost:27020" otherwise
*/
mongocryptdURI?: string;
/** If true, autoEncryption will not attempt to spawn a mongocryptd before connecting */
mongocryptdBypassSpawn?: boolean;
/** The path to the mongocryptd executable on the system */
mongocryptdSpawnPath?: string;
/** Command line arguments to use when auto-spawning a mongocryptd */
mongocryptdSpawnArgs?: string[];
};
proxyOptions?: ProxyOptions;
}
/**
* Keeps the state of a unordered batch so we can rewrite the results
* correctly after command execution
*
* @public
*/
export declare class Batch {
originalZeroIndex: number;
currentIndex: number;
originalIndexes: number[];
batchType: BatchType;
operations: T[];
size: number;
sizeBytes: number;
constructor(batchType: BatchType, originalZeroIndex: number);
}
/** @public */
export declare const BatchType: Readonly<{
readonly INSERT: 1;
readonly UPDATE: 2;
readonly DELETE: 3;
}>;
/** @public */
export declare type BatchType = typeof BatchType[keyof typeof BatchType];
export { Binary }
/** @public */
export declare type BitwiseFilter = number /** numeric bit mask */ | Binary /** BinData bit mask */ | ReadonlyArray;
export { BSONRegExp }
/**
* BSON Serialization options.
* @public
*/
export declare interface BSONSerializeOptions extends Omit, Omit {
/** Return BSON filled buffers from operations */
raw?: boolean;
/** Enable utf8 validation when deserializing BSON documents. Defaults to true. */
enableUtf8Validation?: boolean;
}
export { BSONSymbol }
/** @public */
export declare const BSONType: Readonly<{
readonly double: 1;
readonly string: 2;
readonly object: 3;
readonly array: 4;
readonly binData: 5;
readonly undefined: 6;
readonly objectId: 7;
readonly bool: 8;
readonly date: 9;
readonly null: 10;
readonly regex: 11;
readonly dbPointer: 12;
readonly javascript: 13;
readonly symbol: 14;
readonly javascriptWithScope: 15;
readonly int: 16;
readonly timestamp: 17;
readonly long: 18;
readonly decimal: 19;
readonly minKey: -1;
readonly maxKey: 127;
}>;
/** @public */
export declare type BSONType = typeof BSONType[keyof typeof BSONType];
/** @public */
export declare type BSONTypeAlias = keyof typeof BSONType;
/* Excluded from this release type: BufferPool */
/** @public */
export declare abstract class BulkOperationBase {
isOrdered: boolean;
/* Excluded from this release type: s */
operationId?: number;
/* Excluded from this release type: __constructor */
/**
* Add a single insert document to the bulk operation
*
* @example
* ```js
* const bulkOp = collection.initializeOrderedBulkOp();
*
* // Adds three inserts to the bulkOp.
* bulkOp
* .insert({ a: 1 })
* .insert({ b: 2 })
* .insert({ c: 3 });
* await bulkOp.execute();
* ```
*/
insert(document: Document): BulkOperationBase;
/**
* Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne.
* Returns a builder object used to complete the definition of the operation.
*
* @example
* ```js
* const bulkOp = collection.initializeOrderedBulkOp();
*
* // Add an updateOne to the bulkOp
* bulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });
*
* // Add an updateMany to the bulkOp
* bulkOp.find({ c: 3 }).update({ $set: { d: 4 } });
*
* // Add an upsert
* bulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });
*
* // Add a deletion
* bulkOp.find({ g: 7 }).deleteOne();
*
* // Add a multi deletion
* bulkOp.find({ h: 8 }).delete();
*
* // Add a replaceOne
* bulkOp.find({ i: 9 }).replaceOne({writeConcern: { j: 10 }});
*
* // Update using a pipeline (requires Mongodb 4.2 or higher)
* bulk.find({ k: 11, y: { $exists: true }, z: { $exists: true } }).updateOne([
* { $set: { total: { $sum: [ '$y', '$z' ] } } }
* ]);
*
* // All of the ops will now be executed
* await bulkOp.execute();
* ```
*/
find(selector: Document): FindOperators;
/** Specifies a raw operation to perform in the bulk write. */
raw(op: AnyBulkWriteOperation): this;
get bsonOptions(): BSONSerializeOptions;
get writeConcern(): WriteConcern | undefined;
get batches(): Batch[];
execute(options?: BulkWriteOptions): Promise;
execute(callback: Callback): void;
execute(options: BulkWriteOptions | undefined, callback: Callback): void;
execute(options?: BulkWriteOptions | Callback, callback?: Callback): Promise | void;
/* Excluded from this release type: handleWriteError */
abstract addToOperationsList(batchType: BatchType, document: Document | UpdateStatement | DeleteStatement): this;
}
/* Excluded from this release type: BulkOperationPrivate */
/** @public */
export declare interface BulkResult {
ok: number;
writeErrors: WriteError[];
writeConcernErrors: WriteConcernError[];
insertedIds: Document[];
nInserted: number;
nUpserted: number;
nMatched: number;
nModified: number;
nRemoved: number;
upserted: Document[];
opTime?: Document;
}
/** @public */
export declare interface BulkWriteOperationError {
index: number;
code: number;
errmsg: string;
errInfo: Document;
op: Document | UpdateStatement | DeleteStatement;
}
/** @public */
export declare interface BulkWriteOptions extends CommandOperationOptions {
/** Allow driver to bypass schema validation in MongoDB 3.2 or higher. */
bypassDocumentValidation?: boolean;
/** If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. */
ordered?: boolean;
/** @deprecated use `ordered` instead */
keepGoing?: boolean;
/** Force server to assign _id values instead of driver. */
forceServerObjectId?: boolean;
}
/**
* @public
* The result of a bulk write.
*/
export declare class BulkWriteResult {
result: BulkResult;
/* Excluded from this release type: __constructor */
/** Number of documents inserted. */
get insertedCount(): number;
/** Number of documents matched for update. */
get matchedCount(): number;
/** Number of documents modified. */
get modifiedCount(): number;
/** Number of documents deleted. */
get deletedCount(): number;
/** Number of documents upserted. */
get upsertedCount(): number;
/** Upserted document generated Id's, hash key is the index of the originating operation */
get upsertedIds(): {
[key: number]: any;
};
/** Inserted document generated Id's, hash key is the index of the originating operation */
get insertedIds(): {
[key: number]: any;
};
/** Evaluates to true if the bulk operation correctly executes */
get ok(): number;
/** The number of inserted documents */
get nInserted(): number;
/** Number of upserted documents */
get nUpserted(): number;
/** Number of matched documents */
get nMatched(): number;
/** Number of documents updated physically on disk */
get nModified(): number;
/** Number of removed documents */
get nRemoved(): number;
/** Returns an array of all inserted ids */
getInsertedIds(): Document[];
/** Returns an array of all upserted ids */
getUpsertedIds(): Document[];
/** Returns the upserted id at the given index */
getUpsertedIdAt(index: number): Document | undefined;
/** Returns raw internal result */
getRawResponse(): Document;
/** Returns true if the bulk operation contains a write error */
hasWriteErrors(): boolean;
/** Returns the number of write errors off the bulk operation */
getWriteErrorCount(): number;
/** Returns a specific write error object */
getWriteErrorAt(index: number): WriteError | undefined;
/** Retrieve all write errors */
getWriteErrors(): WriteError[];
/** Retrieve lastOp if available */
getLastOp(): Document | undefined;
/** Retrieve the write concern error if one exists */
getWriteConcernError(): WriteConcernError | undefined;
toJSON(): BulkResult;
toString(): string;
isOk(): boolean;
}
/**
* MongoDB Driver style callback
* @public
*/
export declare type Callback = (error?: AnyError, result?: T) => void;
/** @public */
export declare class CancellationToken extends TypedEventEmitter<{
cancel(): void;
}> {
}
/**
* Creates a new Change Stream instance. Normally created using {@link Collection#watch|Collection.watch()}.
* @public
*/
export declare class ChangeStream extends TypedEventEmitter> {
pipeline: Document[];
options: ChangeStreamOptions;
parent: MongoClient | Db | Collection;
namespace: MongoDBNamespace;
type: symbol;
/* Excluded from this release type: cursor */
streamOptions?: CursorStreamOptions;
/* Excluded from this release type: [kResumeQueue] */
/* Excluded from this release type: [kCursorStream] */
/* Excluded from this release type: [kClosed] */
/* Excluded from this release type: [kMode] */
/** @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";
/* Excluded from this release type: __constructor */
/* Excluded from this release type: cursorStream */
/** 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;
hasNext(callback: Callback): void;
/** Get the next available document from the Change Stream. */
next(): Promise>;
next(callback: Callback>): void;
/** Is the cursor closed */
get closed(): boolean;
/** Close the Change Stream */
close(callback?: Callback): Promise | void;
/**
* Return a modified Readable stream including a possible transform method.
* @throws MongoDriverError if this.cursor is undefined
*/
stream(options?: CursorStreamOptions): Readable;
/**
* Try to get the next available document from the Change Stream's cursor or `null` if an empty batch is returned
*/
tryNext(): Promise;
tryNext(callback: Callback): void;
}
/* Excluded from this release type: ChangeStreamCursor */
/* Excluded from this release type: ChangeStreamCursorOptions */
/** @public */
export declare interface ChangeStreamDocument {
/**
* The id functions as an opaque token for use when resuming an interrupted
* change stream.
*/
_id: InferIdType;
/**
* Describes the type of operation represented in this change notification.
*/
operationType: 'insert' | 'update' | 'replace' | 'delete' | 'invalidate' | 'drop' | 'dropDatabase' | 'rename';
/**
* Contains two fields: “db” and “coll” containing the database and
* collection name in which the change happened.
*/
ns: {
db: string;
coll: string;
};
/**
* Only present for ops of type ‘insert’, ‘update’, ‘replace’, and
* ‘delete’.
*
* For unsharded collections this contains a single field, _id, with the
* value of the _id of the document updated. For sharded collections,
* this will contain all the components of the shard key in order,
* followed by the _id if the _id isn’t part of the shard key.
*/
documentKey?: InferIdType;
/**
* Only present for ops of type ‘update’.
*
* Contains a description of updated and removed fields in this
* operation.
*/
updateDescription?: UpdateDescription;
/**
* Always present for operations of type ‘insert’ and ‘replace’. Also
* present for operations of type ‘update’ if the user has specified ‘updateLookup’
* in the ‘fullDocument’ arguments to the ‘$changeStream’ stage.
*
* For operations of type ‘insert’ and ‘replace’, this key will contain the
* document being inserted, or the new version of the document that is replacing
* the existing document, respectively.
*
* For operations of type ‘update’, this key will contain a copy of the full
* version of the document from some point after the update occurred. If the
* document was deleted since the updated happened, it will be null.
*/
fullDocument?: TSchema;
}
/** @public */
export declare type ChangeStreamEvents = {
resumeTokenChanged(token: ResumeToken): void;
init(response: TSchema): void;
more(response?: TSchema | undefined): void;
response(): void;
end(): void;
error(error: Error): void;
change(change: ChangeStreamDocument): void;
} & AbstractCursorEvents;
/**
* 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
*/
export declare interface ChangeStreamOptions extends AggregateOptions {
/** Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream 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. */
fullDocument?: 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 {@link https://docs.mongodb.com/manual/changeStreams/#resumeafter-for-change-streams|ChangeStream documentation}. */
resumeAfter?: ResumeToken;
/** Similar to resumeAfter, but will allow you to start after an invalidated event. See {@link https://docs.mongodb.com/manual/changeStreams/#startafter-for-change-streams|ChangeStream documentation}. */
startAfter?: ResumeToken;
/** Will start the changeStream after the specified operationTime. */
startAtOperationTime?: OperationTime;
/** The number of documents to return per batch. See {@link https://docs.mongodb.com/manual/reference/command/aggregate|aggregation documentation}. */
batchSize?: number;
}
/** @public */
export declare interface ClientMetadata {
driver: {
name: string;
version: string;
};
os: {
type: string;
name: NodeJS.Platform;
architecture: string;
version: string;
};
platform: string;
version?: string;
application?: {
name: string;
};
}
/** @public */
export declare interface ClientMetadataOptions {
driverInfo?: {
name?: string;
version?: string;
platform?: string;
};
appName?: string;
}
/**
* A class representing a client session on the server
*
* NOTE: not meant to be instantiated directly.
* @public
*/
export declare class ClientSession extends TypedEventEmitter {
/* Excluded from this release type: topology */
/* Excluded from this release type: sessionPool */
hasEnded: boolean;
clientOptions?: MongoOptions;
supports: {
causalConsistency: boolean;
};
clusterTime?: ClusterTime;
operationTime?: Timestamp;
explicit: boolean;
/* Excluded from this release type: owner */
defaultTransactionOptions: TransactionOptions;
transaction: Transaction;
/* Excluded from this release type: [kServerSession] */
/* Excluded from this release type: [kSnapshotTime] */
/* Excluded from this release type: [kSnapshotEnabled] */
/* Excluded from this release type: [kPinnedConnection] */
/* Excluded from this release type: __constructor */
/** The server id associated with this session */
get id(): ServerSessionId | undefined;
get serverSession(): ServerSession;
/** Whether or not this session is configured for snapshot reads */
get snapshotEnabled(): boolean;
get loadBalanced(): boolean;
/* Excluded from this release type: pinnedConnection */
/* Excluded from this release type: pin */
/* Excluded from this release type: unpin */
get isPinned(): boolean;
/**
* Ends this session on the server
*
* @param options - Optional settings. Currently reserved for future use
* @param callback - Optional callback for completion of this operation
*/
endSession(): Promise;
endSession(callback: Callback): void;
endSession(options: EndSessionOptions): Promise;
endSession(options: EndSessionOptions, callback: Callback): void;
/**
* 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 */
incrementTransactionNumber(): void;
/** @returns whether this session is currently in a transaction or not */
inTransaction(): boolean;
/**
* Starts a new transaction with the given options.
*
* @param options - Options for the transaction
*/
startTransaction(options?: TransactionOptions): void;
/**
* Commits the currently active transaction in this session.
*
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
commitTransaction(): Promise;
commitTransaction(callback: Callback): void;
/**
* Aborts the currently active transaction in this session.
*
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
abortTransaction(): Promise;
abortTransaction(callback: Callback): void;
/**
* This is here to ensure that ClientSession is never serialized to BSON.
*/
toBSON(): never;
/**
* Runs a provided lambda within a transaction, retrying either the commit operation
* or entire transaction as needed (and when the error permits) to better ensure that
* the transaction can complete successfully.
*
* IMPORTANT: This method requires the user to return a Promise, all lambdas that do not
* return a Promise will result in undefined behavior.
*
* @param fn - A lambda to run within a transaction
* @param options - Optional settings for the transaction
*/
withTransaction(fn: WithTransactionCallback, options?: TransactionOptions): ReturnType;
}
/** @public */
export declare type ClientSessionEvents = {
ended(session: ClientSession): void;
};
/** @public */
export 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;
/* Excluded from this release type: owner */
/* Excluded from this release type: explicit */
/* Excluded from this release type: initialClusterTime */
}
/** @public */
export declare interface CloseOptions {
force?: boolean;
}
/** @public */
export declare interface ClusterTime {
clusterTime: Timestamp;
signature: {
hash: Binary;
keyId: Long;
};
}
export { Code }
/** @public */
export declare interface CollationOptions {
locale: string;
caseLevel?: boolean;
caseFirst?: string;
strength?: number;
numericOrdering?: boolean;
alternate?: string;
maxVariable?: string;
backwards?: boolean;
normalization?: boolean;
}
/**
* The **Collection** class is an internal class that embodies a MongoDB collection
* allowing for insert/update/remove/find and other command operation on that MongoDB collection.
*
* **COLLECTION Cannot directly be instantiated**
* @public
*
* @example
* ```js
* const MongoClient = require('mongodb').MongoClient;
* const test = require('assert');
* // Connection url
* const url = 'mongodb://localhost:27017';
* // Database Name
* const dbName = 'test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, client) {
* // Create a collection we want to drop later
* const col = client.db(dbName).collection('createIndexExample1');
* // Show that duplicate records got dropped
* col.find({}).toArray(function(err, items) {
* expect(err).to.not.exist;
* test.equal(4, items.length);
* client.close();
* });
* });
* ```
*/
export declare class Collection {
/* Excluded from this release type: s */
/* 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;
/**
* 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);
/**
* 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
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
insertOne(doc: OptionalUnlessRequiredId): Promise>;
insertOne(doc: OptionalUnlessRequiredId, callback: Callback>): void;
insertOne(doc: OptionalUnlessRequiredId, options: InsertOneOptions): Promise>;
insertOne(doc: OptionalUnlessRequiredId, options: InsertOneOptions, callback: Callback>): void;
/**
* 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
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
insertMany(docs: OptionalUnlessRequiredId[]): Promise>;
insertMany(docs: OptionalUnlessRequiredId[], callback: Callback>): void;
insertMany(docs: OptionalUnlessRequiredId[], options: BulkWriteOptions): Promise>;
insertMany(docs: OptionalUnlessRequiredId[], options: BulkWriteOptions, callback: Callback>): void;
/**
* Perform a bulkWrite operation without a fluent API
*
* Legal operation types are
*
* ```js
* { insertOne: { document: { a: 1 } } }
*
* { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
*
* { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
*
* { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} }
*
* { deleteOne: { filter: {c:1} } }
*
* { deleteMany: { filter: {c:1} } }
*
* { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} }
*```
* Please note that raw operations are no longer accepted as of driver version 4.0.
*
* 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
* @param callback - An optional callback, a Promise will be returned if none is provided
* @throws MongoDriverError if operations is not an array
*/
bulkWrite(operations: AnyBulkWriteOperation[]): Promise;
bulkWrite(operations: AnyBulkWriteOperation[], callback: Callback): void;
bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions): Promise;
bulkWrite(operations: AnyBulkWriteOperation[], options: BulkWriteOptions, callback: Callback): void;
/**
* Update a single document in a collection
*
* @param filter - The filter used to select the document to update
* @param update - The update operations to be applied to the document
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
updateOne(filter: Filter, update: UpdateFilter | Partial): Promise;
updateOne(filter: Filter, update: UpdateFilter | Partial, callback: Callback): void;
updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions): Promise;
updateOne(filter: Filter, update: UpdateFilter | Partial, options: UpdateOptions, callback: Callback): void;
/**
* 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
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
replaceOne(filter: Filter, replacement: WithoutId): Promise;
replaceOne(filter: Filter, replacement: WithoutId, callback: Callback): void;
replaceOne(filter: Filter, replacement: WithoutId, options: ReplaceOptions): Promise;
replaceOne(filter: Filter, replacement: WithoutId, options: ReplaceOptions, callback: Callback): void;
/**
* Update multiple documents in a collection
*
* @param filter - The filter used to select the documents to update
* @param update - The update operations to be applied to the documents
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
updateMany(filter: Filter, update: UpdateFilter): Promise;
updateMany(filter: Filter, update: UpdateFilter, callback: Callback): void;
updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions): Promise;
updateMany(filter: Filter, update: UpdateFilter, options: UpdateOptions, callback: Callback): void;
/**
* Delete a document from a collection
*
* @param filter - The filter used to select the document to remove
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
deleteOne(filter: Filter): Promise;
deleteOne(filter: Filter, callback: Callback): void;
deleteOne(filter: Filter, options: DeleteOptions): Promise;
deleteOne(filter: Filter, options: DeleteOptions, callback?: Callback): void;
/**
* Delete multiple documents from a collection
*
* @param filter - The filter used to select the documents to remove
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
deleteMany(filter: Filter): Promise;
deleteMany(filter: Filter, callback: Callback): void;
deleteMany(filter: Filter, options: DeleteOptions): Promise;
deleteMany(filter: Filter, options: DeleteOptions, callback: Callback): void;
/**
* Rename the collection.
*
* @remarks
* This operation does not inherit options from the Db or MongoClient.
*
* @param newName - New name of of the collection.
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
rename(newName: string): Promise;
rename(newName: string, callback: Callback): void;
rename(newName: string, options: RenameOptions): Promise;
rename(newName: string, options: RenameOptions, callback: Callback): void;
/**
* Drop the collection from the database, removing it permanently. New accesses will create a new collection.
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
drop(): Promise;
drop(callback: Callback): void;
drop(options: DropCollectionOptions): Promise;
drop(options: DropCollectionOptions, callback: Callback): void;
/**
* Fetches the first document that matches the filter
*
* @param filter - Query for find Operation
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
findOne(): Promise | null>;
findOne(callback: Callback | null>): void;
findOne(filter: Filter): Promise | null>;
findOne(filter: Filter, callback: Callback | null>): void;
findOne(filter: Filter, options: FindOptions): Promise | null>;
findOne(filter: Filter, options: FindOptions, callback: Callback | null>): void;
findOne(): Promise;
findOne(callback: Callback): void;
findOne(filter: Filter): Promise;
findOne(filter: Filter, options?: FindOptions): Promise;
findOne(filter: Filter, options?: FindOptions, callback?: Callback): void;
/**
* Creates a cursor for a filter that can be used to iterate over results from MongoDB
*
* @param filter - The filter predicate. If unspecified, then all documents in the collection will match the predicate
*/
find(): FindCursor>;
find(filter: Filter, options?: FindOptions): FindCursor>;
find(filter: Filter, options?: FindOptions): FindCursor;
/**
* Returns the options of the collection.
*
* @param options - Optional settings for the command
* @param callback - An optional callback, a Promise will be returned if none is provided
*/
options(): Promise;
options(callback: Callback): void;
options(options: OperationOptions): Promise