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类是一个内部类,它包含了一个MongoDB集合,允许对该MongoDB集合执行insert/find/update/delete和其他命令操作。

COLLECTION Cannot directly be instantiatedCOLLECTION不能直接实例化

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

  • Collection

Accessors

  • 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 namespace(): string
  • The namespace of this collection, in the format ${this.dbName}.${this.collectionName}集合的命名空间,格式为${this.dbName}.${this.collectionName}

    Returns string

  • get readConcern(): undefined | ReadConcern
  • The current readConcern of the collection. 集合的当前readConcernIf 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集合的当前readPreference。如果没有为此集合明确定义,则将从父数据库继承

    Returns undefined | ReadPreference

  • get writeConcern(): undefined | WriteConcern
  • The current writeConcern of the collection. 集合的当前writeConcernIf 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针对集合执行聚合框架管道,需要MongoDB>=2.2

    Type Parameters

    Parameters

    • 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在没有fluent API的情况下执行bulkWrite操作

    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. 如果传入的文档不包含_id字段,则驱动程序将向缺少该字段的每个文档添加一个字段,从而使文档发生变化。This behavior can be overridden by setting the forceServerObjectId flag.可以通过设置forceServerObjectId标志来覆盖此行为。

    Parameters

    • operations: AnyBulkWriteOperation<TSchema>[]

      Bulk operations to perform要执行的批量操作

    • Optional options: BulkWriteOptions

      Optional settings for the command命令的可选设置

    Returns Promise<BulkWriteResult>

    Throws

    MongoDriverError if operations is not an arrayMongoDriverError如果操作不是数组

  • 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.此方法已被弃用,因为它无法提供集合中文档的准确计数。若要获得集合中文档的准确计数,请使用countDocuments To obtain an estimated count of all documents in the collection, use estimatedDocumentCount.若要获取集合中所有文档的估计计数,请使用estimatedDocumentCount

    Parameters

    • filter: Filter<TSchema> = {}

      The filter for the count.计数的筛选器。

    • options: CountOptions = {}

      Optional settings for the command命令的可选设置

    Returns Promise<number>

  • Creates an index on the db and collection collection.在数据库和集合集合上创建索引。

    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>

    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' }])
  • Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher. 在集合中创建多个索引,此方法仅适用于MongoDB 2.6或更高版本。Earlier version of MongoDB will throw a command not supported error.早期版本的MongoDB将抛出一个不支持的命令错误。

    Note: Unlike createIndex, this function takes in raw index specifications.:与createIndex不同,此函数接受原始索引规范。Index specifications are defined here.此处定义了索引规范。

    Parameters

    • indexSpecs: IndexDescription[]

      An array of index specifications to be created要创建的索引规范数组

    • Optional options: CreateIndexesOptions

      Optional settings for the command命令的可选设置

    Returns Promise<string[]>

    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'
    }
    ]);
  • Creates a single search index for the collection.为集合创建单个搜索索引。

    Parameters

    • description: SearchIndexDescription

      The index description for the new search index.新搜索索引的索引描述。

    Returns Promise<string>

    A promise that resolves to the name of the new search index.解析为新搜索索引名称的promise。

    Remarks

    Only available when used against a 7.0+ Atlas cluster.仅在针对7.0以上Atlas群集使用时可用。

  • Creates multiple search indexes for the current collection.为当前集合创建多个搜索索引。

    Parameters

    • descriptions: SearchIndexDescription[]

      An array of SearchIndexDescriptions for the new search indexes.新搜索索引的SearchIndexDescription的数组。

    Returns Promise<string[]>

    A promise that resolves to an array of the newly created search index names.解析为新创建的搜索索引名称的数组的promise。

    Remarks

    Only available when used against a 7.0+ Atlas cluster.仅在针对7.0以上Atlas群集使用时可用。

  • Delete multiple documents from a collection从集合中删除多个文档

    Parameters

    • filter: Filter<TSchema> = {}

      The filter used to select the documents to remove用于选择要删除的文档的筛选器

    • options: DeleteOptions = {}

      Optional settings for the command命令的可选设置

    Returns Promise<DeleteResult>

  • Delete a document from a collection从集合中删除文档

    Parameters

    • filter: Filter<TSchema> = {}

      The filter used to select the document to remove用于选择要删除的文档的筛选器

    • 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.distinct命令返回集合中给定键的不同值列表。

    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

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

  • Parameters

    • key: string

    Returns Promise<any[]>

  • Parameters

    • key: string
    • filter: Filter<TSchema>

    Returns Promise<any[]>

  • Parameters

    Returns Promise<any[]>

  • Drop the collection from the database, removing it permanently. New accesses will create a new collection.从数据库中删除集合,并将其永久删除。新的访问将创建一个新的集合。

    Parameters

    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

    Returns Promise<boolean>

  • Deletes a search index by index name.按索引名称删除搜索索引。

    Parameters

    • name: string

      The name of the search index to be deleted.要删除的搜索索引的名称。

    Returns Promise<void>

    Remarks

    Only available when used against a 7.0+ Atlas cluster.仅在针对7.0以上Atlas群集使用时可用。

  • 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.这将始终在所有服务器版本上运行count命令。

    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.由于MongoDB 5.0.0-5.0.8版本中的一个疏忽,estimatedDocumentCount在其实现中使用的count命令未包含在Stable API的v1中,因此建议使用estimatedDocumentCount的Stable API用户将其服务器版本升级到5.0.9+或设置apiStrict:false以避免出现错误。

    Parameters

    Returns Promise<number>

  • 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用于选择要删除的文档的筛选器

    • options: FindOneAndDeleteOptions & {
          includeResultMetadata: true;
      }

      Optional settings for the command命令的可选设置

    Returns Promise<ModifyResult<TSchema>>

  • Parameters

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    Returns Promise<null | WithId<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替换匹配文档的文档

    • options: FindOneAndReplaceOptions & {
          includeResultMetadata: true;
      }

      Optional settings for the command命令的可选设置

    Returns Promise<ModifyResult<TSchema>>

  • Parameters

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    Returns Promise<null | WithId<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更新要对文档执行的操作

    • options: FindOneAndUpdateOptions & {
          includeResultMetadata: true;
      }

      Optional settings for the command命令的可选设置

    Returns Promise<ModifyResult<TSchema>>

  • Parameters

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    Returns Promise<null | WithId<TSchema>>

  • Parameters

    Returns Promise<null | WithId<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>

  • 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.启动按顺序大容量写入操作。操作将按添加顺序串行执行,为类型中的每个开关创建一个新操作。

    Parameters

    Returns OrderedBulkOperation

    Throws

    MongoNotConnectedError

    Remarks

    NOTE: MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.由于此遗留实现中的已知限制,在调用此方法之前必须连接MongoClient。 However, collection.bulkWrite() provides an equivalent API that does not require prior connecting.但是,collection.bulkWrite()提供了一个等效的API,不需要预先连接。

  • Initiate an Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.启动无序批量写入操作。所有操作都将被缓冲到无序执行的insert/update/remove命令中。

    Parameters

    Returns UnorderedBulkOperation

    Throws

    MongoNotConnectedError

    Remarks

    NOTE: MongoClient must be connected prior to calling this method due to a known limitation in this legacy implementation.由于此遗留实现中的已知限制,在调用此方法之前必须连接MongoClient。 However, collection.bulkWrite() provides an equivalent API that does not require prior connecting.但是,collection.bulkWrite()提供了一个等效的API,不需要预先连接。

  • Inserts an array of documents into MongoDB. 在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. 如果传入的文档不包含_id字段,则驱动程序将向缺少该字段的每个文档添加一个字段,从而使文档发生变化。This behavior can be overridden by setting the forceServerObjectId flag.可以通过设置forceServerObjectId标志来覆盖此行为。

    Parameters

    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.在MongoDB中插入一个文档。如果传入的文档不包含_id字段,则驱动程序将向缺少该字段的每个文档添加一个字段,从而使文档发生变化。可以通过设置forceServerObjectId标志来覆盖此行为。

    Parameters

    Returns Promise<InsertOneResult<TSchema>>

  • Returns if the collection is a capped collection如果集合是封顶集合,则返回true

    Parameters

    • Optional options: OperationOptions

      Optional settings for the command命令的可选设置

    Returns Promise<boolean>

  • Returns all search indexes for the current collection.返回当前集合的所有搜索索引。

    Parameters

    • Optional options: AggregateOptions

      The options for the list indexes operation.列表索引操作的选项。

    Returns ListSearchIndexesCursor

    Remarks

    Only available when used against a 7.0+ Atlas cluster.仅在针对7.0以上Atlas群集使用时可用。

  • Returns all search indexes for the current collection.返回当前集合的所有搜索索引。

    Parameters

    • name: string

      The name of the index to search for. Only indexes with matching index names will be returned.要搜索的索引的名称。将只返回具有匹配索引名称的索引。

    • Optional options: AggregateOptions

      The options for the list indexes operation.列表索引操作的选项。

    Returns ListSearchIndexesCursor

    Remarks

    Only available when used against a 7.0+ Atlas cluster.仅在针对7.0以上Atlas群集使用时可用。

  • Rename the collection.重命名集合。

    Parameters

    • newName: string

      New name of of the collection.集合的新名称。

    • Optional options: RenameOptions

      Optional settings for the command命令的可选设置

    Returns Promise<Collection<Document>>

    Remarks

    This operation does not inherit options from the Db or MongoClient.此操作不会从Db或MongoClient继承选项。

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

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

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

  • Updates a search index by replacing the existing index definition with the provided definition.通过用提供的定义替换现有索引定义来更新搜索索引。

    Parameters

    • name: string

      The name of the search index to update.要更新的搜索索引的名称。

    • definition: Document

      The new search index definition.新的搜索索引定义。

    Returns Promise<void>

    Remarks

    Only available when used against a 7.0+ Atlas cluster.仅在针对7.0以上Atlas群集使用时可用。

  • Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this collection.创建一个新的更改流,监视此集合中的新更改(插入、更新、替换、删除和无效)。

    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

    • 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.一组管道阶段,通过这些阶段传递更改流文档。这允许筛选(使用$match)和操作变更流文档。

    • options: ChangeStreamOptions = {}

      Optional settings for the command命令的可选设置

    Returns ChangeStream<TLocal, TChange>

    Remarks

    watch() accepts two generic arguments for distinct use cases:watch()为不同的用例接受两个泛型参数:

    • 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第二种是完全覆盖变更流文档的形状,如果没有提供,则类型将默认为第一个参数的ChangeStreamDocument

    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.在这里,我们使用了一个管道,让MongoDB筛选器只用于插入更改并添加注释。No need start from scratch on the ChangeStreamInsertDocument type!ChangeStreamInsertDocument类型无需从头开始!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);
    });

Generated using TypeDoc