Docs Menu
Docs Home
/ / /
Kotlin Coroutine
/ /

Specify MongoClient Settings

On this page

  • Overview
  • MongoClient Settings
  • Cluster Settings
  • Socket Settings
  • Connection Pool Settings
  • Server 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:

  • MongoClient Settings

  • Cluster Settings

  • Socket Settings

  • Connection Pool Settings

  • Server Settings

  • TLS/SSL Settings

You can control the behavior of your MongoClient by creating and passing in a MongoClientSettings object to the MongoClient.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()
codecRegistry()
Sets the codec registry. Sets the codec registry.
commandListenerList()
compressorList()
Sets the compressors to use for compressing messages to the server.
credential()
Sets the credential.
readConcern()
Sets the read concern.
readPreference()
retryReads()
Whether the driver should retry reads if a network error occurs.
retryWrites()
Whether the driver should retry writes if a network error occurs.
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()

This example demonstrates specifying a ConnectionString:

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

Tip

Each setting has an applyConnectionString() method. They are rarely needed within the settings, so you should use this method as shown in the preceding example.

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

val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("mongodb+srv:/<db_username>:<db_password>@<hostname>:<port>?connectTimeoutMS(2000)"))
.applyToSocketSettings{ builder ->
builder.connectTimeout(5, TimeUnit.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 Kotlin 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 server.
localThreshold()
Sets the amount of time that a server’s round trip can take and still be eligible for server selection.
mode()
Sets how to connect to a MongoDB server.
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.
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.

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.

val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("mongodb+srv://host1.acme.com"))
.build()
)
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:

val mongoClient = MongoClient.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 applyToSocketSettings() method to modify the driver's behavior when connecting and communicating with your MongoDB server.

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 socket settings specified in a SocketSettings object.
applyToProxySettings()
Applies the ProxySettings.Builder block and then sets the proxySettings field.
connectTimeout()
Sets the maximum time to connect to an available socket before throwing a timeout exception.
readTimeout()
Sets the maximum time to read to an available socket before throwing a timeout exception.
receiveBufferSize()
Sets the socket's buffer size when receiving.
sendBufferSize()
Sets the socket's buffer size when sending.

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

val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<your connection string>"))
.applyToSocketSettings{ builder ->
builder
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(15, TimeUnit.SECONDS)
}
.build()
)

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.
maxWaitTime()
Sets the maximum time to wait for an available connection.
maxSize()
Sets the maximum amount of connections associated with a connection pool.
minSize()
Sets the minimum amount of connections associated with a connection pool.

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

val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<your connection string>"))
.applyToConnectionPoolSettings{ builder ->
builder
.maxWaitTime(10, TimeUnit.SECONDS)
.maxSize(200)
}
.build()
)

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

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.
minHeartbeatFrequency()
Sets the minimum interval for server monitoring checks.
serverMonitoringMode()
Specifies which server monitoring protocol the driver uses.

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

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

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

val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<your connection string>"))
.applyToServerSettings{ builder ->
builder
.minHeartbeatFrequency(700, TimeUnit.MILLISECONDS)
.heartbeatFrequency(15, TimeUnit.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:

val mongoClient = MongoClient.create(
MongoClientSettings.builder()
.applyConnectionString(ConnectionString("<your connection string>"))
.applyToSslSettings{ builder ->
builder.enabled(true)
}
.build()
)

Back

Connection Options