Opções de conexão
Esta seção descreve as opções de conexão e autenticação MongoDB disponíveis no Driver .NET/C#. Você pode configurar sua conexão usando o URI da conexão ou um objeto MongoClientSettings
.
Como utilizar o URI de conexão
Se você passar um URI de conexão para o construtor MongoClient
, poderá incluir opções de conexão na cadeia de caracteres como pares <name>=<value>
. No exemplo a seguir, o URI de conexão contém a opção connectTimeoutMS
com um valor de 60000
e a opção tls
com um valor de true
:
using MongoDB.Driver; // Sets the connection URI const string connectionUri = "mongodb+srv://sample.host:27017/?connectTimeoutMS=60000&tls=true"; // Creates a new client and connects to the server var client = new MongoClient(connectionUri);
Usando MongoClientSettings
Você pode usar um objeto MongoClientSettings
para definir as configurações de conexão no código em vez de em um URI de conexão. Configurar a conexão dessa maneira facilita a alteração das configurações em tempo de execução, ajuda a detectar erros durante a compilação e oferece mais opções de configuração do que o URI de conexão.
Para usar um objeto MongoClientSettings
, crie uma instância da classe, defina suas propriedades e passe-a como um argumento para o construtor MongoClient
:
//const string connectionUri = "mongodb+srv://sample.host:27017/?connectTimeoutMS=60000&tls=true"; // Creates a MongoClientSettings object var settings = new MongoClientSettings() { Scheme = ConnectionStringScheme.MongoDBPlusSrv, Server = new MongoServerAddress("sample.host", 27017), ConnectTimeout = new TimeSpan(0, 0, 60), UseTls = true }; // Creates a new client and connects to the server var client = new MongoClient(settings);
Opções de conexão
A tabela a seguir lista cada opção de conexão disponível na classe MongoClientSettings
e, se possível, como alcançar o mesmo resultado na string de conexão. Se uma propriedade MongoClientSettings
for associada a mais de uma opção na cadeia de conexão, o Exemplo de URI de Conexão mostrará todas as opções correspondentes.
Observação
Se você estiver utilizando um parâmetro de query para uma duração de tempo, o valor deverá ser em milissegundos. Por exemplo, para especificar 60 segundos, utilize o valor 60000
. Se você estiver usando um objeto MongoClientSettings
por um período de tempo, use o valor TimeSpan
apropriado.
Propriedade MongoClientSettings | Descrição | |||
---|---|---|---|---|
AllowInsecureTIs | Specifies whether to relax TLS constraints as much as possible. This can include allowing invalid certificates or hostname mismatches. If this property is set to true and SslSettings.CheckCertificateRevocation is set to false , the .NET/C# Driver will throw an exception.Data Type: boolean Default: false Connection URI Example: tlsInsecure=true | |||
Nome do aplicativo | 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. Data Type: string Default: null Connection URI Example: appName=yourApp | |||
AutoEncryptionOptions | Settings for automatic client-side encryption. Data Type: AutoEncryptionOptions Default: null Connection URI Example: N/A | |||
ClusterConfigurator | Low-level configuration options for sockets, TLS, cluster, and others. Data Type: Action<ClusterBuilder> Default: null Connection URI Example: N/A | |||
Compressores | 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. Data Type: CompressorConfiguration Default: null Connection URI Example: compressors=snappy,zstd | |||
ConnectTimeout | The length of time the driver tries to establish a single TCP socket connection to the server before timing out. DataType: TimeSpan Default: 30 seconds Connection URI Example: connectTimeoutMS=0 | |||
Credenciais | Settings for how the driver authenticates to the server. This includes authentication credentials, mechanism, source, and other settings. If you don't specify an authentication mechanism, the driver uses either SCRAM-SHA-1 or SCRAM-SHA-256 , depending on the server version. Seeauthentication mechanisms for available authentication mechanisms. Data Type: MongoCredential Default: null Connection URI Example:
| |||
Conexão direta | Specifies whether to force dispatch all operations to the host. If you specify this option, the driver doesn't accept the You must use the standard connection URI format instead. This property must be set to false if you specify more than onehost name. Data Type: boolean Default: false Connection URI Example: directConnection=true | |||
HeartbeatInterval | The interval between regular server-monitoring checks. Must be greater than or equal to 500 milliseconds. Data Type: TimeSpan Default: 10 seconds Connection URI Example: heartbeatFrequencyMS=5000 | |||
HeartbeatTimeout | The length of time a monitoring socket can be idle before timing out. Data Type: TimeSpan Default: Same value as ConnectTimeout Connection URI Example: heartbeatTimeoutMS=5000 | |||
IPv6 | Specifies whether the host address is in IPv6 format. Data Type: boolean Default: false Connection URI Example: ipv6=true | |||
IsFrozen | Indicates whether the settings have been frozen. Frozen settings can't be changed. This option is read-only. Data Type: boolean Default: false Connection URI Example: N/A | |||
LinqProvider | ||||
loadBalanced | Specifies whether the driver is connecting to a load balancer. You can set this property to true only if:
Data Type: boolean Default: false Connection URI Example: loadBalanced=true | |||
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. Data Type: TimeSpan Default: 15 milliseconds Connection URI Example: localThresholdMS=0 | |||
LoggingSettings | ||||
maxConnecting | The greatest number of connections a driver's connection pool may be establishing concurrently. Data Type: integer Default: 2 Connection URI Example: maxConnecting=3 | |||
MaxConnectionIdleTime | The length of time a connection can be idle before the driver closes it. Data Type: TimeSpan Default: 10 minutes Connection URI Example: maxIdleTimeMS=300000 | |||
MaxConnectionLifeTime | The length of time a connection can be pooled before expiring. Data Type: TimeSpan Default: 30 minutes Connection URI Example: maxLifetimeMS=50000 | |||
MaxConnectionPoolSize | 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: 100 Connection URI Example: maxPoolSize=150 | |||
MinConnectionPoolSize | The number of connections the driver should create and keep in the connection pool even when no operations are occurring. This count includes connections in use. Data Type: integer Default: 0 Connection URI Example: minPoolSize=1 | |||
Leia a preocupação | The client's default read concern. See read concern for more information. Data Type: ReadConcern Default: ReadConcern.Default Connection URI Example: readConcernLevel=local | |||
Leia a codificação | The UTF-8 encoding to use for string deserialization. Strict encoding will throw an exception when an invalid UTF-8 byte sequence is encountered. Data Type: UTF8Encoding Default: Strict encoding Connection URI Example: N/A | |||
readPreference | The client's default read-preference settings. MaxStaleness represents thelongest replication lag, in wall-clock time, that a secondary can experience and still be eligible for server selection. Specifying -1 means no maximum.See read preference for more information. Data Type: ReadPreference Default: ReadPreference.Primary Connection URI Example:
You can include the readPreferenceTags parameter in the connection URI more
than once. If you do, the client treats each instance as a separate tag set.
The order of the tags in the URI determines the order for read preference. You can
use this parameter only if the read-preference mode is not primary . | |||
ReplicaSetName | The name of the replica set to connect to. Data Type: string Default: null Connection URI Example: replicaSet=yourReplicaSet | |||
RetryReads | Enables retryable reads. Data Type: boolean Default: true Connection URI Example: retryReads=false | |||
RetryWrites | Enables retryable writes. Data Type: boolean Default: true Connection URI Example: retryWrites=false | |||
Esquema | Specifies whether to use the standard connection string format ( MongoDB )or the DNS seed list format ( MongoDBPlusSrv ).See the MongoDB Manual for more information about connection string formats. If the DirectConnection property is set to true and youtry to use the DNS seed list format, the .NET/C# Driver will throw an exception. Data Type: ConnectionStringScheme Default: ConnectionStringScheme.MongoDB Connection URI Example: mongodb+srv:// | |||
Servidor | The host and port number where MongoDB is running. Data Type: MongoServerAddress Default: localhost:27017 Connection URI Example: mongodb://sample.host:27017 | |||
API do servidor | Allows opting into Stable API versioning. See the MongoDB Manual for more information about Stable API versioning. Data Type: ServerApi Default: null Connection URI Example: N/A | |||
serverMonitoringMode | Specifies the server monitoring protocol to use. When this option is set to Auto , the monitoring mode is determinedby 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. Data Type: ServerMonitoringMode Default: Auto Connection URI Example: serverMonitoringMode=poll | |||
Servidores | The cluster members where MongoDB is running. Data Type: IEnumerable<MongoServerAddress> Default: localhost:27017 Connection URI Example: mongodb://sample.host1:27017,sample.host2:27017 | |||
ServerSelectionTimeout | The length of time the driver tries to select a server before timing out. Data Type: TimeSpan Default: 30 seconds Connection URI Example: serverSelectionTimeoutMS=15000 | |||
Tempo limite do soquete | The length of time the driver tries to send or receive on a socket before timing out. Data Type: TimeSpan Default: OS default Connection URI Example: socketTimeoutMS=0 | |||
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 connectingto a replica set. Data Type: integer Default: 0 Connection URI Example: srvMaxHosts=3 | |||
Configurações SSL | TLS/SSL options, including client certificates, revocation handling, and enabled and disabled TLS/SSL protocols. If SslSettings.CheckCertificateRevocation is set to false andAllowInsecureTls is set to true , the .NET/C# Driver will throwan exception. Data Type: SslSettings Default: null Connection URI Example: tlsDisableCertificateRevocationCheck=false | |||
Use 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 .Data Type: boolean Default: false Connection URI Example: tls=true | |||
Tempo limite da fila de espera | The length of time the driver tries to check out a connection from a server's connection pool before timing out. Data Type: TimeSpan Default: 2 minutes Connection URI Example: waitQueueTimeoutMS=0 | |||
Escreva preocupação | The default write-concern settings, including write timeout and journaling, for the client. See write concern for more information. Data Type: WriteConcern Default: WriteConcern.Acknowledged Connection URI Example: w=majority&wTimeoutMS=0&journal=true | |||
WriteEncoding | Specifies whether UTF-8 string serialization is strict or lenient. With strict encoding, the driver will throw an exception when it encounters an invalid UTF-8 byte sequence. Data Type: UTF8Encoding Default: Strict encoding Connection URI Example: N/A |