Class Collection<TSchema>

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

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}!`);
}

Type Parameters

  • TSchema extends Document = Document

Hierarchy

  • Collection

Constructors

  • Type Parameters

    • TSchema extends Document = Document

    Returns Collection<TSchema>

Accessors

  • get bsonOptions(): BSONSerializeOptions
  • Returns BSONSerializeOptions

  • get collectionName(): string
  • The name of this collection

    Returns string

  • get dbName(): string
  • The name of the database this collection belongs to

    Returns string

  • get hint(): undefined | Hint
  • The current index hint for the collection

    Returns undefined | Hint

  • set hint(v: undefined | Hint): void
  • Parameters

    • v: undefined | Hint

    Returns void

  • get namespace(): string
  • The namespace of this collection, in the format ${this.dbName}.${this.collectionName}

    Returns string

  • get readConcern(): undefined | ReadConcern
  • The current readConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns undefined | ReadConcern

  • get readPreference(): undefined | ReadPreference
  • The current readPreference of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns undefined | ReadPreference

  • get writeConcern(): undefined | WriteConcern
  • The current writeConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns undefined | WriteConcern

Methods

  • Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2

    Type Parameters

    • T extends Document = Document

    Parameters

    • Optional pipeline: Document[]

      An array of aggregation pipelines to execute

    • Optional options: AggregateOptions

      Optional settings for the command

    Returns AggregationCursor<T>

  • 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.

    Throws

    MongoDriverError if operations is not an array

    Parameters

    • operations: AnyBulkWriteOperation<TSchema>[]

      Bulk operations to perform

    • Optional options: BulkWriteOptions

      Optional settings for the command

    Returns Promise<BulkWriteResult>

  • 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.

    Deprecated

    use Collection#countDocuments| countDocuments or Collection#estimatedDocumentCount| estimatedDocumentCount instead

    Parameters

    • Optional filter: Filter<TSchema>

      The filter for the count.

    • Optional options: CountOptions

      Optional settings for the command

    Returns Promise<number>

  • Creates an index on the db and collection collection.

    Example

    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' }])

    Parameters

    • indexSpec: IndexSpecification

      The field name or index specification to create an index for

    • Optional options: CreateIndexesOptions

      Optional settings for the command

    Returns 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 Collection#createIndex| createIndex, this function takes in raw index specifications. Index specifications are defined here.

    Example

    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'
    }
    ]);

    Parameters

    • indexSpecs: IndexDescription[]

      An array of index specifications to be created

    • Optional options: CreateIndexesOptions

      Optional settings for the command

    Returns Promise<string[]>

  • Delete multiple documents from a collection

    Parameters

    • Optional filter: Filter<TSchema>

      The filter used to select the documents to remove

    • Optional options: DeleteOptions

      Optional settings for the command

    Returns Promise<DeleteResult>

  • Delete a document from a collection

    Parameters

    • Optional filter: Filter<TSchema>

      The filter used to select the document to remove

    • Optional options: DeleteOptions

      Optional settings for the command

    Returns Promise<DeleteResult>

  • The distinct command returns a list of distinct values for the given key across a collection.

    Type Parameters

    • Key extends string | number | symbol

    Parameters

    • key: Key

      Field of the document to find distinct values for

    Returns Promise<Flatten<WithId<TSchema>[Key]>[]>

  • Type Parameters

    • Key extends string | number | symbol

    Parameters

    • key: Key
    • filter: Filter<TSchema>

    Returns Promise<Flatten<WithId<TSchema>[Key]>[]>

  • Type Parameters

    • Key extends string | number | symbol

    Parameters

    • key: Key
    • filter: Filter<TSchema>
    • options: CommandOperationOptions

    Returns Promise<Flatten<WithId<TSchema>[Key]>[]>

  • Parameters

    • key: string

    Returns Promise<any[]>

  • Parameters

    • key: string
    • filter: Filter<TSchema>

    Returns Promise<any[]>

  • Parameters

    • key: string
    • filter: Filter<TSchema>
    • options: CommandOperationOptions

    Returns Promise<any[]>

  • Drop the collection from the database, removing it permanently. New accesses will create a new collection.

    Parameters

    • Optional options: DropCollectionOptions

      Optional settings for the command

    Returns Promise<boolean>

  • Drops an index from this collection.

    Parameters

    • indexName: string

      Name of the index to drop.

    • Optional options: CommandOperationOptions

      Optional settings for the command

    Returns Promise<Document>

  • Drops all indexes from this collection.

    Parameters

    • Optional options: CommandOperationOptions

      Optional settings for the command

    Returns Promise<Document>

  • Gets an estimate of the count of documents in a collection using collection metadata. This will always run a count command on all server versions.

    due to an oversight in versions 5.0.0-5.0.8 of MongoDB, the count command, which estimatedDocumentCount uses in its implementation, was not included in v1 of the Stable API, and so users of the Stable API with estimatedDocumentCount are recommended to upgrade their server version to 5.0.9+ or set apiStrict: false to avoid encountering errors.

    See

    Behavior

    Parameters

    • Optional options: EstimatedDocumentCountOptions

      Optional settings for the command

    Returns Promise<number>

  • Creates a cursor for a filter that can be used to iterate over results from MongoDB

    Returns FindCursor<WithId<TSchema>>

  • Parameters

    • filter: Filter<TSchema>
    • Optional options: FindOptions<Document>

    Returns FindCursor<WithId<TSchema>>

  • Type Parameters

    • T extends Document

    Parameters

    • filter: Filter<TSchema>
    • Optional options: FindOptions<Document>

    Returns FindCursor<T>

  • Fetches the first document that matches the filter

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    • filter: Filter<TSchema>

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    • filter: Filter<TSchema>
    • options: FindOptions<Document>

    Returns Promise<null | WithId<TSchema>>

  • Type Parameters

    • T = TSchema

    Returns Promise<null | T>

  • Type Parameters

    • T = TSchema

    Parameters

    • filter: Filter<TSchema>

    Returns Promise<null | T>

  • Type Parameters

    • T = TSchema

    Parameters

    • filter: Filter<TSchema>
    • Optional options: FindOptions<Document>

    Returns Promise<null | T>

  • Find a document and delete it in one atomic operation. Requires a write lock for the duration of the operation.

    Parameters

    • filter: Filter<TSchema>

      The filter used to select the document to remove

    • Optional options: FindOneAndDeleteOptions

      Optional settings for the command

    Returns Promise<ModifyResult<TSchema>>

  • Find a document and replace it in one atomic operation. Requires a write lock for the duration of the operation.

    Parameters

    • filter: Filter<TSchema>

      The filter used to select the document to replace

    • replacement: WithoutId<TSchema>

      The Document that replaces the matching document

    • Optional options: FindOneAndReplaceOptions

      Optional settings for the command

    Returns Promise<ModifyResult<TSchema>>

  • Find a document and update it in one atomic operation. Requires a write lock for the duration of the operation.

    Parameters

    • filter: Filter<TSchema>

      The filter used to select the document to update

    • update: UpdateFilter<TSchema>

      Update operations to be performed on the document

    • Optional options: FindOneAndUpdateOptions

      Optional settings for the command

    Returns Promise<ModifyResult<TSchema>>

  • Checks if one or more indexes exist on the collection, fails on first non-existing index

    Parameters

    • indexes: string | string[]

      One or more index names to check.

    • Optional options: IndexInformationOptions

      Optional settings for the command

    Returns Promise<boolean>

  • Retrieves this collections index info.

    Parameters

    • Optional options: IndexInformationOptions

      Optional settings for the command

    Returns Promise<Document>

  • Retrieve all the indexes on the collection.

    Parameters

    • Optional options: IndexInformationOptions

      Optional settings for the command

    Returns Promise<Document[]>

  • 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.

    Parameters

    • Optional options: BulkWriteOptions

    Returns OrderedBulkOperation

  • 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.

    Parameters

    • Optional options: BulkWriteOptions

    Returns UnorderedBulkOperation

  • 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.

    Parameters

    • docs: OptionalUnlessRequiredId<TSchema>[]

      The documents to insert

    • Optional options: BulkWriteOptions

      Optional settings for the command

    Returns Promise<InsertManyResult<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.

    Parameters

    • doc: OptionalUnlessRequiredId<TSchema>

      The document to insert

    • Optional options: InsertOneOptions

      Optional settings for the command

    Returns Promise<InsertOneResult<TSchema>>

  • Returns if the collection is a capped collection

    Parameters

    • Optional options: OperationOptions

      Optional settings for the command

    Returns Promise<boolean>

  • Get the list of all indexes information for the collection.

    Parameters

    • Optional options: ListIndexesOptions

      Optional settings for the command

    Returns ListIndexesCursor

  • Returns the options of the collection.

    Parameters

    • Optional options: OperationOptions

      Optional settings for the command

    Returns Promise<Document>

  • Rename the collection.

    Remarks

    This operation does not inherit options from the Db or MongoClient.

    Parameters

    • newName: string

      New name of of the collection.

    • Optional options: RenameOptions

      Optional settings for the command

    Returns Promise<Collection<Document>>

  • Replace a document in a collection with another document

    Parameters

    • filter: Filter<TSchema>

      The filter used to select the document to replace

    • replacement: WithoutId<TSchema>

      The Document that replaces the matching document

    • Optional options: ReplaceOptions

      Optional settings for the command

    Returns Promise<Document | UpdateResult>

  • Get all the collection statistics.

    Parameters

    • Optional options: CollStatsOptions

      Optional settings for the command

    Returns Promise<CollStats>

  • Update multiple documents in a collection

    Parameters

    • filter: Filter<TSchema>

      The filter used to select the documents to update

    • update: UpdateFilter<TSchema>

      The update operations to be applied to the documents

    • Optional options: UpdateOptions

      Optional settings for the command

    Returns Promise<UpdateResult>

  • Update a single document in a collection

    Parameters

    • filter: Filter<TSchema>

      The filter used to select the document to update

    • update: UpdateFilter<TSchema> | Partial<TSchema>

      The update operations to be applied to the document

    • Optional options: UpdateOptions

      Optional settings for the command

    Returns Promise<UpdateResult>

  • Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.

    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

    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

    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);
    });

    Type Parameters

    • TLocal extends Document = TSchema

      Type of the data being detected by the change stream

    • TChange extends Document = ChangeStreamDocument<TLocal>

      Type of the whole change stream document emitted

    Parameters

    • Optional pipeline: Document[]

      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 options: ChangeStreamOptions

      Optional settings for the command

    Returns ChangeStream<TLocal, TChange>

Generated using TypeDoc