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/update/remove/find and other command operation on that MongoDB collection.Collection类是包含MongoDB集合的内部类,允许对该MongoDB集合执行插入、更新、删除、查找和其他命令操作。

COLLECTION Cannot directly be instantiated集合不能直接实例化

example
const MongoClient = require('mongodb').MongoClient;
const test = require('assert');
// Connection url
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'test';
// Connect using MongoClient
MongoClient.connect(url, function(err, client) {
  // Create a collection we want to drop later
  const col = client.db(dbName).collection('createIndexExample1');
  // Show that duplicate records got dropped
  col.find({}).toArray(function(err, items) {
    expect(err).to.not.exist;
    test.equal(4, items.length);
    client.close();
  });
});

(?<=)Type parameters类型参数

Hierarchy层级

  • Collection

Index索引

Constructors构造函数

constructor

Properties属性

s

internal

Accessors访问器

bsonOptions

collectionName

  • get collectionName(): string
  • The name of this collection此集合的名称

    Returns返回string

dbName

  • get dbName(): string
  • The name of the database this collection belongs to此集合所属的数据库的名称

    Returns返回string

hint

  • 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

logger

namespace

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

    Returns返回string

readConcern

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

    Returns返回undefined | ReadConcern

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

writeConcern

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

    Returns返回undefined | WriteConcern

Methods方法

aggregate

  • Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2针对集合执行聚合框架管道,需要MongoDB>=2.2

    Type parameters类型参数

    • T = TSchema

    Parameters参数

    • pipeline: Document[] = []

      An array of aggregation pipelines to execute要执行的聚合管道数组

    • Optional options: AggregateOptions

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

    Returns返回AggregationCursor<T>

bulkWrite

  • Perform a bulkWrite operation without a fluent API在没有fluent API的情况下执行批量写入操作

    Legal operation types are合法的操作类型包括

     { insertOne: { document: { a: 1 } } }
     { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
     { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
     { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} }
     { deleteOne: { filter: {c:1} } }
     { deleteMany: { filter: {c:1} } }
     { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true} }
    

    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>

  • Parameters参数

    Returns返回void

  • Parameters参数

    Returns返回Promise<BulkWriteResult>

  • Parameters参数

    Returns返回void

count

countDocuments

createIndex

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

  • Parameters参数

    Returns返回void

  • Parameters参数

    Returns返回Promise<string>

  • Parameters参数

    Returns返回void

createIndexes

  • 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.这里定义了索引规范。

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

  • Parameters参数

    Returns返回void

  • Parameters参数

    Returns返回Promise<string[]>

  • Parameters参数

    Returns返回void

deleteMany

deleteOne

distinct

drop

dropIndex

dropIndexes

estimatedDocumentCount

find

findOne

findOneAndDelete

findOneAndReplace

findOneAndUpdate

getLogger

indexExists

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

  • Parameters参数

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

    Returns返回void

  • Parameters参数

    Returns返回Promise<boolean>

  • Parameters参数

    Returns返回void

indexInformation

indexes

initializeOrderedBulkOp

  • 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

initializeUnorderedBulkOp

  • 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

insert

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

    Parameters参数

    • docs: OptionalId<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一个可选的回调,如果没有提供,将返回一个承诺

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

insertMany

  • 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参数

    • docs: OptionalId<TSchema>[]

      The documents to insert要插入的文件

    Returns返回Promise<InsertManyResult<TSchema>>

  • Parameters参数

    Returns返回void

  • Parameters参数

    Returns返回Promise<InsertManyResult<TSchema>>

  • Parameters参数

    Returns返回void

insertOne

  • Inserts a single document 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参数

    • doc: OptionalId<TSchema>

      The document to insert要插入的文档

    Returns返回Promise<InsertOneResult<TSchema>>

  • Parameters参数

    Returns返回void

  • Parameters参数

    Returns返回Promise<InsertOneResult<TSchema>>

  • Parameters参数

    Returns返回void

isCapped

listIndexes

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

    Parameters参数

    • Optional options: ListIndexesOptions

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

    Returns返回ListIndexesCursor

mapReduce

options

remove

  • Remove documents.删除文档。

    deprecated

    use deleteOne, deleteMany or bulkWrite使用deleteOne、deleteMany或bulkWrite

    Parameters参数

    • selector: Filter<TSchema>

      The selector for the update operation.更新操作的选择器。

    • options: DeleteOptions

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

    • callback: Callback<any>

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

    Returns返回void | Promise<DeleteResult>

rename

replaceOne

stats

update

  • Updates documents.更新文档。

    deprecated

    use updateOne, updateMany or bulkWrite使用updateOne、updateMany或bulkWrite

    Parameters参数

    • selector: Filter<TSchema>

      The selector 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一个可选的回调,如果没有提供,将返回一个承诺

    Returns返回void | Promise<UpdateResult>

updateMany

updateOne

watch

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

    since

    3.0.0

    Type parameters类型参数

    • TLocal = TSchema

    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>

Generated using TypeDoc使用TypeDoc生成