Specify MongoClient Settings
On this page
Overview
In this guide, you can learn about the different settings to control
the behavior of your MongoClient
.
The following sections describe commonly used settings:
MongoClient 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 the methods you can chain to modify your connection behavior:
Method | Description |
---|---|
| Adds a listener for command events. |
| Sets the logical name of the application using the |
| Applies the settings from the given |
| Applies the |
| Applies the |
| Applies the |
| Applies the |
| Applies the |
| Applies the |
| Sets the auto-encryption settings. 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 . |
| Sets the codec registry. |
| Sets the command listeners. |
| Sets the compressors to use for compressing messages to the server. |
| Sets the credential. |
| Sets the read concern. |
| |
| |
| |
| Sets the server API to use when sending commands to the server. |
| Sets TransportSettings. |
| Sets the UUID representation to use when encoding instances of UUID and decoding BSON binary values with subtype of 3. |
| Sets the write concern. Default: WriteConcern#ACKNOWLEDGED . For more information about
the default value, see Implicit Default Write Concern. |
Example
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(5L, 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.
Cluster Settings
Chain the applyToClusterSettings() method to modify the driver's behavior when interacting with your MongoDB cluster.
The following table describes the methods you can chain to your settings to modify the driver's behavior:
Method | Description | |||
---|---|---|---|---|
| Adds a listener for cluster-related events. | |||
| Uses the settings from a | |||
| Uses the cluster settings specified in a | |||
| Sets all the specified locations of a Mongo deployment. | |||
| Sets the amount of time that a server’s round trip can take and still
be eligible for server selection. Default: 15 milliseconds | |||
| Sets how to connect to a MongoDB deployment. | |||
| Sets the type of cluster required for the cluster. | |||
| Sets the replica set name required for the cluster. | |||
| Sets the maximum time to select a primary node before throwing a
timeout exception. Default: 30 seconds | |||
| Adds a server selector to apply before server selection. | |||
| Sets the host name to use to look up an SRV DNS record to find the
MongoDB hosts. If you want to enable the processing of TXT records associated with the host,
specify the SRV host in the connection string
using the applyConnectionString() method.For example:
| |||
| 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. |
Example
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.
Connection Pool Settings
Chain the applyToConnectionPoolSettings() method to modify the way the driver manages its connection pool.
The following table describes the methods you can chain to your settings to modify the driver's behavior:
Method | Description |
---|---|
| Adds a listener for connection pool-related events. |
| Uses the settings from a |
| Uses the connection pool settings specified in a
|
| Sets the frequency for running a maintenance job. |
| Sets the time to wait before running the first maintenance job. |
| Sets the maximum time a connection can be idle before it's closed. |
| Sets the maximum time a pooled connection can be alive before it's closed. |
| Sets the maximum number of connections associated with a connection
pool. Default: 100 |
| Sets the maximum time to wait for an available connection. Default: 2 minutes |
| 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.
Example
This example specifies the following driver behavior in a pool of
Connection
types:
The thread to wait at most
10 SECONDS
for an available connectionTo 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());
Logger Settings
Chain the applyToLoggerSettings() method to modify the logging behavior of the driver.
The following table describes the methods you can chain to your settings to modify the logging behavior:
Method | Description |
---|---|
| Sets the maximum document length, in characters, of a single log
message. Default: 1000 |
Example
This example specifies that the maximum number of characters for a single log
message is set to 5000
characters.
MongoClient mongoClient = MongoClients.create( MongoClientSettings.builder().applyConnectionString(new ConnectionString("<your connection string>")) .applyToLoggerSettings(builder -> builder.maxDocumentLength(5_000)) .build());
Server Settings
Chain the applyToServerSettings() method to modify the driver's behavior when monitoring each MongoDB deployment.
The following table describes the methods you can chain to your settings to modify the driver's behavior:
Method | Description |
---|---|
| Adds a listener for server-related events. |
| Adds a listener for server monitor-related events. |
| Uses the settings from a |
| Uses the server settings specified in a |
| Sets the interval for a cluster monitor to attempt reaching a server. Default: 10 seconds |
| Sets the minimum interval for server monitoring checks. Default: 500 milliseconds |
Example
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());
Socket Settings
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 |
---|---|
| Uses the settings from a |
| Uses the socket settings specified in a |
| Sets the maximum time to connect to an available socket before throwing
a timeout exception. Default: 10 seconds |
| Sets the maximum time to read from an available socket before throwing a
timeout exception. Default: 0 , which indicates no timeout |
| Sets the socket's buffer size when receiving. Default: The operating system default |
| Sets the socket's buffer size when sending. Default: The operating system default |
Example
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());
TLS/SSL Settings
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 the methods you can chain to your settings to modify the driver's behavior:
Method | Description |
---|---|
| Uses the settings from a |
| Uses the TLS/SSL settings specified in a |
| Sets the |
| Whether to enable TLS/SSL. (You must enable this for Atlas clusters.) |
| Whether to allow a mismatch between the server’s hostname and the hostname specified by the TLS certificate. |
Example
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());