The name of this collection
The name of the database this collection belongs to
The namespace of this collection, in the format ${this.dbName}.${this.collectionName}
The current readConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB
The current readPreference of the collection. If not explicitly defined for this collection, will be inherited from the parent DB
The current writeConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB
Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
An array of aggregation pipelines to execute
Optional
options: AggregateOptionsOptional settings for the command
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.
Bulk operations to perform
Optional
options: BulkWriteOptionsOptional settings for the command
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 Collection#countDocuments| countDocuments. To obtain an estimated count of all documents in the collection, use Collection#estimatedDocumentCount| estimatedDocumentCount.
The filter for the count.
Optional settings for the command
Gets the number of documents matching the filter. For a fast count of the total documents in a collection see Collection#estimatedDocumentCount| estimatedDocumentCount. Note: When migrating from Collection#count| count to Collection#countDocuments| countDocuments the following query operators must be replaced:
Operator | Replacement |
---|---|
$where |
$expr |
$near |
$geoWithin with $center |
$nearSphere |
$geoWithin with $centerSphere |
The filter for the count
Optional settings for the command
Creates an index on the db and collection collection.
The field name or index specification to create an index for
Optional
options: CreateIndexesOptionsOptional settings for the command
const collection = client.db('foo').collection('bar');
await collection.createIndex({ a: 1, b: -1 });
// Alternate syntax for { c: 1, d: -1 } that ensures order of indexes
await collection.createIndex([ [c, 1], [d, -1] ]);
// Equivalent to { e: 1 }
await collection.createIndex('e');
// Equivalent to { f: 1, g: 1 }
await collection.createIndex(['f', 'g'])
// Equivalent to { h: 1, i: -1 }
await collection.createIndex([ { h: 1 }, { i: -1 } ]);
// Equivalent to { j: 1, k: -1, l: 2d }
await collection.createIndex(['j', ['k', -1], { l: '2d' }])
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 Collection#createIndex| createIndex, this function takes in raw index specifications. Index specifications are defined here.
An array of index specifications to be created
Optional
options: CreateIndexesOptionsOptional settings for the command
Creates a single search index for the collection.
The index description for the new search index.
A promise that resolves to the name of the new search index.
Creates multiple search indexes for the current collection.
An array of SearchIndexDescription
s for the new search indexes.
A promise that resolves to an array of the newly created search index names.
Delete multiple documents from a collection
The filter used to select the documents to remove
Optional settings for the command
Delete a document from a collection
The filter used to select the document to remove
Optional settings for the command
The distinct command returns a list of distinct values for the given key across a collection.
Field of the document to find distinct values for
Drop the collection from the database, removing it permanently. New accesses will create a new collection.
Optional
options: DropCollectionOptionsOptional settings for the command
Drops an index from this collection.
Name of the index to drop.
Optional
options: CommandOperationOptionsOptional settings for the command
Drops all indexes from this collection.
Optional
options: CommandOperationOptionsOptional settings for the command
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.
Optional
options: EstimatedDocumentCountOptionsOptional settings for the command
Creates a cursor for a filter that can be used to iterate over results from MongoDB
Optional
options: FindOptions<Document>Optional
options: FindOptions<Document>Fetches the first document that matches the filter
Optional
options: Omit<FindOptions<Document>, "timeoutMode">Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.
The filter used to select the document to remove
Optional settings for the command
Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.
The filter used to select the document to replace
The Document that replaces the matching document
Optional settings for the command
Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.
The filter used to select the document to update
Update operations to be performed on the document
Optional settings for the command
Retrieve all the indexes on the collection.
Optional settings for the command
Optional
options: ListIndexesOptionsChecks if one or more indexes exist on the collection, fails on first non-existing index
One or more index names to check.
Optional
options: ListIndexesOptionsOptional settings for the command
Retrieves this collections index info.
Optional settings for the command
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.
Optional
options: BulkWriteOptionsInitiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Optional
options: BulkWriteOptionsInserts 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.
The documents to insert
Optional
options: BulkWriteOptionsOptional settings for the command
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.
The document to insert
Optional
options: InsertOneOptionsOptional settings for the command
Returns if the collection is a capped collection
Optional
options: OperationOptionsOptional settings for the command
Get the list of all indexes information for the collection.
Optional
options: ListIndexesOptionsOptional settings for the command
Returns all search indexes for the current collection.
Optional
options: ListSearchIndexesOptionsThe options for the list indexes operation.
Returns all search indexes for the current collection.
The name of the index to search for. Only indexes with matching index names will be returned.
Optional
options: ListSearchIndexesOptionsThe options for the list indexes operation.
Returns the options of the collection.
Optional
options: OperationOptionsOptional settings for the command
Rename the collection.
New name of of the collection.
Optional
options: RenameOptionsOptional settings for the command
Replace a document in a collection with another document
The filter used to select the document to replace
The Document that replaces the matching document
Optional
options: ReplaceOptionsOptional settings for the command
Update multiple documents in a collection
The value of update
can be either:
The filter used to select the document to update
The modifications to apply
Optional
options: UpdateOptionsOptional settings for the command
Update a single document in a collection
The value of update
can be either:
The filter used to select the document to update
The modifications to apply
Optional
options: UpdateOptionsOptional settings for the command
Updates a search index by replacing the existing index definition with the provided definition.
The name of the search index to update.
The new search index definition.
Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.
Type of the data being detected by the change stream
Type of the whole change stream document emitted
An array of pipeline stages through which to pass change stream documents. This allows for filtering (using $match) and manipulating the change stream documents.
Optional settings for the command
watch() accepts two generic arguments for distinct use cases:
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)));
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);
});
In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream. The next call can just be retried after this succeeds.
const changeStream = collection.watch([], { timeoutMS: 100 });
try {
await changeStream.next();
} catch (e) {
if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
await changeStream.next();
}
throw e;
}
In emitter mode, if the change stream goes timeoutMS
without emitting a change event, it will
emit an error event that returns a MongoOperationTimeoutError, but will not close the change
stream unless the resume attempt fails. There is no need to re-establish change listeners as
this will automatically continue emitting change events once the resume attempt completes.
const changeStream = collection.watch([], { timeoutMS: 100 });
changeStream.on('change', console.log);
changeStream.on('error', e => {
if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
// do nothing
} else {
changeStream.close();
}
});
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