mongodb
- Version 6.8.1
- Published
- 3.04 MB
- 3 dependencies
- Apache-2.0 license
Install
npm i mongodb
yarn add mongodb
pnpm add mongodb
Overview
The official MongoDB driver for Node.js
Index
Variables
- AuthMechanism
- AutoEncryptionLoggerLevel
- BatchType
- Compressor
- CURSOR_FLAGS
- ExplainVerbosity
- GSSAPICanonicalizationValue
- LEGAL_TCP_SOCKET_OPTIONS
- LEGAL_TLS_SOCKET_OPTIONS
- MONGO_CLIENT_EVENTS
- MongoErrorLabel
- ProfilingLevel
- ReadConcernLevel
- ReadPreferenceMode
- ReturnDocument
- ServerApiVersion
- ServerMonitoringMode
- ServerType
- TopologyType
Classes
ClientSession
- abortTransaction()
- advanceClusterTime()
- advanceOperationTime()
- clientOptions
- clusterTime
- commitTransaction()
- defaultTransactionOptions
- endSession()
- equals()
- explicit
- hasEnded
- id
- incrementTransactionNumber()
- inTransaction()
- isPinned
- loadBalanced
- operationTime
- serverSession
- snapshotEnabled
- startTransaction()
- supports
- toBSON()
- transaction
- withTransaction()
Collection
- aggregate()
- bsonOptions
- bulkWrite()
- collectionName
- count()
- countDocuments()
- createIndex()
- createIndexes()
- createSearchIndex()
- createSearchIndexes()
- dbName
- deleteMany()
- deleteOne()
- distinct()
- drop()
- dropIndex()
- dropIndexes()
- dropSearchIndex()
- estimatedDocumentCount()
- find()
- findOne()
- findOneAndDelete()
- findOneAndReplace()
- findOneAndUpdate()
- hint
- indexes()
- indexExists()
- indexInformation()
- initializeOrderedBulkOp()
- initializeUnorderedBulkOp()
- insertMany()
- insertOne()
- isCapped()
- listIndexes()
- listSearchIndexes()
- namespace
- options()
- readConcern
- readPreference
- rename()
- replaceOne()
- updateMany()
- updateOne()
- updateSearchIndex()
- watch()
- writeConcern
Db
- admin()
- aggregate()
- bsonOptions
- collection()
- collections()
- command()
- createCollection()
- createIndex()
- databaseName
- dropCollection()
- dropDatabase()
- indexInformation()
- listCollections()
- namespace
- options
- profilingLevel()
- readConcern
- readPreference
- removeUser()
- renameCollection()
- runCursorCommand()
- secondaryOk
- setProfilingLevel()
- stats()
- SYSTEM_COMMAND_COLLECTION
- SYSTEM_INDEX_COLLECTION
- SYSTEM_JS_COLLECTION
- SYSTEM_NAMESPACE_COLLECTION
- SYSTEM_PROFILE_COLLECTION
- SYSTEM_USER_COLLECTION
- watch()
- writeConcern
Interfaces
MongoClientOptions
- appName
- auth
- authMechanism
- authMechanismProperties
- authSource
- autoEncryption
- compressors
- connectTimeoutMS
- directConnection
- driverInfo
- forceServerObjectId
- heartbeatFrequencyMS
- journal
- loadBalanced
- localThresholdMS
- maxConnecting
- maxIdleTimeMS
- maxPoolSize
- maxStalenessSeconds
- minHeartbeatFrequencyMS
- minPoolSize
- monitorCommands
- noDelay
- pkFactory
- proxyHost
- proxyPassword
- proxyPort
- proxyUsername
- readConcern
- readConcernLevel
- readPreference
- readPreferenceTags
- replicaSet
- retryReads
- retryWrites
- serverApi
- serverMonitoringMode
- serverSelectionTimeoutMS
- socketTimeoutMS
- srvMaxHosts
- srvServiceName
- ssl
- tls
- tlsAllowInvalidCertificates
- tlsAllowInvalidHostnames
- tlsCAFile
- tlsCertificateKeyFile
- tlsCertificateKeyFilePassword
- tlsCRLFile
- tlsInsecure
- w
- waitQueueTimeoutMS
- writeConcern
- wtimeoutMS
- zlibCompressionLevel
Type Aliases
- AbstractCursorEvents
- AcceptedFields
- AddToSetOperators
- AlternativeType
- AnyBulkWriteOperation
- AnyError
- ArrayElement
- ArrayOperator
- AuthMechanism
- AutoEncryptionExtraOptions
- AutoEncryptionLoggerLevel
- AzureKMSProviderConfiguration
- BatchType
- BitwiseFilter
- BSONTypeAlias
- Callback
- ChangeStreamDocument
- ChangeStreamEvents
- ClientEncryptionDataKeyProvider
- ClientEncryptionTlsOptions
- ClientSessionEvents
- CommonEvents
- Compressor
- CompressorName
- Condition
- ConnectionEvents
- ConnectionPoolEvents
- CSFLEKMSTlsOptions
- CursorFlag
- DistinctOptions
- DropDatabaseOptions
- DropIndexesOptions
- EnhancedOmit
- EventEmitterWithState
- EventsDescription
- ExplainVerbosity
- ExplainVerbosityLike
- Filter
- FilterOperations
- Flatten
- GCPKMSProviderConfiguration
- GenericListener
- GridFSBucketEvents
- GSSAPICanonicalizationValue
- Hint
- IndexDescriptionCompact
- IndexDescriptionInfo
- IndexDirection
- IndexSpecification
- InferIdType
- IntegerType
- IsAny
- Join
- KeysOfAType
- KeysOfOtherType
- ListIndexesOptions
- ListSearchIndexesOptions
- MatchKeysAndValues
- MongoClientEvents
- MongoErrorLabel
- MonitorEvents
- NestedPaths
- NestedPathsOfType
- NonObjectIdLikeDocument
- NotAcceptedFields
- NumericType
- OIDCCallbackFunction
- OneOrMore
- OnlyFieldsOfType
- OperationTime
- OptionalId
- OptionalUnlessRequiredId
- ProfilingLevel
- ProfilingLevelOptions
- PropertyType
- PullAllOperator
- PullOperator
- PushOperator
- ReadConcernLevel
- ReadConcernLike
- ReadPreferenceLike
- ReadPreferenceMode
- RegExpOrString
- RemoveUserOptions
- ResumeToken
- ReturnDocument
- RunCommandOptions
- RunCursorCommandOptions
- SchemaMember
- ServerApiVersion
- ServerEvents
- ServerMonitoringMode
- ServerSessionId
- ServerType
- SetFields
- SetProfilingLevelOptions
- Sort
- SortDirection
- Stream
- StrictFilter
- StrictMatchKeysAndValues
- StrictUpdateFilter
- SupportedNodeConnectionOptions
- SupportedSocketOptions
- SupportedTLSConnectionOptions
- SupportedTLSSocketOptions
- TagSet
- TopologyEvents
- TopologyType
- UpdateFilter
- W
- WithId
- WithoutId
- WithSessionCallback
- WithTransactionCallback
Variables
variable AuthMechanism
const AuthMechanism: Readonly<{ readonly MONGODB_AWS: 'MONGODB-AWS'; readonly MONGODB_CR: 'MONGODB-CR'; readonly MONGODB_DEFAULT: 'DEFAULT'; readonly MONGODB_GSSAPI: 'GSSAPI'; readonly MONGODB_PLAIN: 'PLAIN'; readonly MONGODB_SCRAM_SHA1: 'SCRAM-SHA-1'; readonly MONGODB_SCRAM_SHA256: 'SCRAM-SHA-256'; readonly MONGODB_X509: 'MONGODB-X509'; readonly MONGODB_OIDC: 'MONGODB-OIDC';}>;
Modifiers
@public
variable AutoEncryptionLoggerLevel
const AutoEncryptionLoggerLevel: Readonly<{ readonly FatalError: 0; readonly Error: 1; readonly Warning: 2; readonly Info: 3; readonly Trace: 4;}>;
Modifiers
@public
variable BatchType
const BatchType: Readonly<{ readonly INSERT: 1; readonly UPDATE: 2; readonly DELETE: 3;}>;
Modifiers
@public
variable Compressor
const Compressor: Readonly<{ readonly none: 0; readonly snappy: 1; readonly zlib: 2; readonly zstd: 3;}>;
Modifiers
@public
variable CURSOR_FLAGS
const CURSOR_FLAGS: readonly [ 'tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];
Modifiers
@public
variable ExplainVerbosity
const ExplainVerbosity: Readonly<{ readonly queryPlanner: 'queryPlanner'; readonly queryPlannerExtended: 'queryPlannerExtended'; readonly executionStats: 'executionStats'; readonly allPlansExecution: 'allPlansExecution';}>;
Modifiers
@public
variable GSSAPICanonicalizationValue
const GSSAPICanonicalizationValue: Readonly<{ readonly on: true; readonly off: false; readonly none: 'none'; readonly forward: 'forward'; readonly forwardAndReverse: 'forwardAndReverse';}>;
Modifiers
@public
variable LEGAL_TCP_SOCKET_OPTIONS
const LEGAL_TCP_SOCKET_OPTIONS: readonly [ 'family', 'hints', 'localAddress', 'localPort', 'lookup'];
Modifiers
@public
variable LEGAL_TLS_SOCKET_OPTIONS
const LEGAL_TLS_SOCKET_OPTIONS: readonly [ 'ALPNProtocols', 'ca', 'cert', 'checkServerIdentity', 'ciphers', 'crl', 'ecdhCurve', 'key', 'minDHSize', 'passphrase', 'pfx', 'rejectUnauthorized', 'secureContext', 'secureProtocol', 'servername', 'session'];
Modifiers
@public
variable MONGO_CLIENT_EVENTS
const MONGO_CLIENT_EVENTS: readonly [ 'connectionPoolCreated', 'connectionPoolReady', 'connectionPoolCleared', 'connectionPoolClosed', 'connectionCreated', 'connectionReady', 'connectionClosed', 'connectionCheckOutStarted', 'connectionCheckOutFailed', 'connectionCheckedOut', 'connectionCheckedIn', 'commandStarted', 'commandSucceeded', 'commandFailed', 'serverOpening', 'serverClosed', 'serverDescriptionChanged', 'topologyOpening', 'topologyClosed', 'topologyDescriptionChanged', 'error', 'timeout', 'close', 'serverHeartbeatStarted', 'serverHeartbeatSucceeded', 'serverHeartbeatFailed'];
Modifiers
@public
variable MongoErrorLabel
const MongoErrorLabel: Readonly<{ readonly RetryableWriteError: 'RetryableWriteError'; readonly TransientTransactionError: 'TransientTransactionError'; readonly UnknownTransactionCommitResult: 'UnknownTransactionCommitResult'; readonly ResumableChangeStreamError: 'ResumableChangeStreamError'; readonly HandshakeError: 'HandshakeError'; readonly ResetPool: 'ResetPool'; readonly PoolRequstedRetry: 'PoolRequstedRetry'; readonly InterruptInUseConnections: 'InterruptInUseConnections'; readonly NoWritesPerformed: 'NoWritesPerformed';}>;
Modifiers
@public
variable ProfilingLevel
const ProfilingLevel: Readonly<{ readonly off: 'off'; readonly slowOnly: 'slow_only'; readonly all: 'all';}>;
Modifiers
@public
variable ReadConcernLevel
const ReadConcernLevel: Readonly<{ readonly local: 'local'; readonly majority: 'majority'; readonly linearizable: 'linearizable'; readonly available: 'available'; readonly snapshot: 'snapshot';}>;
Modifiers
@public
variable ReadPreferenceMode
const ReadPreferenceMode: Readonly<{ readonly primary: 'primary'; readonly primaryPreferred: 'primaryPreferred'; readonly secondary: 'secondary'; readonly secondaryPreferred: 'secondaryPreferred'; readonly nearest: 'nearest';}>;
Modifiers
@public
variable ReturnDocument
const ReturnDocument: Readonly<{ readonly BEFORE: 'before'; readonly AFTER: 'after';}>;
Modifiers
@public
variable ServerApiVersion
const ServerApiVersion: Readonly<{ readonly v1: '1' }>;
Modifiers
@public
variable ServerMonitoringMode
const ServerMonitoringMode: Readonly<{ readonly auto: 'auto'; readonly poll: 'poll'; readonly stream: 'stream';}>;
Modifiers
@public
variable ServerType
const ServerType: Readonly<{ readonly Standalone: 'Standalone'; readonly Mongos: 'Mongos'; readonly PossiblePrimary: 'PossiblePrimary'; readonly RSPrimary: 'RSPrimary'; readonly RSSecondary: 'RSSecondary'; readonly RSArbiter: 'RSArbiter'; readonly RSOther: 'RSOther'; readonly RSGhost: 'RSGhost'; readonly Unknown: 'Unknown'; readonly LoadBalancer: 'LoadBalancer';}>;
An enumeration of server types we know about
Modifiers
@public
variable TopologyType
const TopologyType: Readonly<{ readonly Single: 'Single'; readonly ReplicaSetNoPrimary: 'ReplicaSetNoPrimary'; readonly ReplicaSetWithPrimary: 'ReplicaSetWithPrimary'; readonly Sharded: 'Sharded'; readonly Unknown: 'Unknown'; readonly LoadBalanced: 'LoadBalanced';}>;
An enumeration of topology types we know about
Modifiers
@public
Classes
class AbstractCursor
abstract class AbstractCursor< TSchema = any, CursorEvents extends AbstractCursorEvents = AbstractCursorEvents> extends TypedEventEmitter<CursorEvents> {}
Modifiers
@public
property CLOSE
static readonly CLOSE: string;
property closed
readonly closed: boolean;
The cursor is closed and all remaining locally buffered documents have been iterated.
property id
readonly id: any;
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
.
property killed
readonly killed: boolean;
A
killCursors
command was attempted on this cursor. This is performed if the cursor id is non zero.
property loadBalanced
readonly loadBalanced: boolean;
property namespace
readonly namespace: MongoDBNamespace;
property readConcern
readonly readConcern: ReadConcern;
property readPreference
readonly readPreference: ReadPreference;
method [Symbol.asyncIterator]
[Symbol.asyncIterator]: () => AsyncGenerator<TSchema, void, void>;
method addCursorFlag
addCursorFlag: (flag: CursorFlag, value: boolean) => this;
Add a cursor flag to the cursor
Parameter flag
The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial' -.
Parameter value
The flag boolean value.
method batchSize
batchSize: (value: number) => this;
Set the batch size for the cursor.
Parameter value
The number of documents to return per batch. See find command documentation.
method bufferedCount
bufferedCount: () => number;
Returns current buffered documents length
method clone
abstract clone: () => AbstractCursor<TSchema>;
Returns a new uninitialized copy of this cursor, with options matching those that have been set on the current instance
method close
close: () => Promise<void>;
method forEach
forEach: (iterator: (doc: TSchema) => boolean | void) => Promise<void>;
Iterates over all the documents for this cursor using the iterator, callback pattern.
If the iterator returns
false
, iteration will stop.Parameter iterator
The iteration callback.
Deprecated
- Will be removed in a future release. Use for await...of instead.
method hasNext
hasNext: () => Promise<boolean>;
method map
map: <T = any>(transform: (doc: TSchema) => T) => AbstractCursor<T>;
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.
Parameter transform
The mapping transformation method.
Remarks
**Note** Cursors use
null
internally to indicate that there are no more documents in the cursor. Providing a mapping function that maps values tonull
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: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:
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 1
const cursor: FindCursor<Document> = coll.find();const mappedCursor: FindCursor<number> = cursor.map(doc => Object.keys(doc).length);const keyCounts: number[] = await mappedCursor.toArray(); // cursor.toArray() still returns Document[]
method maxTimeMS
maxTimeMS: (value: number) => this;
Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
Parameter value
Number of milliseconds to wait before aborting the query.
method next
next: () => Promise<TSchema | null>;
Get the next available document from the cursor, returns null if no more documents are available.
method readBufferedDocuments
readBufferedDocuments: (number?: number) => TSchema[];
Returns current buffered documents
method rewind
rewind: () => void;
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.
method stream
stream: (options?: CursorStreamOptions) => Readable & AsyncIterable<TSchema>;
method toArray
toArray: () => Promise<TSchema[]>;
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.
method tryNext
tryNext: () => Promise<TSchema | null>;
Try to get the next available document from the cursor or
null
if an empty batch is returned
method withReadConcern
withReadConcern: (readConcern: ReadConcernLike) => this;
Set the ReadPreference for the cursor.
Parameter readPreference
The new read preference for the cursor.
method withReadPreference
withReadPreference: (readPreference: ReadPreferenceLike) => this;
Set the ReadPreference for the cursor.
Parameter readPreference
The new read preference for the cursor.
class Admin
class Admin {}
The **Admin** class is an internal class that allows convenient access to the admin functionality and commands for MongoDB.
**ADMIN Cannot directly be instantiated**
Example 1
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);}Modifiers
@public
method buildInfo
buildInfo: (options?: CommandOperationOptions) => Promise<Document>;
Retrieve the server build information
Parameter options
Optional settings for the command
method command
command: (command: Document, options?: RunCommandOptions) => Promise<Document>;
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 databaseIf 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 TransactionOptionsAttaching any of the above fields to the command will have no effect as the driver will overwrite the value.
Parameter command
The command to execute
Parameter options
Optional settings for the command
method listDatabases
listDatabases: (options?: ListDatabasesOptions) => Promise<ListDatabasesResult>;
List the available databases
Parameter options
Optional settings for the command
method ping
ping: (options?: CommandOperationOptions) => Promise<Document>;
Ping the MongoDB server and retrieve results
Parameter options
Optional settings for the command
method removeUser
removeUser: (username: string, options?: RemoveUserOptions) => Promise<boolean>;
Remove a user from a database
Parameter username
The username to remove
Parameter options
Optional settings for the command
method replSetGetStatus
replSetGetStatus: (options?: CommandOperationOptions) => Promise<Document>;
Get ReplicaSet status
Parameter options
Optional settings for the command
method serverInfo
serverInfo: (options?: CommandOperationOptions) => Promise<Document>;
Retrieve the server build information
Parameter options
Optional settings for the command
method serverStatus
serverStatus: (options?: CommandOperationOptions) => Promise<Document>;
Retrieve this db's server status.
Parameter options
Optional settings for the command
method validateCollection
validateCollection: ( collectionName: string, options?: ValidateCollectionOptions) => Promise<Document>;
Validate an existing collection
Parameter collectionName
The name of the collection to validate.
Parameter options
Optional settings for the command
class AggregationCursor
class AggregationCursor<TSchema = any> extends AbstractCursor<TSchema> {}
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
Modifiers
@public
property pipeline
readonly pipeline: Document[];
method addStage
addStage: { (stage: Document): this; <T = Document>(stage: Document): AggregationCursor<T>;};
Add a stage to the aggregation pipeline
Example 1
const documents = await users.aggregate().addStage({ $match: { name: /Mike/ } }).toArray();Example 2
const documents = await users.aggregate().addStage<{ name: string }>({ $project: { name: true } }).toArray(); // type of documents is { name: string }[]
method clone
clone: () => AggregationCursor<TSchema>;
method explain
explain: (verbosity?: ExplainVerbosityLike) => Promise<Document>;
Execute the explain for the cursor
method geoNear
geoNear: ($geoNear: Document) => this;
Add a geoNear stage to the aggregation pipeline
method group
group: <T = TSchema>($group: Document) => AggregationCursor<T>;
Add a group stage to the aggregation pipeline
method limit
limit: ($limit: number) => this;
Add a limit stage to the aggregation pipeline
method lookup
lookup: ($lookup: Document) => this;
Add a lookup stage to the aggregation pipeline
method map
map: <T>(transform: (doc: TSchema) => T) => AggregationCursor<T>;
method match
match: ($match: Document) => this;
Add a match stage to the aggregation pipeline
method out
out: ($out: { db: string; coll: string } | string) => this;
Add an out stage to the aggregation pipeline
method project
project: <T extends Document = Document>( $project: Document) => AggregationCursor<T>;
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.
**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 1
// Best wayconst docs: AggregationCursor<{ a: number }> = cursor.project<{ a: number }>({ _id: 0, a: true });// Flexible wayconst docs: AggregationCursor<Document> = cursor.project({ _id: 0, a: true });Example 2
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 cursorconst cursor = coll.aggregate().project<{ a: string }>({_id: 0,a: { $convert: { input: '$a', to: 'string' }}});
method redact
redact: ($redact: Document) => this;
Add a redact stage to the aggregation pipeline
method skip
skip: ($skip: number) => this;
Add a skip stage to the aggregation pipeline
method sort
sort: ($sort: Sort) => this;
Add a sort stage to the aggregation pipeline
method unwind
unwind: ($unwind: Document | string) => this;
Add a unwind stage to the aggregation pipeline
class Batch
class Batch<T = Document> {}
Keeps the state of a unordered batch so we can rewrite the results correctly after command execution
Modifiers
@public
constructor
constructor(batchType: BatchType, originalZeroIndex: number);
property batchType
batchType: BatchType;
property currentIndex
currentIndex: number;
property operations
operations: T[];
property originalIndexes
originalIndexes: number[];
property originalZeroIndex
originalZeroIndex: number;
property size
size: number;
property sizeBytes
sizeBytes: number;
class BulkOperationBase
abstract class BulkOperationBase {}
Modifiers
@public
property batches
readonly batches: Batch<Document>[];
property bsonOptions
readonly bsonOptions: BSONSerializeOptions;
property isOrdered
isOrdered: boolean;
property operationId
operationId?: number;
property writeConcern
readonly writeConcern: WriteConcern;
method addToOperationsList
abstract addToOperationsList: ( batchType: BatchType, document: Document | UpdateStatement | DeleteStatement) => this;
method execute
execute: (options?: BulkWriteOptions) => Promise<BulkWriteResult>;
method find
find: (selector: Document) => FindOperators;
Builds a find operation for an update/updateOne/delete/deleteOne/replaceOne. Returns a builder object used to complete the definition of the operation.
Example 1
const bulkOp = collection.initializeOrderedBulkOp();// Add an updateOne to the bulkOpbulkOp.find({ a: 1 }).updateOne({ $set: { b: 2 } });// Add an updateMany to the bulkOpbulkOp.find({ c: 3 }).update({ $set: { d: 4 } });// Add an upsertbulkOp.find({ e: 5 }).upsert().updateOne({ $set: { f: 6 } });// Add a deletionbulkOp.find({ g: 7 }).deleteOne();// Add a multi deletionbulkOp.find({ h: 8 }).delete();// Add a replaceOnebulkOp.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 executedawait bulkOp.execute();
method insert
insert: (document: Document) => BulkOperationBase;
Add a single insert document to the bulk operation
Example 1
const bulkOp = collection.initializeOrderedBulkOp();// Adds three inserts to the bulkOp.bulkOp.insert({ a: 1 }).insert({ b: 2 }).insert({ c: 3 });await bulkOp.execute();
method raw
raw: (op: AnyBulkWriteOperation) => this;
Specifies a raw operation to perform in the bulk write.
class BulkWriteResult
class BulkWriteResult {}
The result of a bulk write.
Modifiers
@public
property deletedCount
readonly deletedCount: number;
Number of documents deleted.
property insertedCount
readonly insertedCount: number;
Number of documents inserted.
property insertedIds
readonly insertedIds: { [key: number]: any };
Inserted document generated Id's, hash key is the index of the originating operation
property matchedCount
readonly matchedCount: number;
Number of documents matched for update.
property modifiedCount
readonly modifiedCount: number;
Number of documents modified.
property ok
readonly ok: number;
Evaluates to true if the bulk operation correctly executes
property upsertedCount
readonly upsertedCount: number;
Number of documents upserted.
property upsertedIds
readonly upsertedIds: { [key: number]: any };
Upserted document generated Id's, hash key is the index of the originating operation
method getRawResponse
getRawResponse: () => Document;
Returns raw internal result
method getUpsertedIdAt
getUpsertedIdAt: (index: number) => Document | undefined;
Returns the upserted id at the given index
method getWriteConcernError
getWriteConcernError: () => WriteConcernError | undefined;
Retrieve the write concern error if one exists
method getWriteErrorAt
getWriteErrorAt: (index: number) => WriteError | undefined;
Returns a specific write error object
method getWriteErrorCount
getWriteErrorCount: () => number;
Returns the number of write errors off the bulk operation
method getWriteErrors
getWriteErrors: () => WriteError[];
Retrieve all write errors
method hasWriteErrors
hasWriteErrors: () => boolean;
Returns true if the bulk operation contains a write error
method isOk
isOk: () => boolean;
method toString
toString: () => string;
class CancellationToken
class CancellationToken extends TypedEventEmitter<{ cancel(): void;}> {}
Modifiers
@public
class ChangeStream
class ChangeStream< TSchema extends Document = Document, TChange extends Document = ChangeStreamDocument<TSchema>> extends TypedEventEmitter<ChangeStreamEvents<TSchema, TChange>> {}
Creates a new Change Stream instance. Normally created using Collection.watch().
Modifiers
@public
property CHANGE
static readonly CHANGE: string;
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.
property CLOSE
static readonly CLOSE: string;
property closed
readonly closed: boolean;
Is the cursor closed
property END
static readonly END: string;
property ERROR
static readonly ERROR: string;
property INIT
static readonly INIT: string;
property MORE
static readonly MORE: string;
property namespace
namespace: MongoDBNamespace;
property options
options: ChangeStreamOptions & { writeConcern?: never };
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.
property parent
parent: MongoClient | Db | Collection<Document>;
property pipeline
pipeline: Document[];
property RESPONSE
static readonly RESPONSE: string;
property RESUME_TOKEN_CHANGED
static readonly RESUME_TOKEN_CHANGED: string;
Emitted each time the change stream stores a new resume token.
property resumeToken
readonly resumeToken: {};
The cached resume token that is used to resume after the most recently returned change.
property streamOptions
streamOptions?: CursorStreamOptions;
property type
type: Symbol;
method [Symbol.asyncIterator]
[Symbol.asyncIterator]: () => AsyncGenerator<TChange, void, void>;
method close
close: () => Promise<void>;
Close the Change Stream
method hasNext
hasNext: () => Promise<boolean>;
Check if there is any document still available in the Change Stream
method next
next: () => Promise<TChange>;
Get the next available document from the Change Stream.
method stream
stream: (options?: CursorStreamOptions) => Readable & AsyncIterable<TChange>;
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
method tryNext
tryNext: () => Promise<TChange | null>;
Try to get the next available document from the Change Stream's cursor or
null
if an empty batch is returned
class ClientEncryption
class ClientEncryption {}
The public interface for explicit in-use encryption
Modifiers
@public
constructor
constructor(client: MongoClient, options: ClientEncryptionOptions);
Create a new encryption instance
Example 1
new ClientEncryption(mongoClient, {keyVaultNamespace: 'client.encryption',kmsProviders: {local: {key: masterKey // The master key used for encryption/decryption. A 96-byte long Buffer}}});Example 2
new ClientEncryption(mongoClient, {keyVaultNamespace: 'client.encryption',kmsProviders: {aws: {accessKeyId: AWS_ACCESS_KEY,secretAccessKey: AWS_SECRET_KEY}}});
property libmongocryptVersion
static readonly libmongocryptVersion: string;
method addKeyAltName
addKeyAltName: ( _id: Binary, keyAltName: string) => Promise<WithId<DataKey> | null>;
Adds a keyAltName to a key identified by the provided _id.
This method resolves to/returns the *old* key value (prior to adding the new altKeyName).
Parameter _id
The id of the document to update.
Parameter keyAltName
a keyAltName to search for a key
Returns
Returns a promise that either resolves to a 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 1
// adding an keyAltName to a data keyconst id = new Binary(); // id is a bson binary subtype 4 objectconst 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}
method createDataKey
createDataKey: ( provider: ClientEncryptionDataKeyProvider, options?: ClientEncryptionCreateDataKeyProviderOptions) => Promise<UUID>;
Creates a data key used for explicit encryption and inserts it into the key vault namespace
Example 1
// Using async/await to create a local keyconst dataKeyId = await clientEncryption.createDataKey('local');Example 2
// Using async/await to create an aws keyconst dataKeyId = await clientEncryption.createDataKey('aws', {masterKey: {region: 'us-east-1',key: 'xxxxxxxxxxxxxx' // CMK ARN here}});Example 3
// Using async/await to create an aws key with a keyAltNameconst dataKeyId = await clientEncryption.createDataKey('aws', {masterKey: {region: 'us-east-1',key: 'xxxxxxxxxxxxxx' // CMK ARN here},keyAltNames: [ 'mySpecialKey' ]});
method createEncryptedCollection
createEncryptedCollection: <TSchema extends Document = Document>( db: Db, name: string, options: { provider: ClientEncryptionDataKeyProvider; createCollectionOptions: Omit< CreateCollectionOptions, 'encryptedFields' > & { encryptedFields: Document }; masterKey?: | AWSEncryptionKeyOptions | AzureEncryptionKeyOptions | GCPEncryptionKeyOptions; }) => Promise<{ collection: Collection<TSchema>; encryptedFields: Document }>;
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.Parameter db
A Node.js driver Db object with which to create the collection
Parameter name
The name of the collection to be created
Parameter 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.
method decrypt
decrypt: <T = any>(value: Binary) => Promise<T>;
Explicitly decrypt a provided encrypted value
Parameter value
An encrypted value
Returns
a Promise that either resolves with the decrypted value, or rejects with an error
Example 1
// Decrypting value with async/await APIasync function decryptMyValue(value) {return clientEncryption.decrypt(value);}
method deleteKey
deleteKey: (_id: Binary) => Promise<DeleteResult>;
Deletes the key with the provided id from the keyvault, if it exists.
Example 1
// delete a key by _idconst id = new Binary(); // id is a bson binary subtype 4 objectconst { deletedCount } = await clientEncryption.deleteKey(id);if (deletedCount != null && deletedCount > 0) {// successful deletion}
method encrypt
encrypt: ( value: unknown, options: ClientEncryptionEncryptOptions) => Promise<Binary>;
Explicitly encrypt a provided value. Note that either
options.keyId
oroptions.keyAltName
must be specified. Specifying bothoptions.keyId
andoptions.keyAltName
is considered an error.Parameter value
The value that you wish to serialize. Must be of a type that can be serialized into BSON
Parameter options
Returns
a Promise that either resolves with the encrypted value, or rejects with an error.
Example 1
// Encryption with async/await apiasync function encryptMyData(value) {const keyId = await clientEncryption.createDataKey('local');return clientEncryption.encrypt(value, { keyId, algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });}Example 2
// Encryption using a keyAltNameasync function encryptMyData(value) {await clientEncryption.createDataKey('local', { keyAltNames: 'mySpecialKey' });return clientEncryption.encrypt(value, { keyAltName: 'mySpecialKey', algorithm: 'AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic' });}
method encryptExpression
encryptExpression: ( expression: Document, options: ClientEncryptionEncryptOptions) => Promise<Binary>;
Encrypts a Match Expression or Aggregate Expression to query a range index.
Only supported when queryType is "rangePreview" and algorithm is "RangePreview".
The Range algorithm is experimental only. It is not intended for production use. It is subject to breaking changes.
Parameter expression
a BSON document of one of the following forms: 1. A Match Expression of this form:
{$and: [{<field>: {$gt: <value1>}}, {<field>: {$lt: <value2> }}]}
2. An Aggregate Expression of this form:{$and: [{$gt: [<fieldpath>, <value1>]}, {$lt: [<fieldpath>, <value2>]}]}
$gt
may also be$gte
.$lt
may also be$lte
.Parameter options
Returns
Returns a Promise that either resolves with the encrypted value or rejects with an error.
Modifiers
@experimental
method getKey
getKey: (_id: Binary) => Promise<DataKey | null>;
Finds a key in the keyvault with the specified _id.
Returns a promise that either resolves to a 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 1
// getting a key by idconst id = new Binary(); // id is a bson binary subtype 4 objectconst key = await clientEncryption.getKey(id);if (!key) {// key is null if there was no matching key}
method getKeyByAltName
getKeyByAltName: (keyAltName: string) => Promise<WithId<DataKey> | null>;
Finds a key in the keyvault which has the specified keyAltName.
Parameter keyAltName
a keyAltName to search for a key
Returns
Returns a promise that either resolves to a 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 1
// get a key by alt nameconst keyAltName = 'keyAltName';const key = await clientEncryption.getKeyByAltName(keyAltName);if (!key) {// key is null if there is no matching key}
method getKeys
getKeys: () => FindCursor<DataKey>;
Finds all the keys currently stored in the keyvault.
This method will not throw.
Returns
a FindCursor over all keys in the keyvault.
Example 1
// fetching all keysconst keys = await clientEncryption.getKeys().toArray();
method removeKeyAltName
removeKeyAltName: ( _id: Binary, keyAltName: string) => Promise<WithId<DataKey> | null>;
Adds a keyAltName to a key identified by the provided _id.
This method resolves to/returns the *old* key value (prior to removing the new altKeyName).
If the removed keyAltName is the last keyAltName for that key, the
altKeyNames
property is unset from the document.Parameter _id
The id of the document to update.
Parameter keyAltName
a keyAltName to search for a key
Returns
Returns a promise that either resolves to a 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 1
// removing a key alt name from a data keyconst id = new Binary(); // id is a bson binary subtype 4 objectconst 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}
method rewrapManyDataKey
rewrapManyDataKey: ( filter: Filter<DataKey>, options: ClientEncryptionRewrapManyDataKeyProviderOptions) => Promise<{ bulkWriteResult?: BulkWriteResult }>;
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 1
// 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 2
// attempting to rewrap all data keys with no matchesconst filter = { _id: new Binary() } // assume _id matches no documents in the databaseconst result = await clientEncryption.rewrapManyDataKey(filter);if (result.bulkWriteResult == null) {// no keys matched, `bulkWriteResult` does not exist on the result object}
class ClientSession
class ClientSession extends TypedEventEmitter<ClientSessionEvents> {}
A class representing a client session on the server
NOTE: not meant to be instantiated directly.
Modifiers
@public
property clientOptions
clientOptions?: MongoOptions;
property clusterTime
clusterTime?: ClusterTime;
property defaultTransactionOptions
defaultTransactionOptions: TransactionOptions;
property explicit
explicit: boolean;
property hasEnded
hasEnded: boolean;
property id
readonly id: ServerSessionId;
The server id associated with this session
property isPinned
readonly isPinned: boolean;
property loadBalanced
readonly loadBalanced: boolean;
property operationTime
operationTime?: Timestamp;
property serverSession
readonly serverSession: ServerSession;
property snapshotEnabled
readonly snapshotEnabled: boolean;
Whether or not this session is configured for snapshot reads
property supports
supports: { causalConsistency: boolean };
property transaction
transaction: Transaction;
method abortTransaction
abortTransaction: () => Promise<void>;
Aborts the currently active transaction in this session.
method advanceClusterTime
advanceClusterTime: (clusterTime: ClusterTime) => void;
Advances the clusterTime for a ClientSession to the provided clusterTime of another ClientSession
Parameter clusterTime
the $clusterTime returned by the server from another session in the form of a document containing the
BSON.Timestamp
clusterTime and signature
method advanceOperationTime
advanceOperationTime: (operationTime: Timestamp) => void;
Advances the operationTime for a ClientSession.
Parameter operationTime
the
BSON.Timestamp
of the operation type it is desired to advance to
method commitTransaction
commitTransaction: () => Promise<void>;
Commits the currently active transaction in this session.
method endSession
endSession: (options?: EndSessionOptions) => Promise<void>;
Ends this session on the server
Parameter options
Optional settings. Currently reserved for future use
method equals
equals: (session: ClientSession) => boolean;
Used to determine if this session equals another
Parameter session
The session to compare to
method incrementTransactionNumber
incrementTransactionNumber: () => void;
Increment the transaction number on the internal ServerSession
method inTransaction
inTransaction: () => boolean;
Returns
whether this session is currently in a transaction or not
method startTransaction
startTransaction: (options?: TransactionOptions) => void;
Starts a new transaction with the given options.
Parameter options
Options for the transaction
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.
method toBSON
toBSON: () => never;
This is here to ensure that ClientSession is never serialized to BSON.
method withTransaction
withTransaction: <T = any>( fn: WithTransactionCallback<T>, options?: TransactionOptions) => Promise<T>;
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.Parameter fn
callback to run within a transaction
Parameter options
optional settings for the transaction
Returns
A raw command response or undefined
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 Also
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.
class Collection
class Collection<TSchema extends Document = Document> {}
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**
Example 1
import { MongoClient } from 'mongodb';interface Pet {name: string;kind: 'dog' | 'cat' | 'fish';}const client = new MongoClient('mongodb://localhost:27017');const pets = client.db().collection<Pet>('pets');const petCursor = pets.find();for await (const pet of petCursor) {console.log(`${pet.name} is a ${pet.kind}!`);}Modifiers
@public
property bsonOptions
readonly bsonOptions: BSONSerializeOptions;
property collectionName
readonly collectionName: string;
The name of this collection
property dbName
readonly dbName: string;
The name of the database this collection belongs to
property hint
hint: any;
The current index hint for the collection
property namespace
readonly namespace: string;
The namespace of this collection, in the format
${this.dbName}.${this.collectionName}
property readConcern
readonly readConcern: ReadConcern;
The current readConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB
property readPreference
readonly readPreference: ReadPreference;
The current readPreference of the collection. If not explicitly defined for this collection, will be inherited from the parent DB
property writeConcern
readonly writeConcern: WriteConcern;
The current writeConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB
method aggregate
aggregate: <T extends Document = Document>( pipeline?: Document[], options?: AggregateOptions) => AggregationCursor<T>;
Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
Parameter pipeline
An array of aggregation pipelines to execute
Parameter options
Optional settings for the command
method bulkWrite
bulkWrite: ( operations: AnyBulkWriteOperation<TSchema>[], options?: BulkWriteOptions) => Promise<BulkWriteResult>;
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.
Parameter operations
Bulk operations to perform
Parameter options
Optional settings for the command
Throws
MongoDriverError if operations is not an array
method count
count: (filter?: Filter<TSchema>, options?: CountOptions) => Promise<number>;
An estimated count of matching documents in the db to a filter.
**NOTE:** This method has been deprecated, since it does not provide an accurate count of the documents in a collection. To obtain an accurate count of documents in the collection, use countDocuments. To obtain an estimated count of all documents in the collection, use estimatedDocumentCount.
Parameter filter
The filter for the count.
Parameter options
Optional settings for the command
Deprecated
use countDocuments or estimatedDocumentCount instead
method countDocuments
countDocuments: ( filter?: Filter<TSchema>, options?: CountDocumentsOptions) => Promise<number>;
Gets the number of documents matching the filter. For a fast count of the total documents in a collection see estimatedDocumentCount. **Note**: When migrating from count to countDocuments the following query operators must be replaced:
| Operator | Replacement | | -------- | ----------- | |
$where
| [$expr
][1] | |$near
| [$geoWithin
][2] with [$center
][3] | |$nearSphere
| [$geoWithin
][2] with [$centerSphere
][4] |[1]: https://www.mongodb.com/docs/manual/reference/operator/query/expr/ [2]: https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/ [3]: https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center [4]: https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
Parameter filter
The filter for the count
Parameter options
Optional settings for the command
See Also
https://www.mongodb.com/docs/manual/reference/operator/query/expr/
https://www.mongodb.com/docs/manual/reference/operator/query/geoWithin/
https://www.mongodb.com/docs/manual/reference/operator/query/center/#op._S_center
https://www.mongodb.com/docs/manual/reference/operator/query/centerSphere/#op._S_centerSphere
method createIndex
createIndex: ( indexSpec: IndexSpecification, options?: CreateIndexesOptions) => Promise<string>;
Creates an index on the db and collection collection.
Parameter indexSpec
The field name or index specification to create an index for
Parameter options
Optional settings for the command
Example 1
const collection = client.db('foo').collection('bar');await collection.createIndex({ a: 1, b: -1 });// Alternate syntax for { c: 1, d: -1 } that ensures order of indexesawait collection.createIndex([ [c, 1], [d, -1] ]);// Equivalent to { e: 1 }await collection.createIndex('e');// Equivalent to { f: 1, g: 1 }await collection.createIndex(['f', 'g'])// Equivalent to { h: 1, i: -1 }await collection.createIndex([ { h: 1 }, { i: -1 } ]);// Equivalent to { j: 1, k: -1, l: 2d }await collection.createIndex(['j', ['k', -1], { l: '2d' }])
method createIndexes
createIndexes: ( indexSpecs: IndexDescription[], options?: CreateIndexesOptions) => Promise<string[]>;
Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported error.
**Note**: Unlike createIndex, this function takes in raw index specifications. Index specifications are defined here.
Parameter indexSpecs
An array of index specifications to be created
Parameter options
Optional settings for the command
Example 1
const collection = client.db('foo').collection('bar');await collection.createIndexes([// Simple index on field fizz{key: { fizz: 1 },}// wildcard index{key: { '$**': 1 }},// named index on darmok and jalad{key: { darmok: 1, jalad: -1 }name: 'tanagra'}]);
method createSearchIndex
createSearchIndex: (description: SearchIndexDescription) => Promise<string>;
Creates a single search index for the collection.
Parameter description
The index description for the new search index.
Returns
A promise that resolves to the name of the new search index.
Remarks
Only available when used against a 7.0+ Atlas cluster.
method createSearchIndexes
createSearchIndexes: ( descriptions: SearchIndexDescription[]) => Promise<string[]>;
Creates multiple search indexes for the current collection.
Parameter descriptions
An array of
SearchIndexDescription
s for the new search indexes.Returns
Remarks
Only available when used against a 7.0+ Atlas cluster.
method deleteMany
deleteMany: ( filter?: Filter<TSchema>, options?: DeleteOptions) => Promise<DeleteResult>;
Delete multiple documents from a collection
Parameter filter
The filter used to select the documents to remove
Parameter options
Optional settings for the command
method deleteOne
deleteOne: ( filter?: Filter<TSchema>, options?: DeleteOptions) => Promise<DeleteResult>;
Delete a document from a collection
Parameter filter
The filter used to select the document to remove
Parameter options
Optional settings for the command
method distinct
distinct: { <Key extends '_id' | keyof EnhancedOmit<TSchema, '_id'>>(key: Key): Promise< Array<Flatten<WithId<TSchema>[Key]>> >; <Key extends '_id' | keyof EnhancedOmit<TSchema, '_id'>>( key: Key, filter: Filter<TSchema> ): Promise<Flatten<WithId<TSchema>[Key]>[]>; <Key extends '_id' | keyof EnhancedOmit<TSchema, '_id'>>( key: Key, filter: Filter<TSchema>, options: CommandOperationOptions ): Promise<Flatten<WithId<TSchema>[Key]>[]>; (key: string): Promise<any[]>; (key: string, filter: Filter<TSchema>): Promise<any[]>; ( key: string, filter: Filter<TSchema>, options: CommandOperationOptions ): Promise<any[]>;};
The distinct command returns a list of distinct values for the given key across a collection.
Parameter key
Field of the document to find distinct values for
Parameter filter
The filter for filtering the set of documents to which we apply the distinct filter.
Parameter options
Optional settings for the command
method drop
drop: (options?: DropCollectionOptions) => Promise<boolean>;
Drop the collection from the database, removing it permanently. New accesses will create a new collection.
Parameter options
Optional settings for the command
method dropIndex
dropIndex: ( indexName: string, options?: DropIndexesOptions) => Promise<Document>;
Drops an index from this collection.
Parameter indexName
Name of the index to drop.
Parameter options
Optional settings for the command
method dropIndexes
dropIndexes: (options?: DropIndexesOptions) => Promise<boolean>;
Drops all indexes from this collection.
Parameter options
Optional settings for the command
method dropSearchIndex
dropSearchIndex: (name: string) => Promise<void>;
Deletes a search index by index name.
Parameter name
The name of the search index to be deleted.
Remarks
Only available when used against a 7.0+ Atlas cluster.
method estimatedDocumentCount
estimatedDocumentCount: ( options?: EstimatedDocumentCountOptions) => Promise<number>;
Gets an estimate of the count of documents in a collection using collection metadata. This will always run a count command on all server versions.
due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, which estimatedDocumentCount uses in its implementation, was not included in v1 of the Stable API, and so users of the Stable API with estimatedDocumentCount are recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid encountering errors.
Parameter options
Optional settings for the command
See Also
method find
find: { (): FindCursor<WithId<TSchema>>; (filter: Filter<TSchema>, options?: FindOptions<Document>): FindCursor< WithId<TSchema> >; <T extends Document>( filter: Filter<TSchema>, options?: FindOptions<Document> ): FindCursor<T>;};
Creates a cursor for a filter that can be used to iterate over results from MongoDB
Parameter filter
The filter predicate. If unspecified, then all documents in the collection will match the predicate
method findOne
findOne: { (): Promise<WithId<TSchema> | null>; (filter: Filter<TSchema>): Promise<WithId<TSchema>>; (filter: Filter<TSchema>, options: FindOptions<Document>): Promise< WithId<TSchema> >; <T = TSchema>(): Promise<T>; <T = TSchema>(filter: Filter<TSchema>): Promise<T>; <T = TSchema>( filter: Filter<TSchema>, options?: FindOptions<Document> ): Promise<T>;};
Fetches the first document that matches the filter
Parameter filter
Query for find Operation
Parameter options
Optional settings for the command
method findOneAndDelete
findOneAndDelete: { ( filter: Filter<TSchema>, options: FindOneAndDeleteOptions & { includeResultMetadata: true } ): Promise<ModifyResult<TSchema>>; ( filter: Filter<TSchema>, options: FindOneAndDeleteOptions & { includeResultMetadata: false } ): Promise<WithId<TSchema>>; (filter: Filter<TSchema>, options: FindOneAndDeleteOptions): Promise< WithId<TSchema> >; (filter: Filter<TSchema>): Promise<WithId<TSchema>>;};
Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
Parameter filter
The filter used to select the document to remove
Parameter options
Optional settings for the command
method findOneAndReplace
findOneAndReplace: { ( filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions & { includeResultMetadata: true } ): Promise<ModifyResult<TSchema>>; ( filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions & { includeResultMetadata: false } ): Promise<WithId<TSchema>>; ( filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options: FindOneAndReplaceOptions ): Promise<WithId<TSchema>>; (filter: Filter<TSchema>, replacement: WithoutId<TSchema>): Promise< WithId<TSchema> >;};
Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
Parameter filter
The filter used to select the document to replace
Parameter replacement
The Document that replaces the matching document
Parameter options
Optional settings for the command
method findOneAndUpdate
findOneAndUpdate: { ( filter: Filter<TSchema>, update: UpdateFilter<TSchema>, options: FindOneAndUpdateOptions & { includeResultMetadata: true } ): Promise<ModifyResult<TSchema>>; ( filter: Filter<TSchema>, update: any, options: FindOneAndUpdateOptions & { includeResultMetadata: false } ): Promise<WithId<TSchema>>; ( filter: Filter<TSchema>, update: any, options: FindOneAndUpdateOptions ): Promise<WithId<TSchema>>; (filter: Filter<TSchema>, update: any): Promise<WithId<TSchema>>;};
Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
Parameter filter
The filter used to select the document to update
Parameter update
Update operations to be performed on the document
Parameter options
Optional settings for the command
method indexes
indexes: { (options: IndexInformationOptions & { full?: true }): Promise< IndexDescriptionInfo[] >; ( options: IndexInformationOptions & { full: false } ): Promise<IndexDescriptionCompact>; (options: IndexInformationOptions): Promise<any[] | IndexDescriptionCompact>; (options?: AbstractCursorOptions): Promise<any[]>;};
Retrieve all the indexes on the collection.
Parameter options
Optional settings for the command
method indexExists
indexExists: ( indexes: string | string[], options?: ListIndexesOptions) => Promise<boolean>;
Checks if one or more indexes exist on the collection, fails on first non-existing index
Parameter indexes
One or more index names to check.
Parameter options
Optional settings for the command
method indexInformation
indexInformation: { (options: IndexInformationOptions & { full: true }): Promise< IndexDescriptionInfo[] >; ( options: IndexInformationOptions & { full?: false } ): Promise<IndexDescriptionCompact>; (options: IndexInformationOptions): Promise<any[] | IndexDescriptionCompact>; (): Promise<IndexDescriptionCompact>;};
Retrieves this collections index info.
Parameter options
Optional settings for the command
method initializeOrderedBulkOp
initializeOrderedBulkOp: (options?: BulkWriteOptions) => OrderedBulkOperation;
Initiate an In order bulk write operation. Operations will be serially executed in the order they are added, creating a new operation for each switch in types.
Throws
MongoNotConnectedError
Remarks
**NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. However,
collection.bulkWrite()
provides an equivalent API that does not require prior connecting.
method initializeUnorderedBulkOp
initializeUnorderedBulkOp: ( options?: BulkWriteOptions) => UnorderedBulkOperation;
Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Throws
MongoNotConnectedError
Remarks
**NOTE:** MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation. However,
collection.bulkWrite()
provides an equivalent API that does not require prior connecting.
method insertMany
insertMany: ( docs: OptionalUnlessRequiredId<TSchema>[], options?: BulkWriteOptions) => Promise<InsertManyResult<TSchema>>;
Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the **forceServerObjectId** flag.
Parameter docs
The documents to insert
Parameter options
Optional settings for the command
method insertOne
insertOne: ( doc: OptionalUnlessRequiredId<TSchema>, options?: InsertOneOptions) => Promise<InsertOneResult<TSchema>>;
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.
Parameter doc
The document to insert
Parameter options
Optional settings for the command
method isCapped
isCapped: (options?: OperationOptions) => Promise<boolean>;
Returns if the collection is a capped collection
Parameter options
Optional settings for the command
method listIndexes
listIndexes: (options?: ListIndexesOptions) => ListIndexesCursor;
Get the list of all indexes information for the collection.
Parameter options
Optional settings for the command
method listSearchIndexes
listSearchIndexes: { (options?: ListSearchIndexesOptions): ListSearchIndexesCursor; (name: string, options?: ListSearchIndexesOptions): ListSearchIndexesCursor;};
Returns all search indexes for the current collection.
Parameter options
The options for the list indexes operation.
Remarks
Only available when used against a 7.0+ Atlas cluster.
Returns all search indexes for the current collection.
Parameter name
The name of the index to search for. Only indexes with matching index names will be returned.
Parameter options
The options for the list indexes operation.
Remarks
Only available when used against a 7.0+ Atlas cluster.
method options
options: (options?: OperationOptions) => Promise<Document>;
Returns the options of the collection.
Parameter options
Optional settings for the command
method rename
rename: (newName: string, options?: RenameOptions) => Promise<Collection>;
Rename the collection.
Parameter newName
New name of of the collection.
Parameter options
Optional settings for the command
Remarks
This operation does not inherit options from the Db or MongoClient.
method replaceOne
replaceOne: ( filter: Filter<TSchema>, replacement: WithoutId<TSchema>, options?: ReplaceOptions) => Promise<UpdateResult<TSchema> | Document>;
Replace a document in a collection with another document
Parameter filter
The filter used to select the document to replace
Parameter replacement
The Document that replaces the matching document
Parameter options
Optional settings for the command
method updateMany
updateMany: ( filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions) => Promise<UpdateResult<TSchema>>;
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.Parameter filter
The filter used to select the document to update
Parameter update
The modifications to apply
Parameter options
Optional settings for the command
method updateOne
updateOne: ( filter: Filter<TSchema>, update: UpdateFilter<TSchema> | Document[], options?: UpdateOptions) => Promise<UpdateResult<TSchema>>;
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.Parameter filter
The filter used to select the document to update
Parameter update
The modifications to apply
Parameter options
Optional settings for the command
method updateSearchIndex
updateSearchIndex: (name: string, definition: Document) => Promise<void>;
Updates a search index by replacing the existing index definition with the provided definition.
Parameter name
The name of the search index to update.
Parameter definition
The new search index definition.
Remarks
Only available when used against a 7.0+ Atlas cluster.
method watch
watch: < TLocal extends Document = TSchema, TChange extends Document = ChangeStreamDocument<TLocal>>( pipeline?: Document[], options?: ChangeStreamOptions) => ChangeStream<TLocal, TChange>;
Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
Parameter pipeline
An array of aggregation pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
Parameter options
Optional settings for the command
Remarks
watch() accepts two generic arguments for distinct use cases: - The first is to override the schema that may be defined for this specific collection - The second is to override the shape of the change stream document entirely, if it is not provided the type will default to ChangeStreamDocument of the first argument
Example 1
By just providing the first argument I can type the change to be
ChangeStreamDocument<{ _id: number }>
collection.watch<{ _id: number }>().on('change', change => console.log(change._id.toFixed(4)));Example 2
Passing a second argument provides a way to reflect the type changes caused by an advanced pipeline. Here, we are using a pipeline to have MongoDB filter for insert changes only and add a comment. No need start from scratch on the ChangeStreamInsertDocument type! By using an intersection we can save time and ensure defaults remain the same type!
collection.watch<Schema, ChangeStreamInsertDocument<Schema> & { comment: string }>([{ $addFields: { comment: 'big changes' } },{ $match: { operationType: 'insert' } }]).on('change', change => {change.comment.startsWith('big');change.operationType === 'insert';// No need to narrow in code because the generics did that for us!expectType<Schema>(change.fullDocument);});
class CommandFailedEvent
class CommandFailedEvent {}
An event indicating the failure of a given command
Event
Modifiers
@public
property address
address: string;
property commandName
commandName: string;
property connectionId
connectionId?: string | number;
Driver generated connection id
property duration
duration: number;
property failure
failure: Error;
property hasServiceId
readonly hasServiceId: boolean;
property requestId
requestId: number;
property serverConnectionId
serverConnectionId: BigInt;
Server generated connection id Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
property serviceId
serviceId?: ObjectId;
class CommandStartedEvent
class CommandStartedEvent {}
An event indicating the start of a given command
Event
Modifiers
@public
property address
address: string;
property command
command: Document;
property commandName
commandName: string;
property commandObj
commandObj?: Document;
property connectionId
connectionId?: string | number;
Driver generated connection id
property databaseName
databaseName: string;
property hasServiceId
readonly hasServiceId: boolean;
property requestId
requestId: number;
property serverConnectionId
serverConnectionId: BigInt;
Server generated connection id Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
property serviceId
serviceId?: ObjectId;
class CommandSucceededEvent
class CommandSucceededEvent {}
An event indicating the success of a given command
Event
Modifiers
@public
property address
address: string;
property commandName
commandName: string;
property connectionId
connectionId?: string | number;
Driver generated connection id
property duration
duration: number;
property hasServiceId
readonly hasServiceId: boolean;
property reply
reply: {};
property requestId
requestId: number;
property serverConnectionId
serverConnectionId: BigInt;
Server generated connection id Distinct from the connection id and is returned by the hello or legacy hello response as "connectionId" from the server on 4.2+.
property serviceId
serviceId?: ObjectId;
class ConnectionCheckedInEvent
class ConnectionCheckedInEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection is checked into the connection pool
Event
Modifiers
@public
property connectionId
connectionId: number | '<monitor>';
The id of the connection
class ConnectionCheckedOutEvent
class ConnectionCheckedOutEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection is checked out of the connection pool
Event
Modifiers
@public
property connectionId
connectionId: number | '<monitor>';
The id of the connection
class ConnectionCheckOutFailedEvent
class ConnectionCheckOutFailedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a request to check a connection out fails
Event
Modifiers
@public
property reason
reason: string;
The reason the attempt to check out failed
class ConnectionCheckOutStartedEvent
class ConnectionCheckOutStartedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a request to check a connection out begins
Event
Modifiers
@public
class ConnectionClosedEvent
class ConnectionClosedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection is closed
Event
Modifiers
@public
property connectionId
connectionId: number | '<monitor>';
The id of the connection
property reason
reason: string;
The reason the connection was closed
property serviceId
serviceId?: ObjectId;
class ConnectionCreatedEvent
class ConnectionCreatedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection pool creates a new connection
Event
Modifiers
@public
property connectionId
connectionId: number | '<monitor>';
A monotonically increasing, per-pool id for the newly created connection
class ConnectionPoolClearedEvent
class ConnectionPoolClearedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection pool is cleared
Event
Modifiers
@public
property interruptInUseConnections
interruptInUseConnections?: boolean;
class ConnectionPoolClosedEvent
class ConnectionPoolClosedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection pool is closed
Event
Modifiers
@public
class ConnectionPoolCreatedEvent
class ConnectionPoolCreatedEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection pool is created
Event
Modifiers
@public
property options
options: Pick< ConnectionPoolOptions, | 'maxPoolSize' | 'minPoolSize' | 'maxConnecting' | 'maxIdleTimeMS' | 'waitQueueTimeoutMS'>;
The options used to create this connection pool
class ConnectionPoolMonitoringEvent
abstract class ConnectionPoolMonitoringEvent {}
The base export class for all monitoring events published from the connection pool
Event
Modifiers
@public
class ConnectionPoolReadyEvent
class ConnectionPoolReadyEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection pool is ready
Event
Modifiers
@public
class ConnectionReadyEvent
class ConnectionReadyEvent extends ConnectionPoolMonitoringEvent {}
An event published when a connection is ready for use
Event
Modifiers
@public
property connectionId
connectionId: number | '<monitor>';
The id of the connection
class Db
class Db {}
The **Db** class is a class that represents a MongoDB Database.
Example 1
import { MongoClient } from 'mongodb';interface Pet {name: string;kind: 'dog' | 'cat' | 'fish';}const client = new MongoClient('mongodb://localhost:27017');const db = client.db();// Create a collection that validates our unionawait db.createCollection<Pet>('pets', {validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }})Modifiers
@public
constructor
constructor(client: MongoClient, databaseName: string, options?: DbOptions);
Creates a new Db instance.
Db name cannot contain a dot, the server may apply more restrictions when an operation is run.
Parameter client
The MongoClient for the database.
Parameter databaseName
The name of the database this instance represents.
Parameter options
Optional settings for Db construction.
property bsonOptions
readonly bsonOptions: BSONSerializeOptions;
property databaseName
readonly databaseName: string;
property namespace
readonly namespace: string;
property options
readonly options: DbOptions;
property readConcern
readonly readConcern: ReadConcern;
property readPreference
readonly readPreference: ReadPreference;
The current readPreference of the Db. If not explicitly defined for this Db, will be inherited from the parent MongoClient
property secondaryOk
readonly secondaryOk: boolean;
Check if a secondary can be used (because the read preference is *not* set to primary)
property SYSTEM_COMMAND_COLLECTION
static SYSTEM_COMMAND_COLLECTION: string;
property SYSTEM_INDEX_COLLECTION
static SYSTEM_INDEX_COLLECTION: string;
property SYSTEM_JS_COLLECTION
static SYSTEM_JS_COLLECTION: string;
property SYSTEM_NAMESPACE_COLLECTION
static SYSTEM_NAMESPACE_COLLECTION: string;
property SYSTEM_PROFILE_COLLECTION
static SYSTEM_PROFILE_COLLECTION: string;
property SYSTEM_USER_COLLECTION
static SYSTEM_USER_COLLECTION: string;
property writeConcern
readonly writeConcern: WriteConcern;
method admin
admin: () => Admin;
Return the Admin db instance
method aggregate
aggregate: <T extends Document = Document>( pipeline?: Document[], options?: AggregateOptions) => AggregationCursor<T>;
Execute an aggregation framework pipeline against the database, needs MongoDB >= 3.6
Parameter pipeline
An array of aggregation stages to be executed
Parameter options
Optional settings for the command
method collection
collection: <TSchema extends Document = Document>( name: string, options?: CollectionOptions) => Collection<TSchema>;
Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.
Collection namespace validation is performed server-side.
Parameter name
the collection name we wish to access.
Returns
return the new Collection instance
method collections
collections: (options?: ListCollectionsOptions) => Promise<Collection[]>;
Fetch all collections for the current db.
Parameter options
Optional settings for the command
method command
command: (command: Document, options?: RunCommandOptions) => Promise<Document>;
Execute a command
Parameter command
The command to run
Parameter options
Optional settings for the command
Remarks
This command does not inherit options from the MongoClient.
The driver will ensure the following fields are attached to the command sent to the server: -
lsid
- sourced from an implicit session or options.session -$readPreference
- defaults to primary or can be configured by options.readPreference -$db
- sourced from the name of this databaseIf 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 TransactionOptionsAttaching any of the above fields to the command will have no effect as the driver will overwrite the value.
method createCollection
createCollection: <TSchema extends Document = Document>( name: string, options?: CreateCollectionOptions) => Promise<Collection<TSchema>>;
Create a new collection on a server with the specified options. Use this to create capped collections. More information about command options available at https://www.mongodb.com/docs/manual/reference/command/create/
Collection namespace validation is performed server-side.
Parameter name
The name of the collection to create
Parameter options
Optional settings for the command