API 参考
    正在准备搜索索引...

    类 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

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

    类型参数

    索引

    构造函数

    访问器

    • get bsonOptions(): BSONSerializeOptions

      返回 BSONSerializeOptions

    • get collectionName(): string

      The name of this collection

      返回 string

    • get dbName(): string

      The name of the database this collection belongs to

      返回 string

    • get hint(): undefined | Hint

      The current index hint for the collection

      返回 undefined | Hint

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

      参数

      返回 void

    • get namespace(): string

      The namespace of this collection, in the format ${this.dbName}.${this.collectionName}

      返回 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

      返回 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

      返回 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

      返回 undefined | WriteConcern

    方法

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

      类型参数

      参数

      • 可选pipeline: Document[]

        An array of aggregation pipelines to execute

      • 可选options: AggregateOptions

        Optional settings for the command

      返回 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.

      参数

      返回 Promise<BulkWriteResult>

      MongoDriverError if operations is not an array

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

      参数

      返回 Promise<number>

      use countDocuments or estimatedDocumentCount instead

    • Creates an index on the db and collection collection.

      参数

      返回 Promise<string>

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

      参数

      返回 Promise<string[]>

      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'
      }
      ]);
    • Delete multiple documents from a collection

      参数

      • 可选filter: Filter<TSchema>

        The filter used to select the documents to remove

      • 可选options: DeleteOptions

        Optional settings for the command

      返回 Promise<DeleteResult>

    • Delete a document from a collection

      参数

      • 可选filter: Filter<TSchema>

        The filter used to select the document to remove

      • 可选options: DeleteOptions

        Optional settings for the command

      返回 Promise<DeleteResult>

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

      类型参数

      • Key extends string | number | symbol

      参数

      • key: Key

        Field of the document to find distinct values for

      返回 Promise<Flatten<WithId<TSchema>[Key]>[]>

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

      类型参数

      • Key extends string | number | symbol

      参数

      • key: Key

        Field of the document to find distinct values for

      • filter: Filter<TSchema>

        The filter for filtering the set of documents to which we apply the distinct filter.

      返回 Promise<Flatten<WithId<TSchema>[Key]>[]>

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

      类型参数

      • Key extends string | number | symbol

      参数

      • key: Key

        Field of the document to find distinct values for

      • filter: Filter<TSchema>

        The filter for filtering the set of documents to which we apply the distinct filter.

      • options: CommandOperationOptions

        Optional settings for the command

      返回 Promise<Flatten<WithId<TSchema>[Key]>[]>

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

      参数

      • key: string

        Field of the document to find distinct values for

      返回 Promise<any[]>

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

      参数

      • key: string

        Field of the document to find distinct values for

      • filter: Filter<TSchema>

        The filter for filtering the set of documents to which we apply the distinct filter.

      返回 Promise<any[]>

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

      参数

      • key: string

        Field of the document to find distinct values for

      • filter: Filter<TSchema>

        The filter for filtering the set of documents to which we apply the distinct filter.

      • options: CommandOperationOptions

        Optional settings for the command

      返回 Promise<any[]>

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

      参数

      返回 Promise<boolean>

    • Drops an index from this collection.

      参数

      • indexName: string

        Name of the index to drop.

      • 可选options: CommandOperationOptions

        Optional settings for the command

      返回 Promise<Document>

    • Drops all indexes from this collection.

      参数

      返回 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.

      参数

      返回 Promise<number>

      Behavior

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

      返回 FindCursor<WithId<TSchema>>

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

      参数

      返回 FindCursor<WithId<TSchema>>

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

      类型参数

      参数

      返回 FindCursor<T>

    • Fetches the first document that matches the filter

      返回 Promise<null | WithId<TSchema>>

    • Fetches the first document that matches the filter

      参数

      返回 Promise<null | WithId<TSchema>>

    • Fetches the first document that matches the filter

      参数

      返回 Promise<null | WithId<TSchema>>

    • Fetches the first document that matches the filter

      类型参数

      返回 Promise<null | T>

    • Fetches the first document that matches the filter

      类型参数

      参数

      返回 Promise<null | T>

    • Fetches the first document that matches the filter

      类型参数

      参数

      返回 Promise<null | T>

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

      参数

      返回 Promise<null | ModifyResult<TSchema>>

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

      参数

      返回 Promise<null | ModifyResult<TSchema>>

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

      参数

      返回 Promise<null | ModifyResult<TSchema>>

    • Retrieve all the indexes on the collection.

      参数

      返回 Promise<Document[]>

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

      参数

      • indexes: string | string[]

        One or more index names to check.

      • 可选options: IndexInformationOptions

        Optional settings for the command

      返回 Promise<boolean>

    • Retrieves this collections index info.

      参数

      返回 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.

      参数

      返回 OrderedBulkOperation

      MongoNotConnectedError

      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.

    • Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.

      参数

      返回 UnorderedBulkOperation

      MongoNotConnectedError

      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.

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

      参数

      返回 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.

      参数

      返回 Promise<InsertOneResult<TSchema>>

    • Returns if the collection is a capped collection

      参数

      返回 Promise<boolean>

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

      参数

      返回 ListIndexesCursor

    • Returns the options of the collection.

      参数

      返回 Promise<Document>

    • Rename the collection.

      参数

      • newName: string

        New name of of the collection.

      • 可选options: RenameOptions

        Optional settings for the command

      返回 Promise<Collection<Document>>

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

    • Replace a document in a collection with another document

      参数

      • filter: Filter<TSchema>

        The filter used to select the document to replace

      • replacement: WithoutId<TSchema>

        The Document that replaces the matching document

      • 可选options: ReplaceOptions

        Optional settings for the command

      返回 Promise<Document | UpdateResult>

    • Get all the collection statistics.

      参数

      返回 Promise<CollStats>

    • Update multiple documents in a collection

      参数

      返回 Promise<UpdateResult>

    • Update a single document in a collection

      参数

      返回 Promise<UpdateResult>

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

      类型参数

      参数

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

      • 可选options: ChangeStreamOptions

        Optional settings for the command

      返回 ChangeStream<TLocal, TChange>

      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

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