Options
All
  • Public
  • Public/Protected
  • All
Menu

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集执行插入/查找/更新/删除和其他命令操作。

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

Index索引

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 hint(): undefined | Hint
  • set hint(v: undefined | Hint): void
  • The current index hint for the collection集合的当前索引提示

    Returns 返回 undefined | Hint

  • The current index hint for the collection集合的当前索引提示

    Parameters参数

    • v: undefined | Hint

    Returns 返回 void

  • get namespace(): string
  • The namespace of this collection, in the format ${this.dbName}.${this.collectionName}此集合的命名空间,格式为${this.dbName}.${this.collectionName}

    Returns 返回 string

  • The current readConcern of the collection. 集合的当前readConcern。If not explicitly defined for this collection, will be inherited from the parent DB如果没有为此集合显式定义,将从父数据库继承

    Returns 返回 undefined | ReadConcern

  • The current readPreference of the collection. 集合的当前readPreferenceIf not explicitly defined for this collection, will be inherited from the parent DB如果没有为此集合显式定义,将从父数据库继承

    Returns 返回 undefined | ReadPreference

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

    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.请注意,自驱动程序版本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. 如果传入的文档不包含_id字段,则驱动程序将在缺少该字段的每个文档中添加一个字段,从而对文档进行修改。This behavior can be overridden by setting the forceServerObjectId flag.可以通过设置forceServerObjectId标志来覆盖此行为。

    throws

    MongoDriverError if operations is not an array如果操作不是数组,则抛出MongoDriverError

    Parameters参数

    Returns 返回 Promise<BulkWriteResult>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<BulkWriteResult>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    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请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<string>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • 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 Collection.createIndex, this function takes in raw index specifications. :与Collection.createIndex不同,此函数接受原始索引规范。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要创建的索引规范数组

    Returns 返回 Promise<string[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<string[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • The distinct command returns a list of distinct values for the given key across a collection.distinct命令返回集合中给定键的不同值列表。

    Type parameters类型参数

    • Key: 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请参阅mongodb-legacy获取迁移帮助

    Type parameters类型参数

    • Key: string | number | symbol

    Parameters参数

    Returns 返回 void

  • Type parameters类型参数

    • Key: string | number | symbol

    Parameters参数

    • key: Key
    • filter: Filter<TSchema>

    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请参阅mongodb-legacy获取迁移帮助

    Type parameters类型参数

    • Key: string | number | symbol

    Parameters参数

    Returns 返回 void

  • Type parameters类型参数

    • Key: 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请参阅mongodb-legacy获取迁移帮助

    Type parameters类型参数

    • Key: string | number | symbol

    Parameters参数

    Returns 返回 void

  • 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请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    • key: string
    • filter: Filter<TSchema>

    Returns 返回 Promise<any[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<any[]>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    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请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    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.这将始终在所有服务器版本上运行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以避免遇到错误。

    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请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<number>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Fetches the first document that matches the filter获取与筛选器匹配的第一个文档

    Returns 返回 Promise<null | WithId<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<null | WithId<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<null | WithId<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Type parameters类型参数

    • T = TSchema

    Returns 返回 Promise<null | T>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Type parameters类型参数

    • T = TSchema

    Parameters参数

    Returns 返回 void

  • Type parameters类型参数

    • T = TSchema

    Parameters参数

    Returns 返回 Promise<null | T>

  • Type parameters类型参数

    • T = TSchema

    Parameters参数

    Returns 返回 Promise<null | T>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Type parameters类型参数

    • T = TSchema

    Parameters参数

    Returns 返回 void

  • 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替换匹配文档的文档

    Returns 返回 Promise<ModifyResult<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<ModifyResult<TSchema>>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • indexExists(indexes: string | string[]): Promise<boolean>
  • indexExists(indexes: string | string[], callback: Callback<boolean>): void
  • indexExists(indexes: string | string[], options: IndexInformationOptions): Promise<boolean>
  • indexExists(indexes: string | string[], options: IndexInformationOptions, callback: Callback<boolean>): void
  • 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请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    • indexes: string | string[]
    • callback: Callback<boolean>

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • 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. 由于此传统实现中的已知限制,在调用此方法之前必须连接MongoClient。However, collection.bulkWrite() provides an equivalent API that does not require prior connecting.但是,collection.bulkWrite()提供了一个不需要事先连接的等效API。

    Parameters参数

    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. 由于此传统实现中的已知限制,在调用此方法之前必须连接MongoClient。However, collection.bulkWrite() provides an equivalent API that does not require prior connecting.但是,collection.bulkWrite()提供了一个不需要事先连接的等效API。

    Parameters参数

    Returns 返回 UnorderedBulkOperation

  • Inserts a single document or a 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标志来覆盖此行为。

    deprecated

    Use insertOne, insertMany or bulkWrite instead. 请改用insertOne、insertMany或bulkWrite。Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    • docs: OptionalUnlessRequiredId<TSchema>[]

      The documents to insert要插入的文档

    • options: BulkWriteOptions

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

    • callback: Callback<InsertManyResult<TSchema>>

      An optional callback, a Promise will be returned if none is provided一个可选回调,如果没有提供,则返回Promise

    Returns 返回 void | Promise<InsertManyResult<TSchema>>

  • 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请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Parameters参数

    Returns 返回 Promise<boolean>

  • deprecated

    Callbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    Returns 返回 void

  • Get the list of all indexes information for the collection.获取集合的所有索引信息的列表。

    Parameters参数

    • Optional options: ListIndexesOptions

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

    Returns 返回 ListIndexesCursor

  • Remove documents.删除文档。

    deprecated

    use deleteOne, deleteMany or bulkWrite. 使用deleteOnedeleteManybulkWriteCallbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    • filter: Filter<TSchema>

      The filter for the remove operation.用于删除操作的筛选器。

    • options: DeleteOptions

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

    • callback: Callback<any>

      An optional callback, a Promise will be returned if none is provided一个可选回调,如果没有提供,则返回Promise

    Returns 返回 void | Promise<DeleteResult>

  • Updates documents.更新文档。

    deprecated

    use updateOne, updateMany or bulkWrite. 使用updateOneupdateManybulkWriteCallbacks are deprecated and will be removed in the next major version. 回调已被弃用,将在下一个主要版本中删除。See mongodb-legacy for migration assistance请参阅mongodb-legacy获取迁移帮助

    Parameters参数

    • filter: Filter<TSchema>

      The filter for the update operation.更新操作的筛选器。

    • update: UpdateFilter<TSchema>

      The update operations to be applied to the documents要应用于文档的更新操作

    • options: UpdateOptions

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

    • callback: Callback<Document>

      An optional callback, a Promise will be returned if none is provided一个可选回调,如果没有提供,则返回Promise

    Returns 返回 void | 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: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 }>通过提供第一个参数,我可以将更改键入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);
    });

    Type parameters类型参数

    • TLocal: Document = TSchema

      Type of the data being detected by the change stream更改流检测到的数据类型

    • TChange: Document = ChangeStreamDocument<TLocal>

      Type of the whole change stream document emitted发出的整个变更流文档的类型

    Parameters参数

    • pipeline: Document[] = []

      An array of aggregation 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>

Generated using TypeDoc