Docs Menu
Docs Home
/ / /
Java Sync
/ /

Specify MongoClient Settings

On this page

  • Overview
  • MongoClient Settings
  • Cluster Settings
  • Connection Pool Settings
  • Server Settings
  • Socket Settings
  • TLS/SSL Settings

In this guide, you can learn about the different settings to control the behavior of your MongoClient.

The following sections describe commonly used settings:

You can control the behavior of your MongoClient by creating and passing in a MongoClientSettings object to the MongoClients.create() method.

To create a MongoClientSettings object, use the MongoClientSettings.builder() method and chain methods to specify your settings. After chaining them, use the build() method to create the MongoClientSettings object.

The following table describes all the methods you can chain to modify your connection behavior:

Method
Description
addCommandListener()
Adds a listener for command events.
applicationName()
Sets the logical name of the application using the MongoClient.
applyConnectionString()
Applies the settings from the given ConnectionString to the builder. If you omit this method, the driver attempts to connect to localhost.
applyToClusterSettings()
Applies the ClusterSettings.Builder block and then sets the cluster settings.
applyToConnectionPoolSettings()
Applies the ConnectionPoolSettings.Builder block and then sets the connection pool settings.
applyToServerSettings()
Applies the ServerSettings.Builder block and then sets the server settings.
applyToSocketSettings()
Applies the SocketSettings.Builder block and then sets the socket settings.
applyToSslSettings()
Applies the SslSettings.Builder block and then sets the TLS/SSL settings.
autoEncryptionSettings()

If you omit keyVaultClient or set bypassAutomaticEncryption to false in your AutoEncryptionSettings, the driver creates a separate, internal MongoClient.

The internal MongoClient configuration differs from the parent MongoClient by setting the minPoolSize to 0 and omitting the AutoEncryptionSettings.
codecRegistry()
commandListenerList()
compressorList()
Sets the compressors to use for compressing messages to the server.
credential()
Sets the credential.
readConcern()
Sets the read concern.
readPreference()
Sets the read preference.

Default: primary
retryReads()
Whether the driver performs retry reads if a network error occurs.

Default: true
retryWrites()
Whether the driver performs retry writes if a network error occurs.

Default: true
serverApi()
Sets the server API to use when sending commands to the server.
streamFactoryFactory()
Sets the factory to use to create a StreamFactory.
uuidRepresentation()
Sets the UUID representation to use when encoding instances of UUID and decoding BSON binary values with subtype of 3.
writeConcern()
Sets the write concern.

Default: WriteConcern#ACKNOWLEDGED. For more information about the default value, see Implicit Default Write Concern.

This example demonstrates specifying a ConnectionString:

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("<your connection string>"))
.build());

Note

Chain Order

Some options in the settings map to a connection string option. If you specify the same options in your settings and connection string, the order you chain them determines which option the driver uses. The driver uses the last setting it reads.

For example, this snippet contains settings with the following times for the driver to connect to an available socket:

  • The connection string specifies within 2 SECONDS

  • The socket settings specifies within 5 SECONDS

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("mongodb+srv://<db_username>:<db_password>@<hostname>:<port>/<auth db>?connectTimeoutMS=2000"))
.applyToSocketSettings(builder ->
builder.connectTimeout(5, SECONDS))
.build());

Since the driver reads the socket settings options last, the driver expects to connect to an available socket within 5 SECONDS before timing out.

Tip

Log Your Settings

To log the MongoClient instance settings, set the org.mongodb.driver.client named logger to the INFO level.

To learn more about logging with the MongoDB Java Driver, see the Logging guide.

Chain the applyToClusterSettings() method to modify the driver's behavior when interacting with your MongoDB cluster.

The following table describes all the methods you can chain to your settings to modify the driver's behavior:

Method
Description
addClusterListener()
Adds a listener for cluster-related events.
applyConnectionString()
Uses the settings from a ConnectionString object.
applySettings()
Uses the cluster settings specified in a ClusterSettings object.
hosts()
Sets all the specified locations of a Mongo deployment.
localThreshold()
Sets the amount of time that a server’s round trip can take and still be eligible for server selection.

Default: 15 milliseconds
mode()
Sets how to connect to a MongoDB deployment.
requiredClusterType()
Sets the type of cluster required for the cluster.
requiredReplicaSetName()
Sets the replica set name required for the cluster.
serverSelectionTimeout()
Sets the maximum time to select a primary node before throwing a timeout exception.

Default: 30 seconds
serverSelector()
Adds a server selector to apply before server selection.
srvHost()

Sets the host name to use to look up an SRV DNS record to find the MongoDB hosts.

Note

When setting srvHost, the driver does not process any associated TXT records associated with the host.

If you want to enable the processing of TXT records, you must specify the SRV host in the connection string using the applyConnectionString() method.

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mongodb+srv://host1.acme.com")))
srvMaxHosts()
Sets the maximum number of hosts the driver can connect to when using the DNS seedlist (SRV) connection protocol, identified by the mongodb+srv connection string prefix.

Throws an exception if you are not using the SRV connection protocol.

This example specifies for the driver to connect directly to a server, regardless of the type of MongoDB cluster it's a part of:

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder()
.applyToClusterSettings(builder ->
builder.mode(ClusterConnectionMode.SINGLE)
.build());

Tip

This is analogous to the directConnection parameter you can specify in your connection URI. See Connection Options for more information.

Chain the applyToConnectionPoolSettings() method to modify the way the driver manages its connection pool.

The following table describes all the methods you can chain to your settings to modify the driver's behavior:

Method
Description
addConnectionPoolListener()
Adds a listener for connection pool-related events.
applyConnectionString()
Uses the settings from a ConnectionString object.
applySettings()
Uses the connection pool settings specified in a ConnectionPoolSettings object.
maintenanceFrequency()
Sets the frequency for running a maintenance job.
maintenanceInitialDelay()
Sets the time to wait before running the first maintenance job.
maxConnectionIdleTime()
Sets the maximum time a connection can be idle before it's closed.
maxConnectionLifeTime()
Sets the maximum time a pooled connection can be alive before it's closed.
maxSize()
Sets the maximum number of connections associated with a connection pool.

Default: 100
maxWaitTime()
Sets the maximum time to wait for an available connection.

Default: 2 minutes
minSize()
Sets the minimum number of connections associated with a connection pool.

Default: 0

Note

This maxSize and minSize settings apply to each server in the cluster you connect the driver to.

For example, assume you connect the driver to a cluster with three mongos servers. This means that there can be at most maxSize connections and at least minSize connections to each mongos server.

This example specifies the following driver behavior in a pool of Connection types:

  • The thread to wait at most 10 SECONDS for an available connection

  • To have at most 200 connections associated with the pool

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToConnectionPoolSettings(builder ->
builder.maxWaitTime(10, SECONDS)
.maxSize(200)
.build());

Chain the applyToServerSettings() method to modify the driver's behavior when monitoring each MongoDB deployment.

The following table describes all the methods you can chain to your settings to modify the driver's behavior:

Method
Description
addServerListener()
Adds a listener for server-related events.
addServerMonitorListener()
Adds a listener for server monitor-related events.
applyConnectionString()
Uses the settings from a ConnectionString object.
applySettings()
Uses the server settings specified in a ServerSettings object.
heartbeatFrequency()
Sets the interval for a cluster monitor to attempt reaching a server.

Default: 10 seconds
minHeartbeatFrequency()
Sets the minimum interval for server monitoring checks.

Default: 500 milliseconds

This example specifies the following driver behavior in a MongoDB deployment:

  • The minimum interval for server monitoring checks to be at least 700 MILLISECONDS

  • The cluster monitor to attempt reaching a server every 15 SECONDS

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToServerSettings(builder ->
builder.minHeartbeatFrequency(700, MILLISECONDS)
.heartbeatFrequency(15, SECONDS))
.build());

Chain the applyToSocketSettings() method to modify the driver's behavior when connecting and communicating with your MongoDB deployment.

The following table describes the methods you can chain to your settings to modify the driver's behavior:

Method
Description
applyConnectionString()
Uses the settings from a ConnectionString object.
applySettings()
Uses the socket settings specified in a SocketSettings object.
connectTimeout()
Sets the maximum time to connect to an available socket before throwing a timeout exception.

Default: 10 seconds
readTimeout()
Sets the maximum time to read from an available socket before throwing a timeout exception.

Default: 0, which indicates no timeout
receiveBufferSize()
Sets the socket's buffer size when receiving.

Default: The operating system default
sendBufferSize()
Sets the socket's buffer size when sending.

Default: The operating system default

This example specifies the following driver behavior in a MongoDB socket:

  • To connect to an available socket within 10 SECONDS

  • To read from an available socket within 15 SECONDS

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToSocketSettings(builder ->
builder.connectTimeout(10, SECONDS)
.readTimeout(15, SECONDS))
.build());

Chain the applyToSslSettings() method to modify the driver's behavior when using TLS/SSL to secure a connection between your application and MongoDB.

The following table describes all the methods you can chain to your settings to modify the driver's behavior:

Method
Description
applyConnectionString()
Uses the settings from a ConnectionString object.
applySettings()
Uses the TLS/SSL settings specified in a SslSettings object.
context()
Sets the SSLContext for use when you enable TLS/SSL.
enabled()
Whether to enable TLS/SSL. (You must enable this for Atlas clusters.)
invalidHostNameAllowed()
Whether to allow a mismatch between the server’s hostname and the hostname specified by the TLS certificate.

This example specifies for the driver to enable TLS/SSL when connecting to MongoDB:

MongoClient mongoClient = MongoClients.create(
MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>"))
.applyToSslSettings(builder ->
builder.enabled(true))
.build());

Back

Connection Options