For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Specify Connection Options

This page describes the connection options available in the Node.js driver and explains how to apply them to your MongoDB connection.

The following sections describe how you can specify connection options by using a connection string or a MongoClientOptions object.

You can include connection options in a connection string as <name>=<value> pairs. Pass the connection string to the MongoClient constructor. In the following example, the connection string contains the connectTimeoutMS option with a value of 60000 and the tls option with a value of true:

const uriClient = new MongoClient( 'mongodb://localhost:27017/?connectTimeoutMS=60000&tls=true');

To learn more about connection string options, see Connection String Options in the MongoDB Server manual.

You can pass a MongoClientOptions object to the MongoClient constructor to configure connection settings in code. Configuring the connection this way makes it easier to change settings at runtime and helps you catch errors during compilation. This approach also provides more configuration options than the connection string.

The following example sets the connectTimeoutMS option to 60000 milliseconds and enables TLS:

const optionsClient = new MongoClient(uri, { connectTimeoutMS: 60000, tls: true,});

Specifies whether to force dispatch all operations to the host. If you specify this option, the driver doesn't accept the SRV connection format. You must use the standard connection URI format instead. To learn more about the SRV connection and the standard connection formats, see the Connection Strings guide in the MongoDB Server manual.

This property must be set to false if you specify more than one host name.

Data Type: boolean

Default Value: false

Example:

const directConnectionUriClient = new MongoClient( 'mongodb://localhost:27017/?directConnection=true');

The name of the replica set to connect to.

Data Type: string

Default Value: null

Example:

const replicaSetUriClient = new MongoClient( 'mongodb://localhost:27017/?replicaSet=rs0');

Specifies whether to require TLS for connections to the server. If you use a scheme of "mongodb+srv" or specify other TLS options, this option defaults to true. Otherwise, it defaults to false.

The ssl option is an alias for the tls option.

Data Type: boolean

Default Value: false

Example:

const tlsUriClient = new MongoClient('mongodb://localhost:27017/?tls=true');

The tlsCAFile option specifies the path to a file with either a single or bundle of certificate authorities to trust when making a TLS connection. To learn more about setting this option, see the Provide Certificate Filepaths section of the TLS guide.

Data Type: string

Default Value: null

Example:

const tlsCaFileUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsCAFile=/path/to/ca.pem');

The tlsCertificateKeyFile option specifies the path to the client certificate file or the client private key file. If you need both, you must concatenate the files. To learn more about setting this option, see the Provide Certificate Filepaths section of the TLS guide.

Data Type: string

Default Value: null

Example:

const tlsCertKeyFileUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=/path/to/client.pem');

The tlsCertificateKeyFilePassword option specifies the password to decrypt the client private key used for TLS connections.

Data Type: string

Default Value: null

Example:

const tlsCertKeyPasswordUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=/path/to/client.pem&tlsCertificateKeyFilePassword=iperLuv60');

The tlsAllowInvalidCertificates option specifies whether the driver generates an error when the server's TLS certificate is invalid. Set this option to true for testing purposes only.

Data Type: boolean

Default Value: false

Example:

const tlsAllowInvalidCertsUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsAllowInvalidCertificates=true');

The tlsAllowInvalidHostnames option specifies whether the driver generates an error when there is a mismatch between the server's hostname and the hostname specified by the TLS certificate. Set this option to true for testing purposes only.

Data Type: boolean

Default Value: false

Example:

const tlsAllowInvalidHostnamesUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsAllowInvalidHostnames=true');

The tlsInsecure option relaxes TLS constraints as much as possible, such as allowing invalid certificates or hostname mismatches. Set this option to true for testing purposes only.

Data Type: boolean

Default Value: false

Example:

const tlsInsecureUriClient = new MongoClient( 'mongodb://localhost:27017/?tls=true&tlsInsecure=true');

For more information about TLS options, see the Enable TLS on a Connection guide.

The length of time the driver tries to establish a single TCP socket connection to the server before timing out.

Data Type: non-negative number

Default Value: 30000 milliseconds

Example:

const connectTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?connectTimeoutMS=60000');

The length of time the driver tries to send or receive on a socket before timing out. The default value is set by the operating system.

If a MongoDB process fails with an error or the network connection drops, you might not receive confirmation that the driver closed the corresponding socket. To ensure that the driver closes the socket in these cases, set the socketTimeoutMS option. Select a value for socketTimeoutMS that is two to three times longer than the expected duration of your slowest operation.

Data Type: non-negative number

Default Value: 0 (no timeout)

Example:

const socketTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?socketTimeoutMS=60000');

The length of time the driver tries to select a server before timing out.

Data Type: non-negative number

Default Value: 30000 milliseconds

Example:

const serverSelectionTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?serverSelectionTimeoutMS=10000');

To learn how to limit the server execution time of individual operations, see the Limit Server Execution Time guide.

The preferred compression types, in order, for wire-protocol messages sent to or received from the server. You can enable "snappy", "zlib", and "zstd" as optional build time dependencies. The driver uses the first of these compression types that the server supports.

Data Type: comma-separated string

Default Value: null

Example:

const compressorsUriClient = new MongoClient( 'mongodb://localhost:27017/?compressors=snappy,zlib,zstd');

The zlibCompressionLevel option sets the compression level for zlib to use. This option accepts an integer value between -1 and 9:

  • -1: Default compression level.

  • 0: No compression.

  • 1: Fastest speed but lowest compression.

  • 9: Best compression but slowest speed.

Data Type: number between -1 and 9 (inclusive)

Default Value: -1

Example:

const zlibLevelUriClient = new MongoClient( 'mongodb://localhost:27017/?compressors=zlib&zlibCompressionLevel=6');

For more information about compression, see the Compress Network Traffic guide.

The greatest number of clients or connections the driver can create in its connection pool. This count includes connections in use.

Data Type: non-negative number

Default Value: 100

Example:

const maxPoolSizeUriClient = new MongoClient( 'mongodb://localhost:27017/?maxPoolSize=150');

The number of connections the driver creates and keeps in the connection pool even when no operations are occurring. This count includes connections in use.

Data Type: non-negative number

Default Value: 0

Example:

const minPoolSizeUriClient = new MongoClient( 'mongodb://localhost:27017/?minPoolSize=10');

The length of time a connection can be idle before the driver closes it.

Data Type: non-negative number

Default Value: 0 (no limit)

Example:

const maxIdleTimeUriClient = new MongoClient( 'mongodb://localhost:27017/?maxIdleTimeMS=30000');

The maxConnecting option sets the maximum number of connections the connection pool may establish concurrently.

Data Type: non-negative number

Default Value: 2

Example:

const maxConnectingUriClient = new MongoClient( 'mongodb://localhost:27017/?maxConnecting=5');

The length of time the driver tries to check out a connection from a server's connection pool before timing out.

Data Type: non-negative number

Default Value: 0 (no timeout)

Example:

const waitQueueTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?waitQueueTimeoutMS=2000');

To learn more about connection pools, see the Manage Connections with Connection Pools guide.

The w component of the write concern, which requests acknowledgment that the write operation has propagated to a specified number of MongoDB instances. The default value is "majority" or 1, depending on the number of arbiters and voting nodes. To learn more about the w option, see Write Concern in the MongoDB Server manual.

You can also set the following options in the connection string to complete the write concern:

  • journal: specifies whether the driver waits for the server to group commit to the journal file on disk.

  • wtimeoutMS: specifies a time limit for the write concern.

To learn more, see Write Concern in the MongoDB Server manual.

Data Type:

  • w option: number or string

  • journal option: boolean

  • wtimeoutMS option: non-negative number

Default Value:

  • w option: 1

  • journal option: depends on the writeConcernMajorityJournalDefault replica set configuration setting

  • wtimeoutMS option: 0 (no timeout)

Example:

const writeConcernUriClient = new MongoClient( 'mongodb://localhost:27017/?w=majority&journal=true&wtimeoutMS=1000');

The client's read concern level. For more information, see the Read Concern reference in the MongoDB Server manual.

Data Type: string

Default Value: null

Example:

const readConcernLevelUriClient = new MongoClient( 'mongodb://localhost:27017/?readConcernLevel=majority');

The client's default read-preference settings. See Read Preference in the MongoDB Server manual for more information.

Data Type: string

Default Value: primary

Example:

const readPreferenceUriClient = new MongoClient( 'mongodb://localhost:27017/?readPreference=secondaryPreferred');

The readPreferenceTags option specifies the default read preference tags for the client as comma-separated key:value pairs. This option is valid only if the read preference mode is not primary. The driver uses the order of the tags in the URI as the order for the read preference. To learn more about read preference tags, see tags in the MongoDB Server manual.

Data Type: comma-separated key:value pairs

Default Value: null

Example:

const readPreferenceTagsUriClient = new MongoClient( replicaSetUri + '&readPreference=secondaryPreferred&readPreferenceTags=dc:ny,rack:1');

Max Staleness Seconds represents the longest replication lag, in wall-clock time, that a secondary can experience and still be eligible for server selection. The smallest allowed value for maxStalenessSeconds is 90 seconds. This option must be used with a non-primary read preference.

To apply no maximum, omit this option rather than setting it explicitly.

Data Type: number greater than or equal to 90

Default Value: null (no maximum)

Example:

const maxStalenessUriClient = new MongoClient( replicaSetUri + '&readPreference=secondaryPreferred&maxStalenessSeconds=120');

The latency window for server eligibility. If a server's round trip takes longer than the fastest server's round-trip time plus this value, the server isn't eligible for selection.

Data Type: non-negative number

Default Value: 15 milliseconds

Example:

const localThresholdUriClient = new MongoClient( 'mongodb://localhost:27017/?localThresholdMS=30');

The mechanism that the driver uses to authenticate to MongoDB Server. If you don't specify an authentication mechanism, the driver uses either SCRAM-SHA-1 or SCRAM-SHA-256, depending on the server version.

To learn more about available authentication mechanisms, see the Authentication Mechanisms guide.

Data Type: string

Default Value: null (the driver uses SCRAM-SHA-1 or SCRAM-SHA-256 depending on the server version)

Example:

const authMechanismUriClient = new MongoClient( 'mongodb://user:password@localhost:27017/?authSource=admin&authMechanism=SCRAM-SHA-256');

The authMechanismProperties option specifies properties for the authentication mechanism set in the authMechanism option, such as the service name for Kerberos (GSSAPI) authentication.

Data Type: comma-separated key:value pairs

Default Value: null

Example:

const authMechanismPropertiesUriClient = new MongoClient( 'mongodb://<Kerberos principal>@localhost:27017/?authMechanism=GSSAPI&authMechanismProperties=SERVICE_NAME:<service name>');

The authSource option specifies the database that contains the user's credentials.

Data Type: string

Default Value: null

Example:

const authSourceUriClient = new MongoClient( 'mongodb://user:password@localhost:27017/?authSource=admin');

The interval between server monitoring checks. Must be greater than or equal to 500 milliseconds. The default value is 10000 ms (10 seconds) in pooled (multi-threaded) mode and 60000 ms (60 seconds) in non-pooled (single-threaded) mode.

The Node.js driver maintains a connection pool, so the driver defaults to pooled mode.

Data Type: number greater than or equal to 500

Default Value: 10000 milliseconds

Example:

const heartbeatFrequencyUriClient = new MongoClient( 'mongodb://localhost:27017/?heartbeatFrequencyMS=10000');

The serverMonitoringMode option specifies the monitoring mode that the driver monitors use. When this option is set to auto, the monitoring mode is determined by the environment in which the driver runs. The driver uses polling mode in function-as-a-service (FaaS) environments and the streaming mode in other environments.

Data Type: auto, stream, or poll

Default Value: auto

Example:

const serverMonitoringModeUriClient = new MongoClient( 'mongodb://localhost:27017/?serverMonitoringMode=poll');

Enables retryable reads.

Data Type: boolean

Default Value: true

Example:

const retryReadsUriClient = new MongoClient( 'mongodb://localhost:27017/?retryReads=false');

Enables retryable writes.

Data Type: boolean

Default Value: true

Example:

const retryWritesUriClient = new MongoClient( 'mongodb://localhost:27017/?retryWrites=false');

The maxAdaptiveRetries option sets the maximum number of retries to attempt when the driver encounters overload errors. Specifying 0 disables adaptive retries. This option requires MongoDB Atlas 9.0 or later.

Data Type: non-negative number

Default Value: 2

Example:

const maxAdaptiveRetriesUriClient = new MongoClient( 'mongodb://localhost:27017/?maxAdaptiveRetries=2');

The enableOverloadRetargeting option specifies whether the driver deprioritizes a server that returns an overload error, reducing the likelihood of retrying on the same overloaded server. This option requires MongoDB Atlas 9.0 or later.

Data Type: boolean

Default Value: false

Example:

const overloadRetargetingUriClient = new MongoClient( 'mongodb://localhost:27017/?enableOverloadRetargeting=true');

Note

Load Shedding in Intelligent Workload Management (IWM)

If errors with SystemOverloadedError or RetryableError labels are causing failures in your application or appearing in your application logs, Load Shedding may be active on your cluster and your driver may not be upgraded to a version that supports it. We recommend upgrading your MongoDB Node.js driver to version 7.2 or later. If you continue to see these errors after upgrading, you can address them through server-side changes, such as reviewing your Load Shedding configuration, or through application-side changes, such as implementing custom error handling or client-side request throttling. Depending on your situation, application-side changes may be preferable or necessary.

Load Shedding is a feature of IWM, and helps manage server load by rejecting excess operations during sustained overload. This feature is available on MongoDB 9.0 and later.

For more information about IWM or handling overload errors, see the Intelligent Workload Management page or Overload Errors page in the Atlas documentation.

The app name the driver passes to the server in the client metadata as part of the connection handshake. The server prints this value to the MongoDB logs once it establishes the connection. The value is also recorded in the slow query logs and profile collections.

Data Type: string

Default Value: null

Example:

const appNameUriClient = new MongoClient( 'mongodb://localhost:27017/?appName=docsExample');

Specifies whether the driver is connecting to a load balancer. You can set this property to true only if all the following conditions are met:

  • You specify just one host name

  • You're not connecting to a replica set

  • You're not using the SrvMaxHosts property

  • You're not using the DirectConnection property

The Node.js driver supports this option only in the connection string. You cannot set it in a MongoClientOptions object.

Data Type: boolean

Default Value: false

Example:

const loadBalancedUriClient = new MongoClient( 'mongodb://localhost:27017/?loadBalanced=true');

The greatest number of SRV results to randomly select when initially populating the seedlist or, during SRV polling, adding new hosts to the topology.

You can use this property only if the connection-string scheme is set to ConnectionStringScheme.MongoDBPlusSrv. You cannot use it when connecting to a replica set.

Data Type: non-negative number

Default Value: 0 (unlimited)

Example:

const srvMaxHostsUriClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/?srvMaxHosts=10');

The service name of the SRV resource records that the driver retrieves to construct your seedlist. The driver uses the service name to create the SRV URI, which matches the following format:

_{srvServiceName}._tcp.{hostname}.{domainname}

This property overrides the default service name for SRV lookup in discovery and polling. The default value is "mongodb".

You can use this property only if the connection-string scheme is set to ConnectionStringScheme.MongoDBPlusSrv. You cannot use it when connecting to a replica set.

Data Type: string

Default Value: mongodb

Example:

const srvServiceNameUriClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/?srvServiceName=docsExample');

If you set the autoSelectFamily option to true, the socket attempts to connect to IPv6 and IPv4 addresses until a connection is established. If available, the driver selects the first IPv6 address.

Data Type: boolean

Default Value: true

Example:

const autoSelectFamilyUriClient = new MongoClient( 'mongodb://localhost:27017/?autoSelectFamily=false');

The autoSelectFamilyAttemptTimeout option specifies the amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the autoSelectFamily option. If you set a positive integer less than 10, the driver uses 10 instead.

Data Type: non-negative number

Default Value: null

Example:

const autoSelectFamilyAttemptTimeoutUriClient = new MongoClient( 'mongodb://localhost:27017/?autoSelectFamilyAttemptTimeout=300');

The enableUtf8Validation option specifies whether the driver validates UTF-8 characters when it deserializes BSON documents from MongoDB. If you enable validation, the driver throws a BSONError when it reads data that contains invalid UTF-8 characters. Disable UTF-8 validation only as a temporary workaround to query or export data.

To learn more about UTF-8 characters, see UTF-8 on Wikipedia.

Data Type: boolean

Default Value: true

Example:

const utf8ValidationUriClient = new MongoClient( 'mongodb://localhost:27017/?enableUtf8Validation=false');

You can route connections through a SOCKS5 proxy by setting the proxyHost option to the proxy's IPv4 address, IPv6 address, or domain name. The proxyPort option specifies the TCP port number of the proxy server. To authenticate to the proxy server, set the proxyUsername and proxyPassword options. If you omit the proxyPort option, the driver uses 1080. If you set one of the proxyUsername or proxyPassword options, you must set both. To learn more, see Enable SOCKS5 Proxy Support.

Data Type:

  • string for the proxyHost, proxyUsername, and proxyPassword options

  • non-negative number for the proxyPort option

Default Value: null for all four options

Example:

const proxyUriClient = new MongoClient( 'mongodb://localhost:27017/?proxyHost=proxy.example.com&proxyPort=4040&proxyUsername=proxyUser&proxyPassword=docsExample');

To see all the available settings, see the MongoClientOptions API documentation.

To learn more about connection string options, see Connection String Options in the MongoDB Server manual.