connection-options
- connection-options
- Specify Connection Options
- Overview
- How to Specify Connection Options
- Replica Set Options
- TLS Options
- Timeout Options
- Compression Options
- Connection Pool Options
- Write Concern Options
- Read Concern Options
- Read Preference Options
- Authentication Options
- Server Selection and Discovery Options
- Retry Options
- Miscellaneous Options
- Additional Information
For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt
<!-- Tab options on this page. Append to the .md URL to filter: ?tabs=<id,...> select specific tabs (e.g. ?tabs=nodejs,shell) ?allTabs=true include every tab (no param) default: one tab per tabset
Available tabs: other tabs: mongoc-connection-uri, mongo-url-builder, mongo-client-settings -->
Specify Connection Options
Overview
This page describes the connection options available in the C driver and explains how to specify them for your MongoDB connection by using a connection string or URI option.
How to Specify Connection Options
The following sections describe the ways in which you can specify connection options.
Use the Connection String
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.
Use the URI Options API
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:
-
Create a
mongoc_uri_tstruct with your connection string -
Use a URI option function to specify your desired connection option
-
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);
Replica Set Options
Connection String
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](https://www.mongodb.com/docs/manual/reference/connection-string.md#std-label-mongodb-uri 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:
mongoc_uri_t *uri = mongoc_uri_new("mongodb://localhost:27017/?directConnection=true");
Replica Set
The name of the replica set to connect to.
Data Type: char*
Default Value: NULL
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?replicaSet=yourReplicaSet");
TLS Options
Connection String
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.
Data Type: boolean
Default Value: false
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true");
Allow Insecure TLS
Specifies whether to relax TLS constraints as much as possible. This can include allowing invalid certificates or hostname mismatches.
Data Type: boolean
Default Value: false
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true&tlsInsecure=true");
TLS Disable Certificate Revocation Check
Whether to disable certificate revocation checking during the TLS handshake.
Data Type: boolean
Default Value: false
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?tls=true&tlsDisableCertificateRevocationCheck=true");
For more information on TLS options, see the [Configure Transport Layer Security (TLS)](https://www.mongodb.com/docs/languages/c/c-driver/current/security/tls.md#std-label-c-tls guide.
Timeout Options
Connection String
Connect Timeout
The length of time the driver tries to establish a single TCP socket connection to the server before timing out.
Data Type: integer
Default Value: 10000 (10 seconds)
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://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.
Data Type: integer
Default Value: 300000 (5 minutes)
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?socketTimeoutMS=60000");
Compression Options
Connection String
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: char*
Default Value: NULL
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?compressors=zlib,snappy");
Connection Pool Options
Connection String
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: integer
Default Value: 100
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?maxPoolSize=150");
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: integer
Default Value: -1 (no timeout)
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?waitQueueTimeoutMS=30000");
To learn more about connection pools, see the [Connection Pools](https://www.mongodb.com/docs/languages/c/c-driver/current/connect/connection-options/connection-pools.md#std-label-c-connection-pools guide.
Write Concern Options
Connection String
w
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](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-w in the MongoDB Server manual.
Data Type: integer or char*
Default Value: 1 or “majority”
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?w=2");
w Timeout
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](https://www.mongodb.com/docs/manual/reference/write-concern.md#std-label-wc-wtimeout in the MongoDB Server manual.
Data Type: integer
Default Value: 0
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?wTimeoutMS=5000");
Journal
The j component of the write concern, which requests acknowledgment that the MongoDB instances have written to the on-disk journal.
Data Type: boolean
Default Value: false
To learn more about the j option, see [Write Concern](https://www.mongodb.com/docs/manual/reference/write-concern/#j-option in the MongoDB Server manual.
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?journal=true");
Read Concern Options
Connection String
Read Concern Level
The client's read concern level. For more information, see the [Read Concern](https://www.mongodb.com/docs/manual/reference/read-concern.md#std-label-read-concern reference in the MongoDB Server manual.
Data Type: char*
Default Value: local
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readConcernLevel=local");
Read Preference Options
Connection String
Read Preference
The client's default read-preference settings. See [Read Preference](https://www.mongodb.com/docs/manual/core/read-preference.md#std-label-read-preference in the MongoDB Server manual for more information.
Data Type: char*
Default Value: primary
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readPreference=primaryPreferred");
Max Staleness
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.
Data Type: integer
Default Value: -1
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?readPreference=secondary&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: integer
Default Value: 15
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?localThresholdMS=150");
Authentication Options
Connection String
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](https://www.mongodb.com/docs/languages/c/c-driver/current/security/authentication.md#std-label-c-auth or the [Enterprise Authentication Mechanisms](https://www.mongodb.com/docs/languages/c/c-driver/current/security/enterprise-authentication.md#std-label-c-enterprise-auth guide.
Data Type: char*
Default Value: SCRAM-SHA-256 (for MongoDB 4.0 and later)
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?authSource=admin&authMechanism=GSSAPI");
Server Selection and Discovery Options
Connection String
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.
Data Type: integer
Default Value: 10000 for pooled clients, 60000 for single-threaded clients
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?heartbeatFrequencyMS=5000");
Server Selection Timeout
The length of time the driver tries to select a server before timing out.
Data Type: integer
Default Value: 30000
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?serverSelectionTimeoutMS=40000");
Socket Check Interval
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.
Data Type: integer
Default Value: 5000
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?socketCheckIntervalMS=10000");
Retry Options
Connection String
Retry Reads
Enables retryable reads.
Data Type: boolean
Default Value: true
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?retryReads=false");
Retry Writes
Enables retryable writes.
Data Type: boolean
Default Value: true with TLS support, false otherwise
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?retryWrites=false");
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 C Driver to version 2.3 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
Connection String
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: char*
Default Value: empty
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?appName=yourAppName");
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
SrvMaxHostsproperty -
You're not using the
DirectConnectionproperty
Data Type: boolean
Default Value: false
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?loadBalanced=true");
SrvMaxHosts
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: integer
Default Value: 0
Example:
mongoc_uri_t *uri = mongoc_uri_new("mongodb+srv://localhost:27017/?srvMaxHosts=5");
Additional Information
For more information about the types used on this page, see the following API documentation:
