Class Db

The Db class is a class that represents a MongoDB Database.

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 name cannot contain a dot, the server may apply more restrictions when an operation is run.

    Parameters

    • client: MongoClient

      The MongoClient for the database.

    • databaseName: string

      The name of the database this instance represents.

    • Optionaloptions: DbOptions

      Optional settings for Db construction.

    Returns Db

Properties

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 readPreference(): ReadPreference
  • The current readPreference of the Db. If not explicitly defined for this Db, will be inherited from the parent 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

  • Returns a reference to a MongoDB Collection. If it does not exist it will be created implicitly.

    Collection namespace validation is performed server-side.

    Type Parameters

    Parameters

    Returns Collection<TSchema>

    return the new Collection instance

  • Execute a command

    Parameters

    Returns Promise<Document>

    This command does not inherit options from the 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
    • $readPreference - defaults to primary or can be configured by options.readPreference
    • $db - sourced from the name of this database

    If the client has a serverApi setting:

    • apiVersion
    • apiStrict
    • apiDeprecationErrors

    When in a transaction:

    • readConcern - sourced from readConcern set on the TransactionOptions
    • writeConcern - sourced from writeConcern set on the TransactionOptions

    Attaching any of the above fields to the command will have no effect as the driver will overwrite the value.

  • 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

    Parameters

    Returns Promise<string>

  • Remove a user from a database

    Parameters

    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.

  • A low level cursor API providing basic driver functionality:

    • ClientSession management
    • ReadPreference for server selection
    • Running getMores automatically when a local batch is exhausted

    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

    Returns RunCommandCursor

  • 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

    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.

    • options: ChangeStreamOptions = {}

      Optional settings for the command

    Returns ChangeStream<TSchema, TChange>

    watch() accepts two generic arguments for distinct use cases:

    • 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

    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.

    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.

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