Options
All
  • Public
  • Public/Protected
  • All
Menu

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

Hierarchy

Index

Constructors

Accessors

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

    Returns string

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

    Returns string

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

    Returns string

  • The current readConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns ReadConcern

  • The current readPreference of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns ReadPreference

  • The current writeConcern of the collection. If not explicitly defined for this collection, will be inherited from the parent DB

    Returns WriteConcern

  • The current index hint for the collection

    Returns Hint

  • The current index hint for the collection

    Parameters

    Returns void

  • Returns Logger

Methods

  • Perform a bulkWrite operation without a fluent API

    Legal operation types are

    • insertOne
    • replaceOne
    • updateOne
    • updateMany
    • deleteOne
    • deleteMany

    Please note that raw operations are no longer accepted as of driver version 4.0.

    If documents passed in do not contain the _id field, one will be added to each of the documents missing it by the driver, mutating the document. This behavior can be overridden by setting the forceServerObjectId flag.

    throws

    MongoDriverError if operations is not an array

    Parameters

    Returns Promise<BulkWriteResult>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<BulkWriteResult>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

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

    Returns Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • Fetches the first document that matches the filter

    Returns Promise<WithId<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<WithId<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<WithId<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • T = TSchema

    Returns Promise<T>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • T = TSchema

    Parameters

    Returns Promise<T>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • T = TSchema

    Parameters

    Returns Promise<T>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • T = TSchema

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • T = TSchema

    Parameters

    Returns void

  • Returns if the collection is a capped collection

    Returns Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • 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

    Returns Promise<string>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<string>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • 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 {@link 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

    Returns Promise<string[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<string[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • Drops an index from this collection.

    Parameters

    • indexName: string

      Name of the index to drop.

    Returns Promise<<internal>.Document>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<<internal>.Document>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

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

    Parameters

    Returns ListIndexesCursor

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

    Returns Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • 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

    Count: Behavior

    Returns Promise<number>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<number>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • 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]>[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • Key extends string | number | symbol

    Parameters

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

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • Key extends string | number | symbol

    Parameters

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

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • Key extends string | number | symbol

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • Key extends string | number | symbol

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Type Parameters

    • Key extends string | number | symbol

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    • key: string

    Returns Promise<any[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<any[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<any[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • 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

    Parameters

    Returns ChangeStream<TLocal, TChange>

  • 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

    Returns UnorderedBulkOperation

  • 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

    Returns OrderedBulkOperation

  • Get the db scoped logger

    Returns Logger

  • Inserts a single document or a 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.

    deprecated

    Use insertOne, insertMany or bulkWrite instead. Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void | Promise<InsertManyResult<TSchema>>

  • Updates documents.

    deprecated

    use updateOne, updateMany or bulkWrite. Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void | Promise<UpdateResult>

  • Remove documents.

    deprecated

    use deleteOne, deleteMany or bulkWrite. Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void | Promise<DeleteResult>

  • 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 {@link Collection#countDocuments| countDocuments}. To obtain an estimated count of all documents in the collection, use {@link Collection#estimatedDocumentCount| estimatedDocumentCount}.

    deprecated

    use {@link Collection#countDocuments| countDocuments} or {@link Collection#estimatedDocumentCount| estimatedDocumentCount} instead

    Returns Promise<number>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<number>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns Promise<number>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

    Parameters

    Returns void | Promise<number>

Generated using TypeDoc