Overview
This page describes the connection options available in the .NET/C# Driver and explains how to apply them to your MongoDB connection.
How to Specify Connection Options
The following sections describe the ways in which you can specify connection options.
Using the Connection URI
If you pass a connection URI to the MongoClient
constructor, you can include
connection options in the string as <name>=<value>
pairs. In the following example,
the connection URI contains the connectTimeoutMS
option with a value of 60000
and the tls
option with a value of true
:
const string uri = "mongodb+srv:/localhost:27017/?connectTimeoutMS=60000&tls=true";
To learn more about the options that you can specify in a connection URI, see Connection String Options in the MongoDB Server manual.
Using MongoClientSettings
You can use a MongoClientSettings
object to configure connection settings in code
rather than in a connection URI. 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 URI.
To set connection options in a MongoClientSettings
object, perform the
following steps:
Create an instance of the
MongoClientSettings
classSet properties on the instance to configure the connection
Pass the instance to the
MongoClient
constructor
The following code example shows how to perform the preceding steps:
var settings = new MongoClientSettings() { Scheme = ConnectionStringScheme.MongoDBPlusSrv, Server = new MongoServerAddress("localhost", 27017), ConnectTimeout = TimeSpan.FromMilliseconds(60000), UseTls = true }; var client = new MongoClient(settings);
You can also create a MongoClientSettings
object from a connection string by calling the
MongoClientSettings.FromConnectionString()
method and passing the connection string,
as shown in the following example. This is useful if you already have a connection string
but want to modify some settings programmatically, or if you must specify settings
that aren't available in the connection string.
const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; var settings = MongoClientSettings.FromConnectionString(connectionUri); settings.ServerApi = new ServerApi(ServerApiVersion.V1); var client = new MongoClient(settings);
Alternatively, you can create a MongoClientSettings
object from a MongoUrl
object
by calling the MongoClientSettings.FromUrl()
method and passing the MongoUrl
object, as shown in the following example. This is useful if you already have a MongoUrl
object but want to specify settings that aren't available in the MongoUrl
class.
const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; var url = new MongoUrl(connectionUri); var settings = MongoClientSettings.FromUrl(url); settings.ServerApi = new ServerApi(ServerApiVersion.V1); var client = new MongoClient(settings);
Using MongoUrlBuilder
You can use a MongoUrlBuilder
object to create and configure connection settings on
a MongoUrl
object. A MongoUrl
is a strongly typed representation of a
connection URI, and is useful when reading a connection URI directly from
another source. Using a MongoUrl
object has many of the same advantages as using
a MongoClientSettings
object, although the two classes contain different properties
and methods.
To use a MongoUrlBuilder
object, create an instance of the class and set the
necessary configuration properties. To create a MongoUrl
object from the
MongoUrlBuilder
, call the MongoUrlBuilder.ToMongoUrl()
method. You can pass the
MongoUrl
object to the MongoClient
constructor. The following code example shows
this process:
const string connectionUri = "mongodb+srv://localhost:27017/?connectTimeoutMS=60000&tls=true"; var builder = new MongoUrlBuilder(connectionUri) { ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream }; var url = builder.ToMongoUrl(); var client = new MongoClient(url);
Connection Options
The following sections describe the connection options available in the
.NET/C# Driver and how to specify them by using a MongoClientSettings
or
MongoUrlBuilder
object.
Replica Set Options
DirectConnection
Specifies whether to force dispatch all operations to the host.
If you specify this option, the driver doesn't accept the
DNS seed list connection format.
You must use the standard connection URI format
instead. The default value is false
.
This property must be set to false
if you specify more than one
host name.
var settings = new MongoClientSettings { DirectConnection = true, };
ReplicaSetName
The name of the replica set to connect to. The default value is null
.
var settings = new MongoClientSettings { ReplicaSetName = "yourReplicaSet", };
DirectConnection
Specifies whether to force dispatch all operations to the host.
If you specify this option, the driver doesn't accept the
DNS seed list connection format.
You must use the standard connection URI format
instead. The default value is false
.
This property must be set to false
if you specify more than one
host name.
var builder = new MongoUrlBuilder { DirectConnection = true, };
ReplicaSetName
The name of the replica set to connect to. The default value is null
.
var builder = new MongoUrlBuilder { ReplicaSetName = "yourReplicaSet", };
TLS Options
AllowInsecureTls
Specifies whether to relax TLS constraints as much as possible. This can include
allowing invalid certificates or hostname mismatches. The default value is false
.
If this property is set to true
and SslSettings.CheckCertificateRevocation
is set to false
, the .NET/C# Driver will throw an exception.
The following code example shows how to set this option to true
:
var settings = new MongoClientSettings { AllowInsecureTls = true, };
SslSettings
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 .NET/C# Driver throws
an exception.
var settings = new MongoClientSettings(); settings.SslSettings = new SslSettings() { CheckCertificateRevocation = false, ClientCertificateSelectionCallback = new LocalCertificateSelectionCallback() { ... }, ClientCertificates = new List<X509Certificate>() { ... }, EnabledSslProtocols = SslProtocols.Tls13, ServerCertificateValidationCallback = new RemoteCertificateValidationCallback() { ... } };
UseTls
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
.
var settings = new MongoClientSettings { UseTls = true, };
AllowInsecureTls
Specifies whether to relax TLS constraints as much as possible. This can include
allowing invalid certificates or hostname mismatches. The default value is false
.
If this property is set to true
and SslSettings.CheckCertificateRevocation
is set to false
, the .NET/C# Driver will throw an exception.
The following code example shows how to set this option to true
:
var builder = new MongoUrlBuilder { AllowInsecureTls = true, };
TlsDisableCertificateRevocationCheck
Whether to disable certificate revocation checking during the TLS handshake. The
default value is false
.
var builder = new MongoUrlBuilder { TlsDisableCertificateRevocationCheck = true };
UseTls
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
.
var builder = new MongoUrlBuilder { UseTls = true, };
Timeout Options
ConnectTimeout
The length of time the driver tries to establish a single TCP socket connection to the server before timing out. The default value is 30 seconds.
var settings = new MongoClientSettings { ConnectTimeout = TimeSpan.FromSeconds(60), };
SocketTimeout
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.
var settings = new MongoClientSettings { ConnectTimeout = TimeSpan.FromSeconds(60), };
ConnectTimeout
The length of time the driver tries to establish a single TCP socket connection to the server before timing out. The default value is 30 seconds.
var builder = new MongoUrlBuilder { ConnectTimeout = TimeSpan.FromSeconds(60), };
SocketTimeout
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.
var builder = new MongoUrlBuilder { SocketTimeout = TimeSpan.FromSeconds(60), };
Compression Options
Compressors
The preferred compression types, in order, for wire-protocol messages sent to
or received from the server. The driver uses the first of these compression types
that the server supports. The default value is null
.
var settings = new MongoClientSettings { Compressors = new List<CompressorConfiguration>() { new(CompressorType.Zlib), new(CompressorType.Snappy) } };
Compressors
The preferred compression types, in order, for wire-protocol messages sent to
or received from the server. The driver uses the first of these compression types
that the server supports. The default value is null
.
var builder = new MongoUrlBuilder { Compressors = new List<CompressorConfiguration>() { new(CompressorType.Zlib), new(CompressorType.Snappy) } };
Connection Pool Options
MaxConnecting
The greatest number of connections a driver's connection pool may be
establishing concurrently. The default value is 2
.
var settings = new MongoClientSettings { MaxConnecting = 3, };
MaxConnectionIdleTime
The length of time a connection can be idle before the driver closes it. The default value is 10 minutes.
var settings = new MongoClientSettings { MaxConnectionIdleTime = TimeSpan.FromMinutes(8), };
MaxConnectionLifeTime
The length of time a connection can be pooled before expiring. The default value is 30 minutes.
var settings = new MongoClientSettings { MaxConnectionLifeTime = TimeSpan.FromMinutes(40), };
MaxConnectionPoolSize
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
.
var settings = new MongoClientSettings { MaxConnectionPoolSize = 150, };
MinConnectionPoolSize
The number of connections the driver creates and keeps in the connection
pool even when no operations are occurring. This count includes connections
in use. The default value is 0
.
var settings = new MongoClientSettings { MinConnectionPoolSize = 3, };
WaitQueueTimeout
The length of time the driver tries to check out a connection from a server's connection pool before timing out. The default value is two minutes.
var settings = new MongoClientSettings { WaitQueueTimeout = TimeSpan.FromSeconds(30), };
MaxConnecting
The greatest number of connections a driver's connection pool may be
establishing concurrently. The default value is 2
.
var builder = new MongoUrlBuilder { MaxConnecting = 3, };
MaxConnectionIdleTime
The length of time a connection can be idle before the driver closes it. The default value is 10 minutes.
var builder = new MongoUrlBuilder { MaxConnectionIdleTime = TimeSpan.FromMinutes(8), };
MaxConnectionLifeTime
The length of time a connection can be pooled before expiring. The default value is 30 minutes.
var builder = new MongoUrlBuilder { MaxConnectionLifeTime = TimeSpan.FromMinutes(40), };
MaxConnectionPoolSize
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
.
var builder = new MongoUrlBuilder { MaxConnectionPoolSize = 150, };
MinConnectionPoolSize
The number of connections the driver creates and keeps in the connection
pool even when no operations are occurring. This count includes connections
in use. The default value is 0
.
var builder = new MongoUrlBuilder { MinConnectionPoolSize = 3, };
WaitQueueTimeout
The length of time the driver tries to check out a connection from a server's connection pool before timing out. The default value is two minutes.
var builder = new MongoUrlBuilder { WaitQueueTimeout = TimeSpan.FromSeconds(30), };
Write Concern Options
WriteConcern
The default write-concern settings, including write timeout and
journaling, for the client. The default value is WriteConcern.Acknowledged
.
See Write Concern in the
MongoDB Server manual for more information.
var settings = new MongoClientSettings(); settings.WriteConcern = MongoDB.Driver.WriteConcern.Acknowledged; settings.WriteConcern = new WriteConcern( w: 1, wTimeout: new TimeSpan(0, 0, 0, 30, 0), fsync: true, journal: true );
FSync
The FSync component of the write concern. The default value is false
. To learn
more about the fsync
command, see fsync
in the MongoDB Server manual.
var builder = new MongoUrlBuilder { FSync = true };
Journal
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.
var builder = new MongoUrlBuilder { Journal = true };
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
in the MongoDB Server manual.
var builder = new MongoUrlBuilder { W = 2 };
WTimeout
The wtimeout
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.
var builder = new MongoUrlBuilder { WTimeout = TimeSpan.FromSeconds(5) };
Read Concern Options
ReadConcern
The client's read concern. The default value is ReadConcern.Default
.
For more information, see Read Concern in the
MongoDB Server manual.
var settings = new MongoClientSettings { ReadConcern = MongoDB.Driver.ReadConcern.Local, };
ReadConcernLevel
The client's read concern level. The default value is ReadConcern.Local
.
For more information, see read concern.
var builder = new MongoUrlBuilder { ReadConcernLevel = MongoDB.Driver.ReadConcernLevel.Local, };
Read Preference Options
ReadPreference
The client's default read-preference settings. MaxStaleness
represents the
longest replication lag, in wall-clock time, that a secondary can experience and
still be eligible for server selection. The default value is ReadPreference.Primary
.
Specifying -1
means no maximum.
See Read Preference in the MongoDB Server manual
for more information.
var settings = new MongoClientSettings { ReadPreference = MongoDB.Driver.ReadPreference.PrimaryPreferred, };
The client's default read-preference settings. MaxStaleness
represents the
longest replication lag, in wall-clock time, that a secondary can experience and
still be eligible for server selection. The default value is ReadPreference.Primary
.
Specifying -1
means no maximum.
See Read Preference in the MongoDB Server manual
for more information.
var builder = new MongoUrlBuilder { ReadPreference = MongoDB.Driver.ReadPreference.PrimaryPreferred, };
Authentication Options
Credential
Settings for how the driver authenticates to the server. This includes
authentication credentials, mechanism, source, and other settings. The default
value is null
.
If you don't specify an authentication mechanism, the driver uses either
SCRAM-SHA-1
or SCRAM-SHA-256
, depending on the server version. See
Authentication Mechanisms for available
authentication mechanisms.
var settings = new MongoClientSettings { Credential = MongoCredential.CreatePlainCredential( databaseName: "admin", username: "user", password: "password" ) };
AuthenticationMechanism
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. See
authentication mechanisms for available
authentication mechanisms.
var builder = new MongoUrlBuilder { AuthenticationMechanism = "GSSAPI", AuthenticationMechanismProperties = new Dictionary<string, string> { { "SERVICE_NAME", "other" }, { "CANONICALIZE_HOST_NAME", "true" } }, AuthenticationSource = "db" };
AuthenticationMechanismProperties
Configuration settings for the authentication mechanism specified in the
AuthenticationMechanism
property.
var builder = new MongoUrlBuilder { AuthenticationMechanism = "GSSAPI", AuthenticationMechanismProperties = new Dictionary<string, string> { { "SERVICE_NAME", "other" }, { "CANONICALIZE_HOST_NAME", "true" } }, AuthenticationSource = "db" };
AuthenticationSource
The source to authenticate the client against.
var builder = new MongoUrlBuilder { AuthenticationMechanism = "GSSAPI", AuthenticationMechanismProperties = new Dictionary<string, string> { { "SERVICE_NAME", "other" }, { "CANONICALIZE_HOST_NAME", "true" } }, AuthenticationSource = "db" };
Password
The password to use for authentication.
var builder = new MongoUrlBuilder { Username = "user", Password = "password" };
Username
The username to use for authentication.
var builder = new MongoUrlBuilder { Username = "user", Password = "password" };
Server Selection and Discovery Options
HeartbeatInterval
The interval between regular server-monitoring checks. Must be greater than or
equal to 500 milliseconds. The default value is 10000
milliseconds (10 seconds).
var settings = new MongoClientSettings { HeartbeatInterval = TimeSpan.FromSeconds(5) };
HeartbeatTimeout
The length of time a monitoring socket can be idle before timing out. The default value
is the value of the ConnectTimeout
property.
var settings = new MongoClientSettings { HeartbeatTimeout = TimeSpan.FromSeconds(5) };
LocalThreshold
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.
var settings = new MongoClientSettings { LocalThreshold = TimeSpan.FromSeconds(15) };
ServerSelectionTimeout
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.
var settings = new MongoClientSettings { ServerSelectionTimeout = TimeSpan.FromSeconds(30) };
HeartbeatInterval
The interval between regular server-monitoring checks. Must be greater than or
equal to 500 milliseconds. The default value is 10000
milliseconds (10 seconds).
var builder = new MongoUrlBuilder { HeartbeatInterval = TimeSpan.FromSeconds(5) };
HeartbeatTimeout
The length of time a monitoring socket can be idle before timing out. The default value
is the value of the ConnectTimeout
property.
var builder = new MongoUrlBuilder { HeartbeatTimeout = TimeSpan.FromSeconds(5) };
LocalThreshold
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.
var builder = new MongoUrlBuilder { LocalThreshold = TimeSpan.FromSeconds(15) };
ServerSelectionTimeout
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.
var builder = new MongoUrlBuilder { ServerSelectionTimeout = TimeSpan.FromSeconds(30) };
Encoding Options
ReadEncoding
The UTF-8 encoding to use for string deserialization. The default value is strict encoding, where the driver throws an exception when it encounters an invalid UTF-8 byte sequence
var settings = new MongoClientSettings { ReadEncoding = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true) };
WriteEncoding
The UTF-8 encoding to use for string serialization. The default value is strict encoding, where the driver throws an exception when it encounters an invalid UTF-8 byte sequence
var settings = new MongoClientSettings { WriteEncoding = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true) };
Note
MongoClientSettings Only
The ReadEncoding
and WriteEncoding
properties are available only in the
MongoClientSettings
class.
Stable API
ServerApi
Allows opting into Stable API versioning. The default value is null
. See
Stable API in the MongoDB Server manual for more
information about Stable API versioning.
var settings = new MongoClientSettings { ServerApi = new ServerApi( ServerApiVersion.V1, strict: true, deprecationErrors: true), };
Note
MongoClientSettings Only
The ServerApi
property is available only in the MongoClientSettings
class.
Retry Options
Miscellaneous Options
ApplicationName
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
the connection is established. The value is also recorded in the slow query logs
and profile collections. The default value is null
.
var settings = new MongoClientSettings { ApplicationName = "yourAppName", };
AutoEncryptionOptions
Settings for automatic client-side encryption. The default value is null
. To
learn more about client-side encryption, see
In-Use Encryption.
var settings = new MongoClientSettings { AutoEncryptionOptions = new AutoEncryptionOptions( keyVaultNamespace: new CollectionNamespace( databaseName: "keyvault", collectionName: "datakeys"), kmsProviders: new Dictionary<string, IReadOnlyDictionary<string, object>> () { { "local", new Dictionary<string, object> () { { "key", "<base64-encoded-key>" } } } } ), };
ClusterConfigurator
Low-level configuration options for sockets, TLS, cluster, and others. The default
value is null
.
var settings = new MongoClientSettings { ClusterConfigurator = builder => { builder .Subscribe<ClusterOpenedEvent>(e => { Console.WriteLine($"Cluster opened: Cluster ID = {e.ClusterId}"); }) .Subscribe<ClusterDescriptionChangedEvent>(e => { Console.WriteLine($"Cluster description changed: {e.NewDescription}"); }); } };
IPv6
Specifies whether the host address is in IPv6 format. The default value is false
.
var settings = new MongoClientSettings { IPv6 = true, };
IsFrozen
A read-only option that indicates whether the settings have been frozen. You can't
change frozen settings. The default value is false
.
var settings = new MongoClientSettings(); if (!settings.IsFrozen) { settings.RetryReads = false; }
Tip
Freeze Settings
You can freeze the settings on a MongoClientSettings
object by calling its
Freeze()
method. This prevents any further changes to the settings.
Alternatively, you can call the FrozenCopy()
method to create a new MongoClientSettings
object with the current settings frozen.
LibraryInfo
The name and version of a custom library built on the .NET/C# Driver. The driver sends this information to the server.
var settings = new MongoClientSettings { LibraryInfo = new LibraryInfo("customLibraryName", "1.0.0") };
LoadBalanced
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
propertyYou're not using the
DirectConnection
property
The default value is false
.
var settings = new MongoClientSettings { LoadBalanced = true, };
LoggingSettings
The settings used for logging. The default value is null
.
var settings = new MongoClientSettings { LoggingSettings = new LoggingSettings( LoggerFactory.Create(l => l.SetMinimumLevel(LogLevel.Debug))) };
Scheme
Specifies whether to use the standard connection string format (MongoDB
)
or the DNS seed list format (MongoDBPlusSrv
). The available values for this
property are defined in the ConnectionStringScheme
enum. The default value is ConnectionStringScheme.MongoDB
.
See Connection Strings in the MongoDB Server
manual for more information about connection string formats.
If the DirectConnection
property is set to true
and you
try to use the DNS seed list format, the .NET/C# Driver will throw an
exception.
var settings = new MongoClientSettings { Scheme = ConnectionStringScheme.MongoDBPlusSrv, };
Server
The host and port number where MongoDB is running. The default value is
localhost:27017
.
var settings = new MongoClientSettings { Server = new MongoServerAddress("localhost", 27017) };
ServerMonitoringMode
Specifies the server monitoring protocol to use. The available values for this
property are defined in the ServerMonitoringMode
enum. The default value is Auto
.
When this option is set to Auto
the monitoring mode is determined
by the environment in which the driver is running. The driver
uses polling mode in function-as-a-service (FaaS) environments,
such as AWS Lambda, and the streaming mode in other environments.
var settings = new MongoClientSettings { ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream };
Servers
The cluster members where MongoDB is running. The default value is
localhost:27017
.
var settings = new MongoClientSettings { Servers = new List<MongoServerAddress>() { new ("localhost", 27017), new ("localhost", 27018) } };
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. 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.
var settings = new MongoClientSettings { SrvMaxHosts = 5 };
SrvServiceName
The SRV service name. The driver uses the service name to create the SRV URI, which mathces the following format:
_{srvServiceName}._tcp.{hostname}.{domainname}
The default value is "mongodb"
.
var settings = new MongoClientSettings { SrvServiceName = "yourServiceName" };
TranslationOptions
Specifies options, such as the MongoDB Server version, for translating LINQ
queries to the Query API. The default value is null
.
var settings = new MongoClientSettings { TranslationOptions = new ExpressionTranslationOptions() { CompatibilityLevel = ServerVersion.Server80, EnableClientSideProjections = true } };
ApplicationName
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
the connection is established. The value is also recorded in the slow query logs
and profile collections. The default value is null
.
var builder = new MongoUrlBuilder { ApplicationName = "yourAppName", };
DatabaseName
The name of the database that the client connects to.
var builder = new MongoUrlBuilder { DatabaseName = "test_database" };
IPv6
Specifies whether the host address is in IPv6 format. The default value is false
.
var builder = new MongoUrlBuilder { IPv6 = true, };
LoadBalanced
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
propertyYou're not using the
DirectConnection
property
The default value is false
.
var builder = new MongoUrlBuilder { LoadBalanced = true, };
Scheme
Specifies whether to use the standard connection string format (MongoDB
)
or the DNS seed list format (MongoDBPlusSrv
). The available values for this
property are defined in the ConnectionStringScheme
enum. The default value is ConnectionStringScheme.MongoDB
.
See Connection Strings in the MongoDB Server
manual for more information about connection string formats.
If the DirectConnection
property is set to true
and you
try to use the DNS seed list format, the .NET/C# Driver will throw an
exception.
var builder = new MongoUrlBuilder { Scheme = ConnectionStringScheme.MongoDBPlusSrv, };
Server
The host and port number where MongoDB is running. The default value is
localhost:27017
.
var builder = new MongoUrlBuilder { Server = new MongoServerAddress("localhost", 27017) };
ServerMonitoringMode
Specifies the server monitoring protocol to use. The available values for this
property are defined in the ServerMonitoringMode
enum. The default value is Auto
.
When this option is set to Auto
the monitoring mode is determined
by the environment in which the driver is running. The driver
uses polling mode in function-as-a-service (FaaS) environments,
such as AWS Lambda, and the streaming mode in other environments.
var builder = new MongoUrlBuilder { ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream };
Servers
The cluster members where MongoDB is running. The default value is
localhost:27017
.
var builder = new MongoUrlBuilder { Servers = new List<MongoServerAddress>() { new ("localhost", 27017), new ("localhost", 27018) } };
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. 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.
var builder = new MongoUrlBuilder { SrvMaxHosts = 5 };
SrvServiceName
The SRV service name. The driver uses the service name to create the SRV URI, which mathces the following format:
_{srvServiceName}._tcp.{hostname}.{domainname}
The default value is "mongodb"
.
var builder = new MongoUrlBuilder { SrvServiceName = "yourServiceName" };
Additional Information
For more information about the types used on this page, see the following API documentation: