对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。

指定连接选项

本页介绍了.NET/ C#驱动程序中可用的连接选项,并解释了如何应用MongoDB连接。

以下部分介绍了指定连接选项的方法。

如果将连接 URI 传递给 MongoClient 构造函数,则可以将连接选项作为 <name>=<value> 对包含在字符串中。在以下示例中,连接 URI 包含值为 60000 的 connectTimeoutMS 选项和值为 true 的 tls 选项:

const string uri = "mongodb+srv:/localhost:27017/?connectTimeoutMS=60000&tls=true";

要学习;了解有关可在连接 URI 中指定的选项的更多信息,请参阅MongoDB Server手册中的连接字符串选项。

您可以使用 MongoClientSettings 对象在代码中(而不是在连接 URI 中)配置连接设置。以这种方式配置连接可以更轻松地在运行时更改设置,帮助您在编译期间捕获错误,并提供比连接 URI 更多的配置选项。

要在 MongoClientSettings对象中设立连接选项,请执行以下步骤:

  1. 创建 MongoClientSettings 类的实例

  2. 在实例上设置属性以配置连接

  3. 将实例传递给 MongoClient 构造函数

以下代码示例展示了如何执行上述步骤:

var settings = new MongoClientSettings(){ Scheme = ConnectionStringScheme.MongoDBPlusSrv, Server = new MongoServerAddress("localhost", 27017), ConnectTimeout = TimeSpan.FromMilliseconds(60000), UseTls = true}; var client = new MongoClient(settings);

您还可以通过调用 MongoClientSettings.FromConnectionString() 方法并传递连接字符串字符串,从连接字符串创建 MongoClientSettings对象,如以下示例所示。 如果您已经有了连接字符串但想以编程方式修改某些设置,或者必须指定连接字符串中未提供的设置,则此操作非常有用。

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);

或者,您可以通过调用 MongoClientSettings.FromUrl() 方法并传递 MongoUrl对象,从 MongoUrl对象创建 MongoClientSettings对象,如以下示例所示。如果您已经有了 MongoUrl对象,但想要指定 MongoUrl 类中未提供的设置,则此操作非常有用。

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);

您可以使用 MongoUrlBuilder对象在 MongoUrl对象上创建和配置连接设置。MongoUrl 是连接 URI 的强类型表示,在直接从其他源读取连接 URI 时非常有用。使用 MongoUrl对象与使用 MongoClientSettings对象具有许多相同的优点,尽管这两个类包含不同的属性和方法。

要使用 MongoUrlBuilder对象,请创建该类的实例并设立必要的配置属性。要从 MongoUrlBuilder 创建 MongoUrl对象,请调用 MongoUrlBuilder.ToMongoUrl() 方法。您可以将 MongoUrl对象传递给 MongoClient 构造函数。以下代码示例显示了此进程:

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);

以下部分介绍.NET/ C#驱动程序中可用的连接选项,以及如何使用 MongoClientSettings 或 MongoUrlBuilder对象指定这些选项。

指定是否强制将所有操作分派到托管。如果指定此选项,驱动程序将不接受 DNS 种子列表连接格式。 您必须改用标准连接 URI 格式。默认值为 false。

如果指定多个托管名,则必须将此属性设立为 false。

var settings = new MongoClientSettings{ DirectConnection = true,};

要连接的副本集的名称。 默认值为 null。

var settings = new MongoClientSettings{ ReplicaSetName = "yourReplicaSet",};

指定是否尽可能放宽 TLS 约束。这可能包括允许无效证书或主机名不匹配。默认值为 false。

如果将此属性设立为 true 并将 SslSettings.CheckCertificateRevocation设立为 false,则.NET/ C#驱动程序将引发异常。

以下代码示例展示了如何将此选项设立为 true:

var settings = new MongoClientSettings{ AllowInsecureTls = true,};

TLS/SSL 选项,包括客户端证书、撤销处理以及启用和禁用的 TLS/SSL 协议。默认值为 null。

如果将 SslSettings.CheckCertificateRevocation设立为 false 并将 AllowInsecureTls设立为 true,则.NET/ C#驱动程序会引发异常。

var settings = new MongoClientSettings();settings.SslSettings = new SslSettings(){ CheckCertificateRevocation = false, ClientCertificateSelectionCallback = new LocalCertificateSelectionCallback() { ... }, ClientCertificates = new List<X509Certificate>() { ... }, EnabledSslProtocols = SslProtocols.Tls13, ServerCertificateValidationCallback = new RemoteCertificateValidationCallback() { ... }};

指定是否需要 TLS 来连接到服务器。如果使用 "mongodb+srv" 模式或指定其他 TLS 选项,则此选项默认为 true。否则,默认为 false。

var settings = new MongoClientSettings{ UseTls = true,};

驱动程序在超时之前尝试与服务器建立单个 TCP 套接字连接的时间长度。默认值为 30 秒。

var settings = new MongoClientSettings{ ConnectTimeout = TimeSpan.FromSeconds(60),};

驱动程序在超时之前尝试在套接字上发送或接收的时间长度。默认值由操作系统设立。

var settings = new MongoClientSettings{ ConnectTimeout = TimeSpan.FromSeconds(60),};

按顺序排列的首选压缩类型,适用于发送到服务器或从服务器接收的传输协议消息。驱动程序使用服务器支持的第一种压缩类型。默认值为 null。

var settings = new MongoClientSettings{ Compressors = new List<CompressorConfiguration>() { new(CompressorType.Zlib), new(CompressorType.Snappy) }};

驱动程序的连接池可以同时建立的最大连接数。默认值为 2。

var settings = new MongoClientSettings{ MaxConnecting = 3,};

在驱动程序关闭连接之前,该连接可以处于空闲状态的时间长度。默认值为 10 分钟。

var settings = new MongoClientSettings{ MaxConnectionIdleTime = TimeSpan.FromMinutes(8),};

连接在过期之前可以进入池化的时间长度。默认值为 30 分钟。

var settings = new MongoClientSettings{ MaxConnectionLifeTime = TimeSpan.FromMinutes(40),};

驱动程序可以在其连接池创建的最大客户端或连接数。此计数包括正在使用的连接。默认值为 100。

var settings = new MongoClientSettings{ MaxConnectionPoolSize = 150,};

即使没有进行操作时,驱动程序也会在连接池创建并保留的连接数。此计数包括正在使用的连接。默认值为 0。

var settings = new MongoClientSettings{ MinConnectionPoolSize = 3,};

驱动程序在超时之前尝试从服务器的连接池检出连接的时间长度。默认值为两分钟。

var settings = new MongoClientSettings{ WaitQueueTimeout = TimeSpan.FromSeconds(30),};

客户端的默认写关注设置,包括写入超时和日志。默认值为 WriteConcern.Acknowledged。有关更多信息,请参阅MongoDB Server手册中的写关注。

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);

客户端的读关注(read concern)。默认值为 ReadConcern.Default。有关更多信息,请参阅MongoDB Server手册中的读关注。

var settings = new MongoClientSettings{ ReadConcern = MongoDB.Driver.ReadConcern.Local,};

客户端的默认读取偏好设置。MaxStaleness 表示从节点(secondary node from replica set)可能出现但仍有资格进行服务器选择的最长复制延迟(以挂钟时间为单位)。默认值为 ReadPreference.Primary。指定 -1 意味着没有最大值。有关更多信息,请参阅MongoDB Server手册中的读取偏好。

var settings = new MongoClientSettings{ ReadPreference = MongoDB.Driver.ReadPreference.PrimaryPreferred,};

关于驱动程序如何向服务器进行身份验证的设置。这包括身份验证凭证、机制、来源和其他设置。默认值为 null。

如果不指定身份验证机制,驱动程序将使用 SCRAM-SHA-1 或 SCRAM-SHA-256,具体取决于服务器版本。有关可用的身份验证机制,请参阅身份验证机制。

var settings = new MongoClientSettings{ Credential = MongoCredential.CreatePlainCredential( databaseName: "admin", username: "user", password: "password" )};

定期服务器监控检查之间的时间间隔。必须大于或等于 500 毫秒。默认值为 10000 毫秒(10 秒)。

var settings = new MongoClientSettings{ HeartbeatInterval = TimeSpan.FromSeconds(5)};

监控套接字在超时之前可以处于空闲状态的时间长度。默认值为 ConnectTimeout属性的值。

var settings = new MongoClientSettings{ HeartbeatTimeout = TimeSpan.FromSeconds(5)};

服务器资格的延迟窗口。如果服务器的往返时间超过最快服务器的往返时间加上此值,则该服务器没有资格被选中。默认值为 15 毫秒。

var settings = new MongoClientSettings{ LocalThreshold = TimeSpan.FromSeconds(15)};

服务器资格的延迟窗口。如果服务器的往返时间超过最快服务器的往返时间加上此值,则该服务器没有资格被选中。默认值为 15 毫秒。

var settings = new MongoClientSettings{ ServerSelectionTimeout = TimeSpan.FromSeconds(30)};

用于 string 反序列化的 UTF-8 编码。默认值为严格编码,即驱动程序在遇到无效的 UTF-8 字节序列时会引发异常

var settings = new MongoClientSettings{ ReadEncoding = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)};

用于 string 序列化的 UTF-8 编码。默认值为严格编码,即驱动程序在遇到无效的 UTF-8 字节序列时会引发异常

var settings = new MongoClientSettings{ WriteEncoding = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)};

注意

仅限 MongoClientSettings

ReadEncoding 和 WriteEncoding 属性仅在 MongoClientSettings 类中可用。

允许选择 Stable API版本控制。默认值为 null。有关 Stable API版本控制的更多信息,请参阅MongoDB Server手册中的 Stable API 。

var settings = new MongoClientSettings{ ServerApi = new ServerApi( ServerApiVersion.V1, strict: true, deprecationErrors: true),};

注意

仅限 MongoClientSettings

ServerApi属性仅在 MongoClientSettings 类中可用。

允许重试读取。 默认值为 true。

var settings = new MongoClientSettings{ RetryReads = false,};

启用可重试写入。 默认值为 true。

var settings = new MongoClientSettings{ RetryWrites = false,};

作为连接握手的一部分,驱动程序在客户端元数据中传递给服务器的应用名称。建立连接后,服务器会将此值打印到MongoDB日志。该值还会记录在慢速查询日志和配置文件集合中。默认值为 null。

var settings = new MongoClientSettings{ ApplicationName = "yourAppName",};

客户端自动加密的设置。默认值为 null。要学习;了解有关客户端加密的更多信息,请参阅正在使用的加密。

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>" } } } } ),};

套接字、TLS、集群等项目的低级配置选项。 默认值为 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 格式。默认值为 false。

var settings = new MongoClientSettings{ IPv6 = true,};

指示设置是否已冻结的只读选项。您无法更改冻结设置。默认值为 false。

var settings = new MongoClientSettings();if (!settings.IsFrozen){ settings.RetryReads = false;}

提示

冻结设置

您可以通过调用 MongoClientSettings对象的Freeze() 方法来冻结该对象的设置。这样可以防止对设置进行进一步更改。

或者,您可以调用 FrozenCopy() 方法来创建新的MongoClientSettings 对象,并冻结当前设置。

基于.NET/C#驱动程序构建的自定义库的名称和版本。驱动程序将此信息发送到服务器。

var settings = new MongoClientSettings{ LibraryInfo = new LibraryInfo("customLibraryName", "1.0.0")};

指定驱动程序是否正在连接到负载均衡器。仅当满足以下所有条件时,才能将此属性设立为 true:

  • 您仅指定一个托管名

  • 您没有连接到副本集

  • 您没有使用 SrvMaxHosts属性

  • 您没有使用 DirectConnection属性

默认值为 false。

var settings = new MongoClientSettings{ LoadBalanced = true,};

用于日志记录的设置。 默认值为 null。

var settings = new MongoClientSettings{ LoggingSettings = new LoggingSettings( LoggerFactory.Create(l => l.SetMinimumLevel(LogLevel.Debug)))};

指定是使用标准连接字符串格式 (MongoDB) 还是 DNS种子列表格式 (MongoDBPlusSrv)。 此属性的可用值在ConnectionStringScheme枚举中定义。默认值为 ConnectionStringScheme.MongoDB。有关连接字符串格式的更多信息,请参阅MongoDB Server手册中的连接字符串。

如果将 DirectConnection属性设立为 true,并且您尝试使用 DNS种子列表格式,则.NET/ C#驱动程序将引发异常。

var settings = new MongoClientSettings{ Scheme = ConnectionStringScheme.MongoDBPlusSrv,};

运行 MongoDB 的主机和端口号。 默认值为 localhost:27017。

var settings = new MongoClientSettings{ Server = new MongoServerAddress("localhost", 27017)};

指定要使用的服务器监控协议。此属性的可用值在ServerMonitoringMode枚举中定义。默认值为 Auto。

当此选项设立为 Auto 时,监控模式由驱动程序运行的环境决定。驱动程序在函数即服务 (FaaS) 环境(例如 AWS Lambda )中使用轮询模式,在其他环境中使用流模式。

var settings = new MongoClientSettings{ ServerMonitoringMode = MongoDB.Driver.Core.Servers.ServerMonitoringMode.Stream};

运行 MongoDB 的集群成员。 默认值为 localhost:27017。

var settings = new MongoClientSettings{ Servers = new List<MongoServerAddress>() { new ("localhost", 27017), new ("localhost", 27018) }};

The hostname suffix that the driver validates SRV-discovered host names against. Specify this option to override the suffix the driver infers from the connection string's hostname. The default value is null.

You can use this property only if the connection-string scheme is set to ConnectionStringScheme.MongoDBPlusSrv. You can't use it when connecting to a replica set.

The driver rejects an empty value or a single-label value that isn't a private or special-use namespace, such as local or internal.

var settings = new MongoClientSettings{ SrvAllowedHostsSuffix = "mongodb.net"};

最初填充种子列表或在 SRV 轮询期间向拓扑结构添加新主机时,要随机选择的 SRV 结果的最大数量。默认值为 0。

仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。

var settings = new MongoClientSettings{ SrvMaxHosts = 5};

SRV 资源记录的服务名称,驱动程序会检索该服务名称以构建您的种子列表。驱动程序使用该服务名称创建 SRV URI,其格式如下:

_{srvServiceName}._tcp.{hostname}.{domainname}

此属性会覆盖发现和轮询中 SRV 查找的默认服务名称。默认值为 "mongodb"。

仅当连接字符串模式设立为 ConnectionStringScheme.MongoDBPlusSrv 时才能使用此属性。连接到副本集时无法使用它。

var settings = new MongoClientSettings{ SrvServiceName = "yourServiceName"};

指定用于将 LINQ 查询转换为 查询API 的选项,例如MongoDB Server版本。默认值为 null。

var settings = new MongoClientSettings{ TranslationOptions = new ExpressionTranslationOptions() { CompatibilityLevel = ServerVersion.Server80, EnableClientSideProjections = true }};

有关此页面上使用的类型的更多信息,请参阅以下API文档: