Class Db

The Db class is a class that represents a MongoDB Database.Db类是一个表示MongoDB数据库的类。

import { MongoClient } from 'mongodb';

interface Pet {
name: string;
kind: 'dog' | 'cat' | 'fish';
}

const client = new MongoClient('mongodb://localhost:27017');
const db = client.db();

// Create a collection that validates our union
await db.createCollection<Pet>('pets', {
validator: { $expr: { $in: ['$kind', ['dog', 'cat', 'fish']] } }
})

Constructors构造函数

  • Creates a new Db instance.创建一个新的Db实例。

    Db name cannot contain a dot, the server may apply more restrictions when an operation is run.Db名称不能包含点,服务器在运行操作时可能会应用更多限制。

    Parameters参数

    • client: MongoClient

      The MongoClient for the database.数据库的MongoClient。

    • databaseName: string

      The name of the database this instance represents.此实例所代表的数据库的名称。

    • Optionaloptions: DbOptions

      Optional settings for Db construction.Db构造的可选设置。

    Returns 返回Db

Properties属性

client: MongoClient

Gets the MongoClient associated with the Db.获取与数据库关联的MongoClient。

SYSTEM_COMMAND_COLLECTION: string = CONSTANTS.SYSTEM_COMMAND_COLLECTION
SYSTEM_INDEX_COLLECTION: string = CONSTANTS.SYSTEM_INDEX_COLLECTION
SYSTEM_JS_COLLECTION: string = CONSTANTS.SYSTEM_JS_COLLECTION
SYSTEM_NAMESPACE_COLLECTION: string = CONSTANTS.SYSTEM_NAMESPACE_COLLECTION
SYSTEM_PROFILE_COLLECTION: string = CONSTANTS.SYSTEM_PROFILE_COLLECTION
SYSTEM_USER_COLLECTION: string = CONSTANTS.SYSTEM_USER_COLLECTION

Accessors访问器

  • get databaseName(): string
  • Returns 返回string

  • get namespace(): string
  • Returns 返回string

  • get readPreference(): ReadPreference
  • The current readPreference of the Db. If not explicitly defined for this Db, will be inherited from the parent MongoClientDb的当前readPreference。如果没有为此数据库明确定义,将从父级MongoClient继承

    Returns 返回ReadPreference

  • get secondaryOk(): boolean
  • Check if a secondary can be used (because the read preference is not set to primary)检查是否可以使用辅助选项(因为读取首选项未设置为主选项)

    Returns 返回boolean

  • get timeoutMS(): undefined | number
  • Returns 返回undefined | number

Methods方法

  • Execute an aggregation framework pipeline against the database.对数据库执行聚合框架管道。

    Type Parameters类型参数

    Parameters参数

    • pipeline: Document[] = []

      An array of aggregation stages to be executed要执行的一系列聚合阶段

    • Optionaloptions: AggregateOptions

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

    Returns 返回AggregationCursor<T>

  • Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.返回对MongoDB集合的引用。如果它不存在,它将隐式创建。

    Collection namespace validation is performed server-side.集合命名空间验证在服务器端执行。

    Type Parameters类型参数

    Parameters参数

    • name: string

      the collection name we wish to access.我们希望访问的集合名称。

    • options: CollectionOptions = {}

    Returns 返回Collection<TSchema>

    return the new Collection instance返回新的Collection实例

  • Execute a command执行命令

    Parameters参数

    Returns 返回Promise<Document>

    This command does not inherit options from the MongoClient.此命令不继承MongoClient的选项。

    The driver will ensure the following fields are attached to the command sent to the server:驱动程序将确保以下字段附加到发送到服务器的命令中:

    • lsid - sourced from an implicit session or options.session来源于隐式会话或options.session
    • $readPreference - defaults to primary or can be configured by options.readPreference默认设置为主选项,也可以通过options.readPreference进行配置
    • $db - sourced from the name of this database来源于此数据库的名称

    If the client has a serverApi setting:如果客户端具有serverApi设置:

    • apiVersion
    • apiStrict
    • apiDeprecationErrors

    When in a transaction:在事务中:

    • readConcern - sourced from readConcern set on the TransactionOptions来源于TransactionOptions上的readConcern
    • writeConcern - sourced from writeConcern set on the TransactionOptions来源于TransactionOptions上的writeConcern

    Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.将上述任何字段附加到命令都将无效,因为驱动程序将覆盖该值。

  • Create a new collection on a server with the specified options. Use this to create capped collections. 使用指定的选项在服务器上创建新集合。使用此选项创建上限集合。More information about command options available at 有关可用命令选项的更多信息,请访问/v8.3/reference/command/create/

    Collection namespace validation is performed server-side.集合命名空间验证在服务器端执行。

    Type Parameters类型参数

    Parameters参数

    • name: string

      The name of the collection to create要创建的集合的名称

    • Optionaloptions: CreateCollectionOptions

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

    Returns 返回Promise<Collection<TSchema>>

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

    Parameters参数

    • name: string

      Name of the collection to create the index on.要在其上创建索引的集合的名称。

    • indexSpec: IndexSpecification

      Specify the field to index, or an index specification指定要索引的字段或索引规范

    • Optionaloptions: CreateIndexesOptions

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

    Returns 返回Promise<string>

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

    Parameters参数

    • name: string

      Name of collection to drop要删除的集合名称

    • Optionaloptions: DropCollectionOptions

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

    Returns 返回Promise<boolean>

  • Drop a database, removing it permanently from the server.删除数据库,将其从服务器中永久删除。

    Parameters参数

    Returns 返回Promise<boolean>

  • Retrieve the current profiling Level for MongoDB检索MongoDB的当前分析级别

    Parameters参数

    Returns 返回Promise<string>

  • Remove a user from a database从数据库中删除用户

    Parameters参数

    • username: string

      The username to remove要删除的用户名

    • Optionaloptions: RemoveUserOptions

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

    Returns 返回Promise<boolean>

  • Rename a collection.重命名集合。

    Type Parameters

    Parameters参数

    • fromCollection: string

      Name of current collection to rename要重命名的当前集合的名称

    • toCollection: string

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

    • Optionaloptions: RenameOptions

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

    Returns 返回Promise<Collection<TSchema>>

    This operation does not inherit options from the MongoClient.此操作不继承MongoClient的选项。

  • A low level cursor API providing basic driver functionality:提供基本驱动程序功能的低级游标API:

    • ClientSession management管理
    • ReadPreference for server selectionReadPreference用于服务器选择
    • Running getMores automatically when a local batch is exhausted当本地批处理耗尽时自动运行getMores

    Parameters参数

    • command: Document

      The command that will start a cursor on the server.将在服务器上启动游标的命令。

    • Optionaloptions: RunCursorCommandOptions

      Configurations for running the command, bson options will apply to getMores运行命令的配置,bson选项将应用于getMores

    Returns 返回RunCommandCursor

  • Set the current profiling level of MongoDB设置MongoDB的当前分析级别

    Parameters参数

    • level: ProfilingLevel

      The new profiling level (off, slow_only, all).新的分析级别(关闭、仅限慢速、全部)。

    • Optionaloptions: SetProfilingLevelOptions

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

    Returns 返回Promise<ProfilingLevel>

  • Get all the db statistics.

    Parameters参数

    • Optionaloptions: DbStatsOptions

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

    Returns 返回Promise<Document>

  • Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this database. Will ignore all changes to system collections.创建新的更改流,观察此数据库中的新更改(插入、更新、替换、删除和无效)。将忽略对系统集合的所有更改。

    Type Parameters类型参数

    • TSchema extends Document = Document

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

    • TChange extends Document = ChangeStreamDocument<TSchema>

      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<TSchema, TChange>

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

    • The first is to provide the schema that may be defined for all the collections within this database第一个是提供可以为该数据库中的所有集合定义的模式
    • 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

    In iterator mode, if a next() call throws a timeout error, it will attempt to resume the change stream. The next call can just be retried after this succeeds.在迭代器模式下,如果next()调用抛出超时错误,它将尝试恢复更改流。此操作成功后,可以重试下一个调用。

    const changeStream = collection.watch([], { timeoutMS: 100 });
    try {
    await changeStream.next();
    } catch (e) {
    if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
    await changeStream.next();
    }
    throw e;
    }

    In emitter mode, if the change stream goes timeoutMS without emitting a change event, it will emit an error event that returns a MongoOperationTimeoutError, but will not close the change stream unless the resume attempt fails. There is no need to re-establish change listeners as this will automatically continue emitting change events once the resume attempt completes.在发射器模式下,如果更改流过了timeoutMS而不发出更改事件,它将发出一个错误事件,返回MongoOperationTimeoutError,但除非恢复尝试失败,否则不会关闭更改流。无需重新建立更改侦听器,因为一旦恢复尝试完成,它将自动继续发出更改事件。

    const changeStream = collection.watch([], { timeoutMS: 100 });
    changeStream.on('change', console.log);
    changeStream.on('error', e => {
    if (e instanceof MongoOperationTimeoutError && !changeStream.closed) {
    // do nothing
    } else {
    changeStream.close();
    }
    });