Class: MongoClient

MongoClient

new MongoClient(url, options, callback){MongoClient}

Creates a new MongoClient instance

Name Type Description
url string

The connection URI string

options object optional

Optional settings

Name Type Default Description
poolSize number 5 optional

The maximum size of the individual server pool

ssl boolean false optional

Enable SSL connection. deprecated use tls variants

sslValidate boolean false optional

Validate mongod server certificate against Certificate Authority

sslCA buffer optional

SSL Certificate store binary buffer deprecated use tls variants

sslCert buffer optional

SSL Certificate binary buffer deprecated use tls variants

sslKey buffer optional

SSL Key file binary buffer deprecated use tls variants

sslPass string optional

SSL Certificate pass phrase deprecated use tls variants

sslCRL buffer optional

SSL Certificate revocation list binary buffer deprecated use tls variants

checkServerIdentity boolean | function true optional

Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. deprecated use tls variants

tls boolean false optional

Enable TLS connections

tlsInsecure boolean false optional

Relax TLS constraints, disabling validation

tlsCAFile string optional

A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection

tlsCertificateKeyFile string optional

A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated

tlsCertificateKeyFilePassword string optional

The password to decrypt the client private key to be used for TLS connections

tlsAllowInvalidCertificates boolean optional

Specifies whether or not the driver should error when the server’s TLS certificate is invalid

tlsAllowInvalidHostnames boolean optional

Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate

autoReconnect boolean true optional

Enable autoReconnect for single server instances

noDelay boolean true optional

TCP Connection no delay

keepAlive boolean true optional

TCP Connection keep alive enabled

keepAliveInitialDelay number 30000 optional

The number of milliseconds to wait before initiating keepAlive on the TCP socket

connectTimeoutMS number 10000 optional

How long to wait for a connection to be established before timing out

socketTimeoutMS number 360000 optional

How long a send or receive on a socket can take before timing out

family number optional

Version of IP stack. Can be 4, 6 or null (default).
If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure

reconnectTries number 30 optional

Server attempt to reconnect #times

reconnectInterval number 1000 optional

Server will wait # milliseconds between retries

ha boolean true optional

Control if high availability monitoring runs for Replicaset or Mongos proxies

haInterval number 10000 optional

The High availability period for replicaset inquiry

replicaSet string optional

The Replicaset set name

secondaryAcceptableLatencyMS number 15 optional

Cutoff latency point in MS for Replicaset member selection

acceptableLatencyMS number 15 optional

Cutoff latency point in MS for Mongos proxies selection

connectWithNoPrimary boolean false optional

Sets if the driver should connect even if no primary is available

authSource string optional

Define the database to authenticate against

w number | string optional

The write concern

wtimeout number optional

The write concern timeout

j boolean false optional

Specify a journal write concern

forceServerObjectId boolean false optional

Force server to assign _id values instead of driver

serializeFunctions boolean false optional

Serialize functions on any object

ignoreUndefined Boolean false optional

Specify if the BSON serializer should ignore undefined fields

raw boolean false optional

Return document results as raw BSON buffers

bufferMaxEntries number -1 optional

Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited

readPreference ReadPreference | string optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)

pkFactory object optional

A primary key factory object for generation of custom _id keys

promiseLibrary object optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

readConcern object optional

Specify a read concern for the collection (only MongoDB 3.2 or higher supported)

Name Type Default Description
level ReadConcernLevel 'local' optional

Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)

maxStalenessSeconds number optional

The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)

loggerLevel string optional

The logging level (error/warn/info/debug)

logger object optional

Custom logger object

promoteValues boolean true optional

Promotes BSON values to native types where possible, set to false to only receive wrapper types

promoteBuffers boolean false optional

Promotes Binary BSON values to native Node Buffers

promoteLongs boolean true optional

Promotes long values to number if they fit inside the 53 bits resolution

domainsEnabled boolean false optional

Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit

validateOptions object false optional

Validate MongoClient passed in options for correctness

appname string optional

The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections

auth.user string optional

The username for auth

auth.password string optional

The password for auth

authMechanism string optional

Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1

compression object optional

Type of compression to use: snappy or zlib

fsync boolean false optional

Specify a file sync write concern

readPreferenceTags array optional

Read preference tags

numberOfRetries number 5 optional

The number of retries for a tailable cursor

auto_reconnect boolean true optional

Enable auto reconnecting for single server instances

monitorCommands boolean false optional

Enable command monitoring for this client

minSize number optional

If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections

useNewUrlParser boolean true optional

Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.

useUnifiedTopology boolean optional

Enables the new unified topology layer

localThresholdMS Number 15 optional

Only applies to the unified topology The size of the latency window for selecting among multiple suitable servers

serverSelectionTimeoutMS Number 30000 optional

Only applies to the unified topology How long to block for server selection before throwing an error

heartbeatFrequencyMS Number 10000 optional

Only applies to the unified topology The frequency with which topology updates are scheduled

maxPoolSize number 10 optional

Only applies to the unified topology The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.

minPoolSize number 0 optional

Only applies to the unified topology The minimum number of connections that MUST exist at any moment in a single connection pool.

maxIdleTimeMS number optional

Only applies to the unified topology The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.

waitQueueTimeoutMS number 0 optional

Only applies to the unified topology The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.

autoEncryption AutoEncrypter~AutoEncryptionOptions optional

Optionally enable client side auto encryption

driverInfo DriverInfoOptions optional

Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver

callback MongoClient~connectCallback optional

The command result callback

Returns:
MongoClient instance

Methods

staticMongoClient.connect(url, options, callback){Promise.<MongoClient>}

Connect to MongoDB using a url as documented at

docs.mongodb.org/manual/reference/connection-string/

Note that for replicasets the replicaSet query parameter is required in the 2.0 driver

Name Type Description
url string

The connection URI string

options object optional

Optional settings

Name Type Default Description
poolSize number 5 optional

The maximum size of the individual server pool

ssl boolean false optional

Enable SSL connection. deprecated use tls variants

sslValidate boolean false optional

Validate mongod server certificate against Certificate Authority

sslCA buffer optional

SSL Certificate store binary buffer deprecated use tls variants

sslCert buffer optional

SSL Certificate binary buffer deprecated use tls variants

sslKey buffer optional

SSL Key file binary buffer deprecated use tls variants

sslPass string optional

SSL Certificate pass phrase deprecated use tls variants

sslCRL buffer optional

SSL Certificate revocation list binary buffer deprecated use tls variants

checkServerIdentity boolean | function true optional

Ensure we check server identify during SSL, set to false to disable checking. Only works for Node 0.12.x or higher. You can pass in a boolean or your own checkServerIdentity override function. deprecated use tls variants

tls boolean false optional

Enable TLS connections

tlsInsecure boolean false optional

Relax TLS constraints, disabling validation

tlsCAFile string optional

A path to file with either a single or bundle of certificate authorities to be considered trusted when making a TLS connection

tlsCertificateKeyFile string optional

A path to the client certificate file or the client private key file; in the case that they both are needed, the files should be concatenated

tlsCertificateKeyFilePassword string optional

The password to decrypt the client private key to be used for TLS connections

tlsAllowInvalidCertificates boolean optional

Specifies whether or not the driver should error when the server’s TLS certificate is invalid

tlsAllowInvalidHostnames boolean optional

Specifies whether or not the driver should error when there is a mismatch between the server’s hostname and the hostname specified by the TLS certificate

autoReconnect boolean true optional

Enable autoReconnect for single server instances

noDelay boolean true optional

TCP Connection no delay

keepAlive boolean true optional

TCP Connection keep alive enabled

keepAliveInitialDelay number 30000 optional

The number of milliseconds to wait before initiating keepAlive on the TCP socket

connectTimeoutMS number 10000 optional

How long to wait for a connection to be established before timing out

socketTimeoutMS number 360000 optional

How long a send or receive on a socket can take before timing out

family number optional

Version of IP stack. Can be 4, 6 or null (default).
If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure

reconnectTries number 30 optional

Server attempt to reconnect #times

reconnectInterval number 1000 optional

Server will wait # milliseconds between retries

ha boolean true optional

Control if high availability monitoring runs for Replicaset or Mongos proxies

haInterval number 10000 optional

The High availability period for replicaset inquiry

replicaSet string optional

The Replicaset set name

secondaryAcceptableLatencyMS number 15 optional

Cutoff latency point in MS for Replicaset member selection

acceptableLatencyMS number 15 optional

Cutoff latency point in MS for Mongos proxies selection

connectWithNoPrimary boolean false optional

Sets if the driver should connect even if no primary is available

authSource string optional

Define the database to authenticate against

w number | string optional

The write concern

wtimeout number optional

The write concern timeout

j boolean false optional

Specify a journal write concern

forceServerObjectId boolean false optional

Force server to assign _id values instead of driver

serializeFunctions boolean false optional

Serialize functions on any object

ignoreUndefined Boolean false optional

Specify if the BSON serializer should ignore undefined fields

raw boolean false optional

Return document results as raw BSON buffers

bufferMaxEntries number -1 optional

Sets a cap on how many operations the driver will buffer up before giving up on getting a working connection, default is -1 which is unlimited

readPreference ReadPreference | string optional

The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST)

pkFactory object optional

A primary key factory object for generation of custom _id keys

promiseLibrary object optional

A Promise library class the application wishes to use such as Bluebird, must be ES6 compatible

readConcern object optional

Specify a read concern for the collection (only MongoDB 3.2 or higher supported)

Name Type Default Description
level ReadConcernLevel 'local' optional

Specify a read concern level for the collection operations (only MongoDB 3.2 or higher supported)

maxStalenessSeconds number optional

The max staleness to secondary reads (values under 10 seconds cannot be guaranteed)

loggerLevel string optional

The logging level (error/warn/info/debug)

logger object optional

Custom logger object

promoteValues boolean true optional

Promotes BSON values to native types where possible, set to false to only receive wrapper types

promoteBuffers boolean false optional

Promotes Binary BSON values to native Node Buffers

promoteLongs boolean true optional

Promotes long values to number if they fit inside the 53 bits resolution

domainsEnabled boolean false optional

Enable the wrapping of the callback in the current domain, disabled by default to avoid perf hit

validateOptions object false optional

Validate MongoClient passed in options for correctness

appname string optional

The name of the application that created this MongoClient instance. MongoDB 3.4 and newer will print this value in the server log upon establishing each connection. It is also recorded in the slow query log and profile collections

auth.user string optional

The username for auth

auth.password string optional

The password for auth

authMechanism string optional

Mechanism for authentication: MDEFAULT, GSSAPI, PLAIN, MONGODB-X509, or SCRAM-SHA-1

compression object optional

Type of compression to use: snappy or zlib

fsync boolean false optional

Specify a file sync write concern

readPreferenceTags array optional

Read preference tags

numberOfRetries number 5 optional

The number of retries for a tailable cursor

auto_reconnect boolean true optional

Enable auto reconnecting for single server instances

monitorCommands boolean false optional

Enable command monitoring for this client

minSize number optional

If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections

useNewUrlParser boolean true optional

Determines whether or not to use the new url parser. Enables the new, spec-compliant, url parser shipped in the core driver. This url parser fixes a number of problems with the original parser, and aims to outright replace that parser in the near future. Defaults to true, and must be explicitly set to false to use the legacy url parser.

useUnifiedTopology boolean optional

Enables the new unified topology layer

localThresholdMS Number 15 optional

Only applies to the unified topology The size of the latency window for selecting among multiple suitable servers

serverSelectionTimeoutMS Number 30000 optional

Only applies to the unified topology How long to block for server selection before throwing an error

heartbeatFrequencyMS Number 10000 optional

Only applies to the unified topology The frequency with which topology updates are scheduled

maxPoolSize number 10 optional

Only applies to the unified topology The maximum number of connections that may be associated with a pool at a given time. This includes in use and available connections.

minPoolSize number 0 optional

Only applies to the unified topology The minimum number of connections that MUST exist at any moment in a single connection pool.

maxIdleTimeMS number optional

Only applies to the unified topology The maximum amount of time a connection should remain idle in the connection pool before being marked idle. The default is infinity.

waitQueueTimeoutMS number 0 optional

Only applies to the unified topology The maximum amount of time operation execution should wait for a connection to become available. The default is 0 which means there is no limit.

autoEncryption AutoEncrypter~AutoEncryptionOptions optional

Optionally enable client side auto encryption

driverInfo DriverInfoOptions optional

Allows a wrapping driver to amend the client metadata generated by the driver to include information about the wrapping driver

callback MongoClient~connectCallback optional

The command result callback

Returns:
Promise if no callback passed

close(force, callback){Promise}

Close the db and its underlying connections

Name Type Default Description
force boolean false optional

Force close, emitting no events

callback Db~noResultCallback optional

The result callback

Returns:
Promise if no callback passed

connect(callback){Promise.<MongoClient>}

Connect to MongoDB using a url as documented at

docs.mongodb.org/manual/reference/connection-string/

Note that for replicasets the replicaSet query parameter is required in the 2.0 driver

Name Type Description
callback MongoClient~connectCallback optional

The command result callback

Returns:
Promise if no callback passed

db(dbName, options){Db}

Create a new Db instance sharing the current socket connections. Be aware that the new db instances are
related in a parent-child relationship to the original instance so that events are correctly emitted on child
db instances. Child db instances are cached so performing db('db1') twice will return the same instance.
You can control these behaviors with the options noListener and returnNonCachedInstance.

Name Type Description
dbName string optional

The name of the database we want to use. If not provided, use database name from connection string.

options object optional

Optional settings.

Name Type Default Description
noListener boolean false optional

Do not make the db an event listener to the original connection.

returnNonCachedInstance boolean false optional

Control if you want to return a cached instance or have a new one created

isConnected(options){boolean}

Check if MongoClient is connected

Name Type Description
options object optional

Optional settings.

Name Type Default Description
noListener boolean false optional

Do not make the db an event listener to the original connection.

returnNonCachedInstance boolean false optional

Control if you want to return a cached instance or have a new one created

startSession(options){ClientSession}

Starts a new session on the server

Name Type Description
options SessionOptions optional

optional settings for a driver session

Returns:
newly established session

watch(pipeline, options){ChangeStream}

Create a new Change Stream, watching for new changes (insertions, updates, replacements, deletions, and invalidations) in this cluster. Will ignore all changes to system collections, as well as the local, admin,
and config databases.

Name Type Description
pipeline Array optional

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.

options object optional

Optional settings

Name Type Default Description
fullDocument string 'default' optional

Allowed values: ‘default’, ‘updateLookup’. When set to ‘updateLookup’, the change stream will include both a delta describing the changes to the document, as well as a copy of the entire document that was changed from some time after the change occurred.

resumeAfter object optional

Specifies the logical starting point for the new change stream. This should be the _id field from a previously returned change stream document.

maxAwaitTimeMS number optional

The maximum amount of time for the server to wait on new documents to satisfy a change stream query

batchSize number 1000 optional

The number of documents to return per batch. See aggregation documentation.

collation object optional

Specify collation settings for operation. See aggregation documentation.

readPreference ReadPreference optional

The read preference. See read preference documentation.

startAtOperationTime Timestamp optional

receive change events that occur after the specified timestamp

session ClientSession optional

optional session to use for this operation

Since:
  • 3.1.0
Returns:
ChangeStream instance.

withSession(options, operation){Promise}

Runs a given operation with an implicitly created session. The lifetime of the session
will be handled without the need for user interaction.

NOTE: presently the operation MUST return a Promise (either explicit or implicity as an async function)

Name Type Description
options Object optional

Optional settings to be appled to implicitly created session

operation function

An operation to execute with an implicitly created session. The signature of this MUST be (session) => {}

Type Definitions

connectCallback(error, client)

The callback format for results

Name Type Description
error MongoError

An error instance representing the error during the execution.

client MongoClient

The connected client.