Overview
This page describes the connection options available in the Node.js driver and explains how to apply them to your MongoDB connection.
How to Specify Connection Options
The following sections describe how you can specify connection options by using a connection string or a MongoClientOptions object.
Use the Connection String
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.
Use the MongoClientOptions Object
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,});Replica Set Options
Direct Connection
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');Replica Set
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');Direct Connection
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 directConnectionClient = new MongoClient(uri, { directConnection: true,});Replica Set
The name of the replica set to connect to.
Data Type: string
Default Value: null
Example:
const replicaSetClient = new MongoClient(uri, { replicaSet: 'rs0',});TLS Options
Enable TLS
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');Specify the CA File
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');Specify the Client Certificate Key File
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');Specify the Client Certificate Key File Password
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');Allow Invalid Certificates
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');Allow Invalid Hostnames
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');Relax TLS Constraints
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');Enable TLS
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 tlsClient = new MongoClient(uri, { tls: true,});Specify the CA File
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 tlsCaFileClient = new MongoClient(uri, { tls: true, tlsCAFile: '/path/to/ca.pem',});Specify the Client Certificate Key File
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 tlsCertKeyFileClient = new MongoClient(uri, { tls: true, tlsCertificateKeyFile: '/path/to/client.pem',});Specify the Client Certificate Key File Password
The tlsCertificateKeyFilePassword option specifies the password to decrypt the client private key used for TLS connections.
Data Type: string
Default Value: null
Example:
const tlsCertKeyPasswordClient = new MongoClient(uri, { tls: true, tlsCertificateKeyFile: '/path/to/client.pem', tlsCertificateKeyFilePassword: 'iperLuv60',});Allow Invalid Certificates
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 tlsAllowInvalidCertsClient = new MongoClient(uri, { tls: true, tlsAllowInvalidCertificates: true,});Allow Invalid Hostnames
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 tlsAllowInvalidHostnamesClient = new MongoClient(uri, { tls: true, tlsAllowInvalidHostnames: true,});Relax TLS Constraints
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 tlsInsecureClient = new MongoClient(uri, { tls: true, tlsInsecure: true,});For more information about TLS options, see the Enable TLS on a Connection guide.
Timeout Options
Connect Timeout
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');Socket Timeout
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');Server Selection Timeout
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');Connect Timeout
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 connectTimeoutClient = new MongoClient(uri, { connectTimeoutMS: 60000,});Socket Timeout
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 socketTimeoutClient = new MongoClient(uri, { socketTimeoutMS: 60000,});Server Selection Timeout
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 serverSelectionTimeoutClient = new MongoClient(uri, { serverSelectionTimeoutMS: 10000,});To learn how to limit the server execution time of individual operations, see the Limit Server Execution Time guide.
Compression Options
Compressors
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');Zlib Compression Level
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');Compressors
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: array of string values
Default Value: null
Example:
const compressorsClient = new MongoClient(uri, { compressors: ['snappy', 'zlib', 'zstd'],});Zlib Compression Level
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 zlibLevelClient = new MongoClient(uri, { compressors: ['zlib'], zlibCompressionLevel: 6,});For more information about compression, see the Compress Network Traffic guide.
Connection Pool Options
Max Pool Size
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');Min Pool Size
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');Max Connection Idle Time
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');Max Connecting
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');Wait Queue Timeout
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');Max Pool Size
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 maxPoolSizeClient = new MongoClient(uri, { maxPoolSize: 150,});Min Pool Size
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 minPoolSizeClient = new MongoClient(uri, { minPoolSize: 10,});Max Connection Idle Time
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 maxIdleTimeClient = new MongoClient(uri, { maxIdleTimeMS: 30000,});Max Connecting
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 maxConnectingClient = new MongoClient(uri, { maxConnecting: 5,});Wait Queue Timeout
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 waitQueueTimeoutClient = new MongoClient(uri, { waitQueueTimeoutMS: 2000,});To learn more about connection pools, see the Manage Connections with Connection Pools guide.
Write Concern Options
Write Concern
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:
woption:numberorstringjournaloption:booleanwtimeoutMSoption: non-negativenumber
Default Value:
woption:1journaloption: depends on thewriteConcernMajorityJournalDefaultreplica set configuration settingwtimeoutMSoption:0(no timeout)
Example:
const writeConcernUriClient = new MongoClient( 'mongodb://localhost:27017/?w=majority&journal=true&wtimeoutMS=1000');Write Concern
The writeConcern option specifies the level of acknowledgement requested from MongoDB for write operations, including the time limit.
To learn more, see Write Concern in the MongoDB Server manual.
The MongoClientOptions type also defines top-level w, wtimeoutMS, and journal options. These top-level options are deprecated. Set the properties on the writeConcern option instead, as shown in the example below.
Data Type: WriteConcern or WriteConcernSettings object
Default Value: w: 1
Example:
const writeConcernClient = new MongoClient(uri, { writeConcern: { w: 'majority', journal: true, wtimeoutMS: 1000 },});Read Concern Options
Read Concern Level
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');Read Concern Level
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 readConcernLevelClient = new MongoClient(uri, { readConcernLevel: 'majority',});Read Preference Options
Read Preference
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');Read Preference Tags
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
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');Local Threshold
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');Read Preference
The client's default read-preference settings. See Read Preference in the MongoDB Server manual for more information.
Data Type: ReadPreferenceMode or ReadPreference object
Default Value: primary
Example:
const readPreferenceClient = new MongoClient(uri, { readPreference: 'secondaryPreferred',});Read Preference Tags
The readPreferenceTags option specifies the default read preference tags for the client. Each tag set is an object that maps tag keys to values. This option is valid only if the read preference mode is not primary. To learn more about read preference tags, see tags in the MongoDB Server manual.
Data Type: array of tags documents
Default Value: null
Example:
const readPreferenceTagsClient = new MongoClient(replicaSetUri, { readPreference: 'secondaryPreferred', readPreferenceTags: [{ dc: 'ny', rack: '1' }],});Max Staleness Seconds
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 maxStalenessClient = new MongoClient(replicaSetUri, { readPreference: 'secondaryPreferred', maxStalenessSeconds: 120,});Local Threshold
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 localThresholdClient = new MongoClient(uri, { localThresholdMS: 30,});Authentication Options
Authentication Mechanism
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');Authentication Mechanism Properties
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>');Auth Source
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');Authentication Mechanism
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: AuthMechanism
Default Value: null (the driver uses SCRAM-SHA-1 or SCRAM-SHA-256 depending on the server version)
Example:
const authMechanismClient = new MongoClient( 'mongodb://user:password@localhost:27017/', { authSource: 'admin', authMechanism: 'SCRAM-SHA-256', });Authentication Mechanism Properties
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: AuthMechanismProperties object
Default Value: null
Example:
const authMechanismPropertiesClient = new MongoClient( 'mongodb://<Kerberos principal>@localhost:27017/', { authMechanism: 'GSSAPI', authMechanismProperties: { SERVICE_NAME: '<service name>', }, });Auth Source
The authSource option specifies the database that contains the user's credentials.
Data Type: string
Default Value: null
Example:
const authSourceClient = new MongoClient( 'mongodb://user:password@localhost:27017/', { authSource: 'admin', });Server Monitoring Options
Heartbeat Frequency
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');Server Monitoring Mode
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');Heartbeat Frequency
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 heartbeatFrequencyClient = new MongoClient(uri, { heartbeatFrequencyMS: 10000,});Server Monitoring Mode
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 serverMonitoringModeClient = new MongoClient(uri, { serverMonitoringMode: 'poll',});Retry Options
Retry Reads
Enables retryable reads.
Data Type: boolean
Default Value: true
Example:
const retryReadsUriClient = new MongoClient( 'mongodb://localhost:27017/?retryReads=false');Retry Writes
Enables retryable writes.
Data Type: boolean
Default Value: true
Example:
const retryWritesUriClient = new MongoClient( 'mongodb://localhost:27017/?retryWrites=false');Max Adaptive Retries
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');Overload Retargeting
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');Retry Reads
Enables retryable reads.
Data Type: boolean
Default Value: true
Example:
const retryReadsClient = new MongoClient(uri, { retryReads: false,});Retry Writes
Enables retryable writes.
Data Type: boolean
Default Value: true
Example:
const retryWritesClient = new MongoClient(uri, { retryWrites: false,});Max Adaptive Retries
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 maxAdaptiveRetriesClient = new MongoClient(uri, { maxAdaptiveRetries: 2,});Overload Retargeting
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 overloadRetargetingClient = new MongoClient(uri, { 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.
Miscellaneous Options
Application Name
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');Load Balanced
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
SrvMaxHostspropertyYou're not using the
DirectConnectionproperty
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');SRV Max Hosts
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');SRV Service Name
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');Auto Select Family
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');Auto Select Family Attempt Timeout
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');UTF-8 Validation
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');SOCKS5 Proxy
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:
stringfor theproxyHost,proxyUsername, andproxyPasswordoptionsnon-negative
numberfor theproxyPortoption
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');Application Name
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 appNameClient = new MongoClient(uri, { appName: 'docsExample',});SRV Max Hosts
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 srvMaxHostsClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/', { srvMaxHosts: 10, });SRV Service Name
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 srvServiceNameClient = new MongoClient( 'mongodb+srv://cluster.example.mongodb.net/', { srvServiceName: 'docsExample', });Auto Select Family
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 autoSelectFamilyClient = new MongoClient(uri, { autoSelectFamily: false,});Auto Select Family Attempt Timeout
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 autoSelectFamilyAttemptTimeoutClient = new MongoClient(uri, { autoSelectFamilyAttemptTimeout: 300,});UTF-8 Validation
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 utf8ValidationClient = new MongoClient(uri, { enableUtf8Validation: false,});SOCKS5 Proxy
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:
stringfor theproxyHost,proxyUsername, andproxyPasswordoptionsnon-negative
numberfor theproxyPortoption
Default Value: null for all four options
Example:
const proxyClient = new MongoClient(uri, { proxyHost: 'proxy.example.com', proxyPort: 4040, proxyUsername: 'proxyUser', proxyPassword: 'docsExample',});Runtime Adapters
(Experimental) The runtimeAdapters option specifies custom implementations of core Node.js APIs. Use this option to run the driver in restricted environments or in alternative runtimes incompatible with Node.js. This option is not supported in a connection string.
Data Type: RuntimeAdapters object
Default Value: null
Example:
const runtimeAdaptersClient = new MongoClient(uri, { runtimeAdapters: { os: { arch: () => 'x64', platform: () => 'linux', release: () => '5.4.0', type: () => 'Linux', }, },});Keep Alive Initial Delay
The keepAliveInitialDelay option specifies the number of milliseconds that the driver waits before initiating a Transmission Control Protocol (TCP) keepalive on a socket. When the driver sends TCP keepalives, it checks whether the connection is active by sending periodic pings to your MongoDB deployment. This functionality works only if your operating system supports the SO_KEEPALIVE socket option. This option is not supported in a connection string.
Driver version 5.3 deprecated the keepAlive option. As of driver version 6.0, the driver always sets keepAlive to true.
Warning
If your firewall ignores or drops the keepalive messages, you might not be able to identify dropped connections.
Data Type: non-negative number
Default Value: 120000 milliseconds (120 seconds)
Additional Information
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.