Docs Menu
Docs Home
/ /

Specify Connection Options

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

The following sections describe the ways in which you can specify connection options.

If you pass a connection string to the monogoc_client_t structure, you can include connection options in the string as <name>=<value> pairs. 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:

mongoc_init();
// Specifies the connection options in the connection string
const char *uri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true";
// Creates a new client
mongoc_client_t *client = mongoc_client_new_from_uri_with_error(uri, &error);
if (!client) {
fprintf(stderr, "%s\n", error.message);
goto cleanup;
}
// Use client...
cleanup:
mongoc_client_destroy(client);
mongoc_uri_destroy(uri);

To learn more about the options that you can specify in a connection string, see Connection String Options in the MongoDB Server manual.

You can use URI options to configure connection settings in code rather than in a connection string. Configuring the connection this way makes it easier to change settings at runtime, helps you catch errors during compilation, and provides more configuration options than the connection string.

To set connection options by using the URI option, perform the following steps:

  1. Create a mongoc_uri_t struct with your connection string

  2. Use a URI option function to specify your desired connection option

  3. Create a new client with the URI by passing the URI to mongoc_client_new_from_uri()

The following code example shows how to perform the preceding steps:

mongoc_uri_t *uri = mongoc_uri_new_with_error("mongodb+srv://localhost:27017/", &error);
if (!uri) {
fprintf(stderr, "%s\n", error.message);
goto cleanup;
}
// Specifies the connection options by using the URI options API
if (!mongoc_uri_set_option_as_int32(uri, MONGOC_URI_CONNECTTIMEOUTMS, 60000)) {
fprintf(stderr, "Failed to set '%s'\n", MONGOC_URI_CONNECTTIMEOUTMS);
goto cleanup;
}
if (!mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLS, true)) {
fprintf(stderr, "Failed to set '%s'\n", MONGOC_URI_TLS);
goto cleanup;
}
// Creates a new client
client = mongoc_client_new_from_uri_with_error(uri, &error);
if (!client) {
fprintf(stderr, "%s\n", error.message);
goto cleanup;
}
// Use client...
cleanup:
mongoc_client_destroy(client);
mongoc_uri_destroy(uri);

The following sections describe the connection options available in the C driver and how to specify them by using a connection string directly or a URI option.

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.

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

mongoc_uri_t *uri = mongoc_uri_new("mongodb://localhost:27017/?directConnection=true");

The name of the replica set to connect to. The default value is null.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?replicaSet=yourReplicaSet");

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.

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

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_DIRECTCONNECTION, true);

The name of the replica set to connect to. The default value is null.

mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_REPLICASET, "yourReplicaSet");

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.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true");

Specifies whether to relax TLS constraints as much as possible. This can include allowing invalid certificates or hostname mismatches. The default value is false.

The following code example shows how to set this option to true:

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true&tlsAllowInvalidCertificates=true");

Whether to disable certificate revocation checking during the TLS handshake. The default value is false.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true&tlsDisableCertificateRevocationCheck=true");

TLS/SSL options, including client certificates, revocation handling, and enabled and disabled TLS/SSL protocols. The default value is null.

This option can only be set by using URI Options. To learn how to set SSL Options, see the SSL Options section under the MongoC URI Option tab.

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.

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLS, true);

Specifies whether to relax TLS constraints as much as possible. This can include allowing invalid certificates or hostname mismatches. The default value is false.

The following code example shows how to set this option to true:

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLSINSECURE, true);

Whether to disable certificate revocation checking during the TLS handshake. The default value is false.

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_TLSDISABLECERTIFICATEREVOCATIONCHECK, true);

TLS/SSL options, including client certificates, revocation handling, and enabled and disabled TLS/SSL protocols. The default value is null.

If SslSettings.CheckCertificateRevocation is set to false and AllowInsecureTls is set to true, the C driver throws an exception.

mongoc_client_t *client;
mongoc_ssl_opt_t ssl_opts = {0};
ssl_opts.pem_file = "/path/to/client-cert.pem";
ssl_opts.pem_pwd = "password";
ssl_opts.ca_file = "/path/to/ca.pem";
ssl_opts.allow_invalid_hostname = false;
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true");
client = mongoc_client_new_from_uri(uri);
mongoc_client_set_ssl_opts(client, &ssl_opts);

For more information on TLS options, see the Configure Transport Layer Security (TLS) guide.

The length of time the driver tries to establish a single TCP socket connection to the server before timing out. The default value is 10 seconds.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://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.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?socketTimeoutMS=60000");

The length of time the driver tries to establish a single TCP socket connection to the server before timing out. The default value is 10 seconds.

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_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.

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SOCKETTIMEOUTMS, 60000);

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. The default value is empty.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?compressors=zlib,snappy");

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. The default value is empty.

mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_COMPRESSORS, "zlib,snappy");

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

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?maxPoolSize=150");

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

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?waitQueueTimeoutMS=30000");

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

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_MAXPOOLSIZE, 150)

You can also set the max connection pool size by using a mongoc_client_pool_t structure:

mongoc_client_pool_t *pool = mongoc_client_pool_new(uri);
// Specifies max pool size
mongoc_client_pool_max_size(pool, 150);

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

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_WAITQUEUETIMEOUTMS, 30000);

To learn more about connection pools, see the 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.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?w=2");

The wtimeoutms component of the write concern, which specifies a time limit for the write concern. To learn more about the wtimeout option, see Write Concern in the MongoDB Server manual.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?wTimeoutMS=5000");

The j component of the write concern, which requests acknowledgment that the MongoDB instances have written to the on-disk journal. The default value depends on the value in the writeConcernMajorityJournalDefault setting. To learn more about the j option, see Write Concern in the MongoDB Server manual.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?journal=true");

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 set w by using the MONGOC_URI_W option:

// Use the int32 version of the mongoc_uri_t set function to set integer values
mongoc_uri_set_option_as_int32(uri, MONGOC_URI_W, 2);
// Use the utf8 version of the mongoc_uri_t set function to set string values
mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_W, "majority");

You can also set w by using a mongoc_write_concern_t structure:

// Creates a write concern structure
mongoc_write_concern_t *write_concern = mongoc_write_concern_new();
// Sets w=2
mongoc_write_concern_set_w(write_concern, 2);
mongoc_client_set_write_concern(client, write_concern);

The wtimeoutms component of the write concern, which specifies a time limit for the write concern. To learn more about the wtimeout option, see Write Concern in the MongoDB Server manual.

You can set wtimeoutms by using the MONGOC_URI_WTIMEOUTMS option:

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_WTIMEOUTMS, 5000);

You can also set wtimeoutms by using a mongoc_write_concern_t structure:

// Creates a write concern structure
mongoc_write_concern_t *write_concern = mongoc_write_concern_new();
// Sets w=2
mongoc_write_concern_set_wtimeout(write_concern, 5000);
// Apply write concern to client
mongoc_client_set_write_concern(client, write_concern);

The j component of the write concern, which requests acknowledgment that the MongoDB instances have written to the on-disk journal. The default value depends on the value in the writeConcernMajorityJournalDefault setting. To learn more about the j option, see Write Concern in the MongoDB Server manual.

You can set journal by using the MONGOC_URI_JOURNAL option:

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_JOURNAL, true);

You can also set journal by using a mongoc_write_concern_t structure:

// Creates a write concern structure
mongoc_write_concern_t *write_concern = mongoc_write_concern_new();
// Sets journal to true
mongoc_write_concern_set_journal(write_concern, true);
// Apply write concern to client
mongoc_client_set_write_concern(client, write_concern);

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

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readConcernLevel=local");

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

You can set the read concern level by using the MONGOC_URI_READCONCERNLEVEL option:

mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_READCONCERNLEVEL, "local")

You can also set the read concern level by using a mongoc_read_concern_t structure:

mongoc_read_concern_t *read_concern = mongoc_read_concern_new();
// Set the read concern level to "local"
mongoc_read_concern_set_level(read_concern, MONGOC_READ_CONCERN_LEVEL_LOCAL);
mongoc_client_set_read_concern(client, read_concern);

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

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readPreference=primaryPreferred");

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.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readPreference=secondary&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. The default value is 15 milliseconds.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?localThresholdMS=150");

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

You can set the read preference by using a mongoc_read_prefs_t structure:

mongoc_client_t *client = mongoc_client_new("mongodb+srv://localhost:27017/");
// Specifies the read preference
mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED);
mongoc_client_set_read_prefs(client, read_prefs);

You can also set the read preference by using the MONGOC_URI_READPREFERENCE option:

mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_READPREFERENCE, "primaryPreferred")

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.

You can set the max staleness by using the MONGOC_URI_MAXSTALENESSSECONDS option:

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_MAXSTALENESSSECONDS, 120);

You can also set the max staleness by using a mongoc_read_prefs_t structure:

mongoc_client_t *client = mongoc_client_new("mongodb+srv://localhost:27017/");
mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
// Specifies max staleness to 120 seconds
mongoc_read_prefs_set_max_staleness_seconds(read_prefs, 120);
mongoc_client_set_read_prefs(client, read_prefs);

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. The default value is 15 milliseconds.

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_LOCALTHRESHOLDMS, 150);

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 or the Enterprise Authentication Mechanisms guide.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?authSource=admin&authMechanism=GSSAPI");

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 or the Enterprise Authentication Mechanisms guide.

mongoc_uri_set_auth_mechanism(uri, "GSSAPI");

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.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?heartbeatFrequencyMS=5000");

The length of time the driver tries to select a server before timing out. The default value is 30000 ms (30 seconds).

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?serverSelectionTimeoutMS=40000");

Only applies to single threaded clients. If a socket has not been used within this time, the driver checks the connection with a quick "hello" call before it is used again. Defaults to 5000 ms (5 seconds).

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?socketCheckIntervalMS=10000");

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.

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_HEARTBEATFREQUENCYMS, 5000);

The length of time the driver tries to select a server before timing out. The default value is 30000 ms (30 seconds).

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SERVERSELECTIONTIMEOUTMS, 40000);

Only applies to single threaded clients. If a socket has not been used within this time, the driver checks the connection with a quick "hello" call before it is used again. Defaults to 5000 ms (5 seconds).

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SOCKETCHECKINTERVALMS, 10000);

Enables retryable reads. The default value is true.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?retryReads=false");

Enables retryable writes. The default value is true.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?retryWrites=false");

Enables retryable reads. The default value is true.

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_RETRYREADS, false)

Enables retryable writes. The default value is true.

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_RETRYWRITES, false);

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. The default value is empty.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?appName=yourAppName");

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 default value is false.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://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. The default value is 0.

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.

mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?srvMaxHosts=5");

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. The default value is empty.

mongoc_uri_set_option_as_utf8(uri, MONGOC_URI_APPNAME, "yourAppName");

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 default value is false.

mongoc_uri_set_option_as_bool(uri, MONGOC_URI_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. The default value is 0.

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.

mongoc_uri_set_option_as_int32(uri, MONGOC_URI_SRVMAXHOSTS, 5);

For more information about the types used on this page, see the following API documentation:

Back

Create a MongoClient

On this page