MongoDB Server ParametersMongoDB服务器参数
On this page本页内容
Synopsis提要Parameters参数Authentication Parameters身份验证参数General Parameters一般参数Logging Parameters日志记录参数Diagnostic Parameters诊断参数Replication and Consistency复制和一致性Sharding Parameters分片参数Health Manager Parameters运行状况管理器参数Storage Parameters存储参数WiredTiger ParametersWiredTiger参数Auditing Parameters审核参数Transaction Parameters事务处理参数Slot-Based Execution Parameters基于插槽的执行参数
Synopsis提要
MongoDB provides a number of configuration options that you can set using:MongoDB提供了许多配置选项,您可以使用这些选项进行设置:
thesetParametercommand:setParameter命令:db.adminCommand( { setParameter: 1, <parameter>: <value> } )
thesetParameterconfiguration setting:setParameter配置设置:setParameter:
<parameter1>: <value1>
...the--setParametercommand-line option formongodandmongos:mongod和mongos的--setParameter命令行选项:mongod --setParameter <parameter>=<value>
mongos --setParameter <parameter>=<value>
For additional configuration options, see Configuration File Options, 有关其他配置选项,请参阅配置文件选项、mongod and mongos.mongod和mongos。
Parameters参数
Authentication Parameters身份验证参数
authenticationMechanisms-
Available for both可用于mongodandmongos.mongod和mongos。Specifies the list of authentication mechanisms the server accepts.指定服务器接受的身份验证机制的列表。Set this to one or more of the following values.将其设置为以下一个或多个值。If you specify multiple values, use a comma-separated list and no spaces. For descriptions of the authentication mechanisms, see Authentication.如果指定多个值,请使用逗号分隔的列表,并且不要使用空格。有关身份验证机制的描述,请参阅身份验证。Value值Description描述SCRAM-SHA-1 RFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.使用SHA-1散列函数的标准Salted质询-响应认证机制。SCRAM-SHA-256 RFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.使用SHA-256散列函数的标准Salted质询-响应认证机制。MONGODB-X509 MongoDB TLS/SSL certificate authentication.MongoDB TLS/SSL证书身份验证。GSSAPI (Kerberos) External authentication using Kerberos.使用Kerberos的外部身份验证。This mechanism is available only in MongoDB Enterprise此机制仅在MongoDB Enterprise.
中可用。
PLAIN (LDAP SASL) External authentication using LDAP.使用LDAP的外部身份验证。You can also use您还可以使用PLAINfor authenticating in-database users.PLAIN对数据库中的用户进行身份验证。PLAINtransmits passwords in plain text.PLAIN以纯文本形式传输密码。This mechanism is available only in MongoDB Enterprise此机制仅在MongoDB Enterprise.
中可用。
MONGODB-OIDC OpenID Connect is an authentication layer built on top of OAuth2.OpenIDConnect是一个建立在OAuth2之上的身份验证层。This mechanism is available only in MongoDB Enterprise此机制仅在MongoDB Enterprise.
中可用。
You can only set您只能在启动期间设置authenticationMechanismsduring start-up.authenticationMechanisms。For example, to specify both例如,要指定PLAINandSCRAM-SHA-256as the authentication mechanisms, use the following command:PLAIN和SCRAM-SHA-256作为身份验证机制,请使用以下命令:mongod --setParameter authenticationMechanisms=PLAIN,SCRAM-SHA-256 --auth
awsSTSRetryCountChanged in version 7.0.7.0版更改。(Also starting in 6.0.7, 5.0.18, 4.4.22)In previous versions, AWS IAM authentication retried only when the server returned an HTTP 500 error.在以前的版本中,只有当服务器返回HTTP 500错误时,才会重试AWS IAM身份验证。Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 2For MongoDB deployments using AWS IAM credentials对于使用AWS IAM凭据or AWS IAM environment variables.
或AWS IAM环境变量
的MongoDB部署。
Maximim number of AWS IAM authentication retries after a connection failure.连接失败后AWS IAM身份验证重试的最大次数。The following example sets以下示例将awsSTSRetryCountto15retries:awsSTSRetryCount设置为15次重试:mongod --setParameter awsSTSRetryCount=15
Alternatively, the following examples uses the或者,以下示例在setParametercommand withinmongosh:mongosh中使用setParameter命令:db.adminCommand( { setParameter: 1, awsSTSRetryCount: 15 } )
clusterAuthMode-
Available for both可用于mongodandmongos.mongod和mongos。Set the将clusterAuthModeto eithersendX509orx509. Useful during rolling upgrade to use x509 for membership authentication to minimize downtime.clusterAuthMode设置为sendX509或x509。在滚动升级期间使用x509进行成员身份验证以最大限度地减少停机时间非常有用。For more information about TLS/SSL and MongoDB, see Configure有关TLS/SSL和MongoDB的更多信息,请参阅配置mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .mongod和mongos的TLS/SSL以及针对客户端的TLS/SSL配置。db.adminCommand( { setParameter: 1, clusterAuthMode: "sendX509" } )
enableLocalhostAuthBypass-
Available for both可用于mongodandmongos.mongod和mongos。Specify指定0orfalseto disable localhost authentication bypass. Enabled by default.0或false以禁用localhost身份验证旁路。默认情况下已启用。enableLocalhostAuthBypassis not available usingsetParameterdatabase command.enableLocalhostAuthBypass无法使用setParameter数据库命令。Use the使用配置文件中的setParameteroption in the configuration file or the--setParameteroption on the command line.setParameter选项或命令行中的--setParameter选项。See Localhost Exception for more information.有关详细信息,请参阅Localhost异常。
KeysRotationIntervalSec-
Default默认值: 7776000 seconds (90 days)Specifies the number of seconds for which an HMAC signing key指定HMAC签名键is valid before rotating to the next one.
在旋转到下一个键之前有效的秒数。
This parameter is intended primarily to facilitate authentication testing.此参数主要用于促进身份验证测试。You can only set您只能在启动期间设置KeysRotationIntervalSecduring start-up, and cannot change this setting with thesetParameterdatabase command.KeysRotationIntervalSec,不能使用setParameter数据库命令更改此设置。
ldapForceMultiThreadModeNew in version 4.2.4.2版新增。Default默认值: falseEnables the performance of concurrent LDAP operations.启用并发LDAP操作的性能。NoteOnly if you are certain that your instance of只有当您确信您的libldap实例在这种模式下使用是安全的时,才启用此标志。libldapis safe to use in this mode, enable this flag.You may experience crashes of the MongoDB process if the如果您使用的libldapversion you are using is not thread safe.libldap版本不是线程安全的,那么您可能会遇到MongoDB进程崩溃的情况。You must use必须使用ldapForceMultiThreadModeto use LDAP connection pool. To enable LDAP connection pool, setldapForceMultiThreadModeandldapUseConnectionPooltotrue.ldapForceMultiThreadMode才能使用LDAP连接池。要启用LDAP连接池,请将ldapForceMultiThreadMode和ldapUseConnectionPool设置为true。TipIf you have any concerns regarding your MongoDB version, OS version or libldap version, please contact MongoDB Support.如果您对MongoDB版本、操作系统版本或libldap版本有任何疑问,请联系MongoDB支持。
ldapRetryCountNew in version 6.1.6.1版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 0For MongoDB deployments using LDAP Authorization.对于使用LDAP授权的MongoDB部署。Number of operation retries by the server LDAP manager after a network error.网络错误后服务器LDAP管理器重试操作的次数。For example, the following sets例如,以下将ldapRetryCountto3seconds:ldapRetryCount设置为3秒:mongod --ldapRetryCount=3
Or, if using the或者,如果在setParametercommand withinmongosh:mongosh中使用setParameter命令:db.adminCommand( { setParameter: 1, ldapRetryCount: 3 } )
ldapUserCacheInvalidationIntervalChanged in version 5.2.5.2版更改。Available for仅适用于mongodonly.mongod。NoteStarting in MongoDB 5.2, the update interval for cached user information retrieved from an LDAP server depends on从MongoDB 5.2开始,从LDAP服务器检索的缓存用户信息的更新间隔取决于ldapShouldRefreshUserCacheEntries:ldapShouldRefreshUserCacheEntries:If true, use如果为ldapUserCacheRefreshInterval.true,请使用ldapUserCacheRefreshInterval。If false, use如果为ldapUserCacheInvalidationInterval.false,请使用ldapUserCacheInvalidationInterval。
For use with MongoDB deployments using LDAP Authorization.用于使用LDAP授权的MongoDB部署。The interval (in seconds) that themongodinstance waits between external user cache flushes.mongod实例在外部用户缓存刷新之间等待的时间间隔(以秒为单位)。After MongoDB flushes the external user cache, MongoDB reacquires authorization data from the LDAP server the next time an LDAP-authorized user issues an operation.MongoDB刷新外部用户缓存后,下次LDAP授权用户发出操作时,MongoDB会从LDAP服务器重新获取授权数据。Increasing the value specified increases the amount of time MongoDB and the LDAP server can be out of sync, but reduces the load on the LDAP server.增加指定的值会增加MongoDB和LDAP服务器不同步的时间,但会减少LDAP服务器上的负载。Conversely, decreasing the value specified decreases the time MongoDB and the LDAP server can be out of sync while increasing the load on the LDAP server.相反,减少指定的值可以减少MongoDB和LDAP服务器不同步的时间,同时增加LDAP服务器上的负载。Defaults to 30 seconds.默认为30秒。
ldapUserCacheRefreshIntervalNew in version 5.2.5.2版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 30 secondsNoteStarting in MongoDB 5.2, the update interval for cached user information retrieved from an LDAP server depends on从MongoDB 5.2开始,从LDAP服务器检索的缓存用户信息的更新间隔取决于ldapShouldRefreshUserCacheEntries:ldapShouldRefreshUserCacheEntries:- If true, use
ldapUserCacheRefreshInterval. - If false, use
ldapUserCacheInvalidationInterval.
For MongoDB deployments using LDAP Authorization.对于使用LDAP授权的MongoDB部署。The interval in seconds thatmongodwaits before refreshing the cached user information from the LDAP server.mongod在从LDAP服务器刷新缓存的用户信息之前等待的时间间隔(秒)。The maximum interval is 86,400 seconds (24 hours).最大间隔为86400秒(24小时)。For example, the following sets例如,以下将ldapUserCacheRefreshIntervalto4000seconds:ldapUserCacheRefreshInterval设置为4000秒:mongod --setParameter ldapUserCacheRefreshInterval=4000
Or, if using the或者,如果在setParametercommand withinmongosh:mongosh中使用setParameter命令:db.adminCommand( { setParameter: 1, ldapUserCacheRefreshInterval: 4000 } )
- If true, use
ldapUserCacheStalenessIntervalNew in version 5.2.5.2版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 90 secondsFor MongoDB deployments using LDAP Authorization.对于使用LDAP授权的MongoDB部署。The interval in seconds thatmongodretains the cached LDAP user information after the last cache refresh.mongod在上次缓存刷新后保留缓存的LDAP用户信息的时间间隔(秒)。If more than如果超过ldapUserCacheStalenessIntervalseconds elapse without a successful refresh of the user information from the LDAP server, thenmongod:ldapUserCacheStalenessInterval秒,LDAP服务器上的用户信息没有成功刷新,则mongod:Invalidates the cached LDAP user information.使缓存的LDAP用户信息无效。Is unable to authenticate new sessions for LDAP users until在mongodconnects to the LDAP server and authorizes the LDAP user.mongod连接到LDAP服务器并授权LDAP用户之前,无法为LDAP用户验证新会话。Authorizes any existing sessions that use previously authenticated LDAP users if如果mongodis unable to connect to the LDAP server.mongod无法连接到LDAP服务器,则授权使用先前已验证LDAP用户的任何现有会话。When当mongodreconnects to the LDAP server,mongodensures the LDAP users are correctly authorized.mongod重新连接到LDAP服务器时,mongod会确保LDAP用户得到正确授权。
The maximum interval is 86,400 seconds (24 hours).最大间隔为86400秒(24小时)。For example, the following sets例如,以下将ldapUserCacheStalenessIntervalto4000seconds:ldapUserCacheStalenessInterval设置为4000秒:mongod --setParameter ldapUserCacheStalenessInterval=4000
Or, if using the或者,如果在setParametercommand withinmongosh:mongosh中使用setParameter命令:db.adminCommand( { setParameter: 1, ldapUserCacheStalenessInterval: 4000 } )
ldapUseConnectionPool-
Specifies whether MongoDB should use connection pooling when connecting to the LDAP server for authentication/authorization.指定MongoDB在连接到LDAP服务器进行身份验证/授权时是否应使用连接池。MongoDB uses the following default values:MongoDB使用以下默认值:true on Windows.在Windows上为true。true on Linux where MongoDB Enterprise binaries are linked against在Linux上为libldap_r.true,其中MongoDB Enterprise二进制文件链接到libldap_r。false on Linux where MongoDB Enterprise binaries are linked against在Linux上为libldap.false,其中MongoDB Enterprise二进制文件是根据libldap链接的。
You can only set您只能在启动期间设置ldapUseConnectionPoolduring start-up, and cannot change this setting with thesetParameterdatabase command.ldapUseConnectionPool,不能使用setParameter数据库命令更改此设置。
ldapConnectionPoolUseLatencyForHostPriorityNew in version 4.2.1.4.2.1版新增。Default默认值: trueA boolean that determines whether the LDAP connection pool (see一个布尔值,用于确定LDAP连接池(请参阅ldapUseConnectionPool) should use latency of the LDAP servers to determine the connection order (from lowest latency to highest).ldapUseConnectionPool)是否应使用LDAP服务器的延迟来确定连接顺序(从最低延迟到最高延迟)。You can only set您只能在启动期间设置ldapConnectionPoolUseLatencyForHostPriorityduring start-up, and cannot change this setting during run time with thesetParameterdatabase command.ldapConnectionPoolUseLatencyForHostPriority,而不能在运行时使用setParameter数据库命令更改此设置。
ldapConnectionPoolMinimumConnectionsPerHostNew in version 4.2.1.4.2.1版新增。Default默认值: 1The minimum number of connections to keep open to each LDAP server.对每个LDAP服务器保持打开状态的最小连接数。You can only set您只能在启动期间设置ldapConnectionPoolMinimumConnectionsPerHostduring start-up, and cannot change this setting during run time with thesetParameterdatabase command.ldapConnectionPoolMinimumConnectionsPerHost,而不能在运行时使用setParameter数据库命令更改此设置。
ldapConnectionPoolMaximumConnectionsPerHostNew in version 4.2.1.4.2.1版新增。Changed starting in MongoDB versions 4.4.15, 5.0.9, and 6.0.0 Changed default value to
2147483647. In previous versions, the default is unset.Default默认值: 2147483647The maximum number of connections to keep open to each LDAP server.要保持对每个LDAP服务器打开的最大连接数。You can only set您只能在启动期间设置ldapConnectionPoolMaximumConnectionsPerHostduring start-up, and cannot change this setting during run time with thesetParameterdatabase command.ldapConnectionPoolMaximumConnectionsPerHost,而不能在运行时使用setParameter数据库命令更改此设置。
ldapConnectionPoolMaximumConnectionsInProgressPerHostNew in version 4.2.1.4.2.1版新增。Changed starting in MongoDB versions 4.4.15, 5.0.9, and 6.0.0 Changed default value to
2. In previous versions, the default is unset.Default默认值: 2The maximum number of in-progress connect operations to each LDAP server.每个LDAP服务器正在进行的连接操作的最大数目。You can only set您只能在启动期间设置ldapConnectionPoolMaximumConnectionsInProgressPerHostduring start-up, and cannot change this setting with thesetParameterdatabase command.ldapConnectionPoolMaximumConnectionsInProgressPerHost,不能使用setParameter数据库命令更改此设置。
ldapConnectionPoolHostRefreshIntervalMillisNew in version 4.2.1.4.2.1版新增。Default默认值: 60000The number of milliseconds in-between health checks of the pooled LDAP connections.池LDAP连接的运行状况检查之间的毫秒数。You can only set您只能在启动期间设置ldapConnectionPoolHostRefreshIntervalMillisduring start-up, and cannot change this setting with thesetParameterdatabase command.ldapConnectionPoolHostRefreshIntervalMillis,不能使用setParameter数据库命令更改此设置。
ldapConnectionPoolIdleHostTimeoutSecsNew in version 4.2.1.4.2.1版新增。Default默认值: 300The maximum number of seconds that the pooled connections to an LDAP server can remain idle before being closed.到LDAP服务器的池连接在关闭之前可以保持空闲的最大秒数。You can only set您只能在启动期间设置ldapConnectionPoolIdleHostTimeoutSecsduring start-up, and cannot change this setting with thesetParameterdatabase command.ldapConnectionPoolIdleHostTimeoutSecs,不能使用setParameter数据库命令更改此设置。
ldapShouldRefreshUserCacheEntriesNew in version 5.2.5.2版新增。Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: trueFor MongoDB deployments using LDAP Authorization.对于使用LDAP授权的MongoDB部署。Starting in MongoDB 5.2, the update interval for cached user information retrieved from an LDAP server depends on从MongoDB 5.2开始,从LDAP服务器检索的缓存用户信息的更新间隔取决于ldapShouldRefreshUserCacheEntries:ldapShouldRefreshUserCacheEntries:- If true, use
ldapUserCacheRefreshInterval. - If false, use
ldapUserCacheInvalidationInterval.
You can only set
ldapShouldRefreshUserCacheEntriesduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following disablesldapShouldRefreshUserCacheEntries:mongod --setParameter ldapShouldRefreshUserCacheEntries=false- If true, use
maxValidateMemoryUsageMBNew in version 5.0:5.0版新增:(Also available starting in 4.4.7.)Default默认值: 200The maximum memory usage limit in megabytes for the
validatecommand. If the limit is exceeded,validatereturns as many results as possible and warns that not all corruption might be reported because of the limit.You can set
maxValidateMemoryUsageMBduring startup, and can change this setting using thesetParameterdatabase command.
oidcIdentityProvidersNew in version 7.0.7.0版新增。Use this parameter to specify identity provider (IDP) configurations when using OpenID Connect Authentication.
oidcIdentityProvidersaccepts an array of zero or more identity provider (IDP) configurations. An empty array (default) indicates no OpenID Connect support is enabled. When more than one IDP is defined,oidcIdentityProvidersuses thematchPatternfield to select an IDP. Array order determines the priority and the first IDP is always selected.oidcIdentityProviders Fields
Field字段Necessity必要性Description描述Type类型issuerRequired必要的The issuer URI of the IDP that the server should accept tokens from. This must match the issfield in any JWT used for authentication.string authNamePrefixRequired必要的Unique prefix applied to each generated UserNameandRoleNameused in authorization.authNamePrefixcan only contain the following characters:- alphanumeric characters (combination of
atozand0to9) - hyphens (
-) - underscores (
_)
string matchPatternConditional Required when more than one IDP is defined.
Regex pattern used to determine which IDP should be used.matchPatternmatches against usernames. Array order determines the priority and the first IDP is always selected.
This is not a security mechanism.matchPatternserves only as an advisory to clients. MongoDB accepts tokens issued by the IDP whose principal names do not match this pattern.string clientIdRequired必要的ID provided by the IDP to identify the client that receives the access tokens. string audienceRequired必要的Specifies the application or service that the access token is intended for. string requestScopesOptional可选的Permissions and access levels that MongoDB requests from the IDP. array[ string ] principalNameOptional可选的The claim to be extracted from the access token containing MongoDB user identifiers.
The default value issub(stands forsubject).string authorizationClaimRequired必要的Claim extracted from access token that contains MongoDB role names. string logClaimsOptional可选的List of access token claims to include in log and audit messages upon authentication completion. array[ string ] JWKSPollSecsOptional可选的Frequency, in seconds, to request an updated JSON Web Key Set (JWKS) from the IDP. A setting of 0 disables polling. integer You can only set
oidcIdentityProvidersduring startup in theconfiguration fileor with the--setParameteroption on the command line.- alphanumeric characters (combination of
ocspEnabledNew in version 4.4:4.4版新增:Available on Linux and macOS.Default默认值: trueThe flag that enables or disables OCSP.
You can only set
ocspEnabledduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following disables OCSP:mongod --setParameter ocspEnabled=false ...Tip
ocspValidationRefreshPeriodSecsNew in version 4.4:4.4版新增:Available on Linux.The number of seconds to wait before refreshing the stapled OCSP status response. Specify a number greater than or equal to 1.
You can only set
ocspValidationRefreshPeriodSecsduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following sets the parameter to 3600 seconds:mongod --setParameter ocspValidationRefreshPeriodSecs=3600 ...
Starting in MongoDB 5.0, the
rotateCertificatescommand anddb.rotateCertificates()method will also refresh any stapled OCSP responses.TipSee also:另请参阅:
opensslCipherConfig-
Available on Linux only
With the use of native TLS/SSL libraries, the parameter
opensslCipherConfigis supported for Linux/BSD and no longer supported in Windows and macOS. See TLS/SSL.Specify the cipher string for OpenSSL when using TLS/SSL encryption. For a list of cipher strings, see https://www.openssl.org/docs/man1.1.1/man1/ciphers.html
. Multiple cipher strings can be provided as a colon-separated list.
NoteThis parameter is only for use with TLS 1.2 or earlier. To specify cipher suites for use with TLS 1.3, use the
opensslCipherSuiteConfigparameter.You can only set
opensslCipherConfigduring start-up, and cannot change this setting using thesetParameterdatabase command.For version 4.2 and greater, the use of
TLSoptions is preferred overSSLoptions. The TLS options have the same functionality as theSSLoptions. For example, the following configures amongodwith aopensslCipherConfigcipher string of'HIGH:!EXPORT:!aNULL@STRENGTH'in MongoDB 4.2:mongod --setParameter opensslCipherConfig='HIGH:!EXPORT:!aNULL@STRENGTH' --tlsMode requireTLS --tlsCertificateKeyFile Certs/server.pem
opensslCipherSuiteConfigNew in version 5.0.5.0版新增。Available on Linux only
Specify the list of supported cipher suites OpenSSL should permit when using TLS 1.3 encryption.
For a list of cipher suites for use with TLS 1.3, see https://www.openssl.org/docs/man1.1.1/man3/SSL_CTX_set_cipher_list.html
. Multiple cipher suites can be provided as a colon-separated list.
NoteThis parameter is only for use with TLS 1.3. To specify cipher strings for use with TLS 1.2 or earlier, use the
opensslCipherConfigparameter.You can only set
opensslCipherSuiteConfigduring start-up, and cannot change this setting using thesetParameterdatabase command. For example, the following configures amongodwith aopensslCipherSuiteConfigcipher suite of'TLS_AES_256_GCM_SHA384'for use with TLS 1.3:mongod --setParameter opensslCipherSuiteConfig='TLS_AES_256_GCM_SHA384' --tlsMode requireTLS --tlsCertificateKeyFile Certs/server.pem
opensslDiffieHellmanParameters-
Available on Linux only
Specify the path to the PEM file that contains the OpenSSL Diffie-Hellman parameters when using TLS 1.2 or previous. Specifying the OpenSSL Diffie-Hellman parameters enables support for Ephemeral Diffie-Hellman (DHE) cipher suites during TLS/SSL encryption.
This parameter is not supported for use with TLS 1.3.
Ephemeral Diffie-Hellman (DHE) cipher suites (and Ephemeral Elliptic Curve Diffie-Hellman (ECDHE) cipher suites) provide Forward Secrecy. Forward Secrecy cipher suites create an ephemeral session key that is protected by the server's private key but never transmitted. This ensures that even if a server's private key is compromised, you cannot decrypt past sessions with the compromised key.
NoteStarting in MongoDB 4.2, if
opensslDiffieHellmanParametersis unset but ECDHE is enabled, MongoDB enables DHE using theffdhe3072Diffie-Hellman parameter, as defined in RFC-7919#appendix-A.2. The
ffdhe3072is a strong parameter (specifically, size is greater than 1024). Strong parameters are not supported with Java 6 and 7 unless extended support has been purchased from Oracle.You can only set
opensslDiffieHellmanParametersduring startup, and cannot change this setting using thesetParameterdatabase command.If for performance reasons, you need to disable support for DHE cipher suites, use the
opensslCipherConfigparameter:mongod --setParameter opensslCipherConfig='HIGH:!EXPORT:!aNULL:!DHE:!kDHE@STRENGTH' ...
saslauthdPath-
Available for both可用于mongodandmongos.mongod和mongos。NoteAvailable only in MongoDB Enterprise (except MongoDB Enterprise for Windows).
Specify the path to the Unix Domain Socket of the
saslauthdinstance to use for proxy authentication.
saslHostName-
Available for both可用于mongodandmongos.mongod和mongos。saslHostNameoverrides MongoDB's default hostname detection for the purpose of configuring SASL and Kerberos authentication.saslHostNamedoes not affect the hostname of themongodormongosinstance for any purpose beyond the configuration of SASL and Kerberos.You can only set
saslHostNameduring start-up, and cannot change this setting using thesetParameterdatabase command.NotesaslHostNamesupports Kerberos authentication and is only included in MongoDB Enterprise. For more information, see the following:
saslServiceName-
Available for both可用于mongodandmongos.mongod和mongos。Allows users to override the default Kerberos service name component of the Kerberos principal name, on a per-instance basis. If unspecified, the default value is
mongodb.MongoDB only permits setting
saslServiceNameat startup. ThesetParametercommand can not change this setting.saslServiceNameis only available in MongoDB Enterprise.ImportantEnsure that your driver supports alternate service names.
scramIterationCount-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值:10000Changes the number of hashing iterations used for all new
SCRAM-SHA-1passwords. More iterations increase the amount of time required for clients to authenticate to MongoDB, but makes passwords less susceptible to brute-force attempts. The default value is ideal for most common use cases and requirements.If you modify this value, it does not change the iteration count for existing passwords. The
scramIterationCountvalue must be5000or greater.For example, the following sets the
scramIterationCountto12000.mongod --setParameter scramIterationCount=12000
Or, if using the
setParametercommand withinmongosh:db.adminCommand( { setParameter: 1, scramIterationCount: 12000 } )
TipSee also:另请参阅:
scramSHA256IterationCount-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值:15000Changes the number of hashing iterations used for all new
SCRAM-SHA-256passwords. More iterations increase the amount of time required for clients to authenticate to MongoDB, but makes passwords less susceptible to brute-force attempts. The default value is ideal for most common use cases and requirements.If you modify this value, it does not change iteration count for existing passwords. The
scramSHA256IterationCountvalue must be5000or greater.For example, the following sets the
scramSHA256IterationCountto20000.mongod --setParameter scramSHA256IterationCount=20000
Or, if using the
setParametercommand withinmongosh:db.adminCommand( { setParameter: 1, scramSHA256IterationCount: 20000 } )
TipSee also:另请参阅:
sslMode-
Available for both可用于mongodandmongos.mongod和mongos。Set the
net.ssl.modeto eitherpreferSSLorrequireSSL. Useful during rolling upgrade to TLS/SSL to minimize downtime.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .db.adminCommand( { setParameter: 1, sslMode: "preferSSL" } )TipSee also:另请参阅:
tlsModeNew in version 4.2.4.2版新增。Available for both可用于mongodandmongos.mongod和mongos。Set to either:
preferTLSrequireTLS
The
tlsModeparameter is useful during rolling upgrade to TLS/SSL to minimize downtime.db.adminCommand( { setParameter: 1, tlsMode: "preferTLS" } )For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .TipSee also:另请参阅:
tlsClusterAuthX509OverrideNew in version 7.0.7.0版新增。Overrides the
clusterAuthX509configuration options.setParameter:
tlsClusterAuthX509Override: { attributes: O=MongoDB, OU=MongoDB Server }The parameter supports
attributesandextensionValueoverrides.When the server authenticates connections from members, it analyzes the X.509 certificate to determine whether it belongs to a cluster member. If the server uses the
attributessetting or theattributesfield on thetlsClusterAuthX509Overrideparameter, it checks the Distinguished Name (DN) values of the certificate. If theextensionValuesetting or theextensionValuefield of thetlsClusterAuthX509Overrideparameter is set, it checks the extension values of the certificate. If it finds a match, it authorizes the connection as a peer.Use this parameter to rotate certificates when the new certificates have different attributes or extension values.
tlsOCSPStaplingTimeoutSecsNew in version 4.4:4.4版新增:Available for Linux.The maximum number of seconds the
mongod/mongosinstance should wait to receive the OCSP status response for its certificates.Specify an integer greater than or equal to (
>=) 1. If unset,tlsOCSPStaplingTimeoutSecsuses thetlsOCSPVerifyTimeoutSecsvalue.You can only set
tlsOCSPStaplingTimeoutSecsduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following sets thetlsOCSPStaplingTimeoutSecsto 20 seconds:mongod --setParameter tlsOCSPStaplingTimeoutSecs=20 ...
TipSee also:另请参阅:
tlsOCSPVerifyTimeoutSecsNew in version 4.4:4.4版新增:Available for Linux and Windows.Default默认值: 5The maximum number of seconds that the
mongod/mongosshould wait for the OCSP response when verifying server certificates.Specify an integer greater than or equal to (
>=) 1.You can only set
tlsOCSPVerifyTimeoutSecsduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following sets thetlsOCSPVerifyTimeoutSecsto 20 seconds:mongod --setParameter tlsOCSPVerifyTimeoutSecs=20 ...
TipSee also:另请参阅:
tlsWithholdClientCertificateNew in version 4.2.4.2版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值: falseA TLS certificate is set for a
mongodormongoseither by the--tlsClusterFileoption or by the--tlsCertificateKeyFileoption when--tlsClusterFileis not set. If the TLS certificate is set, by default, the instance sends the certificate when initiating intra-cluster communications with othermongodormongosinstances in the deployment. SettlsWithholdClientCertificateto1ortrueto direct the instance to withhold sending its TLS certificate during these communications. Use this option with--tlsAllowConnectionsWithoutCertificates(to allow inbound connections without certificates) on all members of the deployment.tlsWithholdClientCertificateis mutually exclusive with--clusterAuthMode x509.
tlsX509ClusterAuthDNOverrideNew in version 4.2.4.2版新增。Available for both可用于mongodandmongos.mongod和mongos。An alternative Distinguished Name (DN) that the instance can also use to identify members of the deployment.
For a MongoDB deployment that uses x.509 certificates for
clusterAuthMode, deployment members identify each other using x.509 certificates (net.tls.clusterFile, if specified, andnet.tls.certificateKeyFile) during intra-cluster communications. For members of the same deployment, theDNfrom their certificates must have the same Organization attributes (O's), the Organizational Unit attributes (OU's), and the Domain Components (DC's).If
tlsX509ClusterAuthDNOverrideis set for a member, the member can also use the override value when comparing theDNcomponents (O's,OU's, andDC's) of the presented certificates. That is the member checks the presented certificates against itsnet.tls.clusterFile/net.tls.certificateKeyFile. If the DN does not match, the member checks the presented certificate against thetlsX509ClusterAuthDNOverridevalue.NoteIf set, you must set this parameter on all members of the deployment.
You can use this parameter for a rolling update of certificates to new certificates that contain a new
DNvalue. See Rolling Update of x.509 Cluster Certificates that Contain New DN.For more information about membership certificate requirements, see Member Certificate Requirements for details.
tlsX509ExpirationWarningThresholdDaysNew in version 4.4.4.4版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值 : 30Starting in MongoDB 4.4,
mongod/mongoslogs a warning on connection if the presented x.509 certificate expires within30days of themongod/mongossystem clock. Use thetlsX509ExpirationWarningThresholdDaysparameter to control the certificate expiration warning threshold:- Increase the parameter value to trigger warnings farther ahead of the certificate expiration date.
- Decrease the parameter value to trigger warnings closer to the certificate expiration date.
- Set the parameter to
0to disable the warning.
This parameter has a minimum value of
0.You can only set
tlsX509ExpirationWarningThresholdDaysduringmongod/mongosstartup using either:- The
setParameterconfiguration setting, or - The
mongod --setParameter/mongos --setParametercommand line option.
See x.509 Certificates Nearing Expiry Trigger Warnings for more information on x.509 expiration warnings in MongoDB 4.4.
For more information on x.509 certificate validity, see RFC 5280 4.1.2.5.
sslWithholdClientCertificateDeprecated since version 4.2: Use
tlsWithholdClientCertificateinstead.Available for both可用于mongodandmongos.mongod和mongos。Default默认值: falseA TLS certificate is set for a
mongodormongoseither by the--tlsClusterFileoption or by the--tlsCertificateKeyFileoption when--tlsClusterFileis not set. If the TLS certificate is set, by default, the instance sends the certificate when initiating intra-cluster communications with othermongodormongosinstances in the deployment. SetsslWithholdClientCertificateto1ortrueto direct the instance to withhold sending its TLS certificate during these communications. Use this option with--tlsAllowConnectionsWithoutCertificates(to allow inbound connections without certificates) on all members of the deployment.sslWithholdClientCertificateis mutually exclusive with--clusterAuthMode x509.
userCacheInvalidationIntervalSecs-
Available for
mongosonly.Default默认值: 30On a
mongosinstance, specifies the interval (in seconds) at which themongosinstance checks to determine whether the in-memory cache of user objects has stale data, and if so, clears the cache. If there are no changes to user objects,mongoswill not clear the cache.This parameter has a minimum value of
1second and a maximum value of86400seconds (24 hours).
authFailedDelayMs-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值: 0NoteEnterprise Feature
Available in MongoDB Enterprise only.
The number of milliseconds to wait before informing clients that their authentication attempt has failed. This parameter may be in the range
0to5000, inclusive.Setting this parameter makes brute-force login attacks on a database more time-consuming. However, clients waiting for a response from the MongoDB server still consume server resources, and this may adversely impact benign login attempts if the server is denying access to many other clients simultaneously.
allowRolesFromX509Certificates-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值: trueA boolean flag that allows or disallows the retrieval of authorization roles from client x.509 certificates.
You can only set
allowRolesFromX509Certificatesduring startup in the config file or on the command line.
General Parameters
allowDiskUseByDefault-
Available for仅适用于mongodonly.mongod。Default默认值: TrueStarting in MongoDB 6.0, pipeline stages that require more than 100 megabytes of memory to execute write temporary files to disk by default. In earlier verisons of MongoDB, you must pass
{ allowDiskUse: true }to individualfindandaggregatecommands to enable this behavior.Individual
findandaggregatecommands may override theallowDiskUseByDefaultparameter by either:- Using
{ allowDiskUse: true }to allow writing temporary files out to disk whenallowDiskUseByDefaultis set tofalse - Using
{ allowDiskUse: false }to prohibit writing temporary files out to disk whenallowDiskUseByDefaultis set totrue
mongod --setParameter allowDiskUseByDefault=falseallowDiskUseByDefaultonly works onmongodnotmongos.mongosnever writes temporary files to disk. Use thesetParametercommand in amongoshsession that is connected to a runningmongodto change the value of the parameter while the server is running:db.adminCommand(
{
setParameter: 1,
allowDiskUseByDefault: false
}
) - Using
connPoolMaxShardedConnsPerHost-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值: 200Sets the maximum size of the legacy connection pools for communication to the shards. The size of a pool does not prevent the creation of additional connections, but does prevent the connection pools from retaining connections above this limit.
NoteThe parameter is separate from the connections in TaskExecutor pools. See
ShardingTaskExecutorPoolMaxSize.Increase the
connPoolMaxShardedConnsPerHostvalue only if the number of connections in a connection pool has a high level of churn or if the total number of created connections increase.You can only set
connPoolMaxShardedConnsPerHostduring startup in the config file or on the command line.For example:例如:mongos --setParameter connPoolMaxShardedConnsPerHost=250
connPoolMaxShardedInUseConnsPerHost-
Available for both可用于mongodandmongos.mongod和mongos。Sets the maximum number of in-use connections at any given time for the legacy sharded cluster connection pools.
By default, the parameter is unset.默认情况下,该参数是未设置的。You can only set
connPoolMaxShardedConnsPerHostduring startup in the config file or on the command line.For example:例如:mongos --setParameter connPoolMaxShardedInUseConnsPerHost=100
TipSee also:另请参阅:
httpVerboseLogging-
Available for both可用于mongodandmongos.mongod和mongos。Adds more verbose tracing for curl on Linux and macOS. Has no affect on Windows.
By default, the parameter is unset.默认情况下,该参数是未设置的。You can only set
httpVerboseLoggingduring startup in the config file or on the command line.For example:例如:mongos --setParameter httpVerboseLogging=true
shardedConnPoolIdleTimeoutMinutes-
Available for both可用于mongodandmongos.mongod和mongos。Sets the time limit that a connection in the legacy sharded cluster connection pool can remain idle before being closed.
By default, the parameter is unset.默认情况下,该参数是未设置的。You can only set
shardedConnPoolIdleTimeoutMinutesduring startup in the config file or on the command line.For example:例如:mongos --setParameter shardedConnPoolIdleTimeoutMinutes=10
TipSee also:另请参阅:
slowConnectionThresholdMillisNew in version 6.3.6.3版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值: 100Sets the time limit in milliseconds to log the establishment of slow server connections.
If a connection takes longer to establish than the
slowConnectionThresholdMillisparameter, an event is added to the log with the messagemsgfield set to"Slow connection establishment".The following example sets
slowConnectionThresholdMillisto250milliseconds.mongod --setParameter slowConnectionThresholdMillis=250
Or, if using the
setParametercommand withinmongosh:db.adminCommand( { setParameter: 1, slowConnectionThresholdMillis: 250 } )
connPoolMaxConnsPerHost-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值: 200Sets the maximum size of the legacy connection pools for outgoing connections to other
mongodinstances in the global connection pool. The size of a pool does not prevent the creation of additional connections, but does prevent a connection pool from retaining connections in excess of the value ofconnPoolMaxConnsPerHost.NoteThe parameter is separate from the connections in TaskExecutor pools. See
ShardingTaskExecutorPoolMaxSize.Only adjust this setting if your driver does not pool connections and you're using authentication in the context of a sharded cluster.
You can only set
connPoolMaxConnsPerHostduring startup in the config file or on the command line.For example:例如:mongod --setParameter connPoolMaxConnsPerHost=250
connPoolMaxInUseConnsPerHost-
Available for both可用于mongodandmongos.mongod和mongos。Sets the maximum number of in-use connections at any given time for for outgoing connections to other
mongodinstances in the legacy global connection pool.By default, the parameter is unset.默认情况下,该参数是未设置的。You can only set
connPoolMaxInUseConnsPerHostduring startup in the config file or on the command line.For example:例如:mongod --setParameter connPoolMaxInUseConnsPerHost=100
TipSee also:另请参阅:
globalConnPoolIdleTimeoutMinutes-
Available for both可用于mongodandmongos.mongod和mongos。Sets the time limit that connection in the legacy global connection pool can remain idle before being closed.
By default, the parameter is unset.默认情况下,该参数是未设置的。You can only set
globalConnPoolIdleTimeoutMinutesduring startup in the config file or on the command line.For example:例如:mongos --setParameter globalConnPoolIdleTimeoutMinutes=10
TipSee also:另请参阅:
cursorTimeoutMillis-
Available for both可用于mongodandmongos.mongod和mongos。Default默认值: 600000 (10 minutes)Sets the expiration threshold in milliseconds for idle cursors before MongoDB removes them; specifically, MongoDB removes cursors that have been idle for the specified
cursorTimeoutMillis.For example, the following sets the
cursorTimeoutMillisto300000milliseconds (5 minutes).mongod --setParameter cursorTimeoutMillis=300000
Or, if using the
setParametercommand withinmongosh:db.adminCommand( { setParameter: 1, cursorTimeoutMillis: 300000 } )
Setting
cursorTimeoutMillisto less than or equal to0results in all cursors being immediately eligible for timeout. Generally, the timeout value should be greater than the average amount of time for a query to return results. Use tools like thecursor.explain()cursor modifier to analyze the average query time and select an appropriate timeout period.
failIndexKeyTooLong-
Removed in 4.4
Important- MongoDB 4.4 removes the deprecated
failIndexKeyTooLongparameter. Attempting to use this parameter with MongoDB 4.4 will result in an error. - MongoDB 4.2 deprecates the
failIndexKeyTooLongparameter and removes the Index Key Length Limit for featureCompatibilityVersion (fCV) set to"4.2"or greater.
Setting
failIndexKeyTooLongtofalseis a temporary workaround, not a permanent solution to the problem of oversized index keys. WithfailIndexKeyTooLongset tofalse, queries can return incomplete results if they use indexes that skip over documents whose indexed fields exceed the Index Key Length Limit.failIndexKeyTooLongdefaults totrue.Issue the following command to disable the index key length validation:
db.adminCommand( { setParameter: 1, failIndexKeyTooLong: false } )
You can also set
failIndexKeyTooLongat startup with the following option:mongod --setParameter failIndexKeyTooLong=false - MongoDB 4.4 removes the deprecated
maxNumActiveUserIndexBuilds-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 3Sets the maximum number of concurrent index builds allowed on the primary. This is a global limit that applies across all collections.
Increasing the value of
maxNumActiveUserIndexBuildsallows additional concurrent index builds at the cost of increased pressure on the WiredTiger cache.System indexes are not limited to
maxNumActiveUserIndexBuilds, however a system index build counts against the limit for user index builds.After the server reaches
maxNumActiveUserIndexBuilds, it blocks additional user index builds until the number of concurrent index builds drops below themaxNumActiveUserIndexBuildslimit. If an index build is blocked, the server logs this message:Too many index builds running simultaneously, waiting until the
number of active index builds is below the threshold.The following command sets a limit of 4 concurrent index builds:
db.adminCommand( { setParameter: 1, maxNumActiveUserIndexBuilds: 4 } )
See also:
notablescan-
Available for仅适用于mongodonly.mongod。Specify whether all queries must use indexes. If
1, MongoDB will not execute queries that require a collection scan and will return an error.Consider the following example which sets
notablescanto1or true:db.adminCommand( { setParameter: 1, notablescan: 1 } )
Setting
notablescanto1can be useful for testing application queries, for example, to identify queries that scan an entire collection and cannot use an index.To detect unindexed queries without
notablescan, consider reading the Evaluate Performance of Current Operations and Optimize Query Performance sections and using thelogLevelparameter,mongostatand profiling.Don't run production
mongodinstances withnotablescanbecause preventing collection scans can potentially affect queries in all databases, including administrative queries.
ttlMonitorEnabled-
Available for仅适用于mongodonly.mongod。Default默认值:trueTo support TTL Indexes,
mongodinstances have a background thread that is responsible for deleting documents from collections with TTL indexes.To disable this worker thread for a
mongod, setttlMonitorEnabledtofalse, as in the following operations:db.adminCommand( { setParameter: 1, ttlMonitorEnabled: false } )
Alternately, you may disable the thread at startup time by starting the
mongodinstance with the following option:mongod --setParameter ttlMonitorEnabled=falseImportantDo not run production
mongodinstances withttlMonitorEnableddisabled, except under guidance from MongoDB support. Preventing TTL document removal can negatively impact MongoDB internal system operations that depend on TTL Indexes.
tcpFastOpenServerNew in version 4.4.4.4版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值:trueEnables support for accepting inbound TCP Fast Open (TFO) connections to the
mongod/mongosfrom a client. TFO requires both the client andmongod/mongoshost machine support and enable TFO:- Windows
-
The following Windows operating systems support TFO:
- Microsoft Windows Server 2016 and later.
- Microsoft Windows 10 Update 1607 and later.
- macOS
- macOS 10.11 (El Capitan) and later support TFO.
- Linux
-
Linux operating systems running Linux Kernel 3.7 or later can support inbound TFO.
Set the value of
/proc/sys/net/ipv4/tcp_fastopento enable inbound TFO connections:- Set to
2to enable only inbound TFO connections. - Set to
3to enable inbound and outbound TFO connections.
- Set to
This parameter has no effect if the host operating system does not support or is not configured to support TFO connections.
You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.See Support for TCP Fast Open for more information on MongoDB TFO support.
TipSee also:另请参阅:
tcpFastOpenClientNew in version 4.4.4.4版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值:trueLinux Operating System Only
Enables support for outbound TCP Fast Open (TFO) connections from the
mongod/mongosto a client. TFO requires both the client and themongod/mongoshost machine support and enable TFO.Linux operating systems running Linux Kernel 4.11 or later can support outbound TFO.
Set the value of
/proc/sys/net/ipv4/tcp_fastopento enable outbound TFO connections:1to enable only outbound TFO connections.3to enable inbound and outbound TFO connections.
This parameter has no effect if the host operating system does not support or is not configured to support TFO connections.
You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.See Support for TCP Fast Open for more information on MongoDB TFO support.
TipSee also:另请参阅:
tcpFastOpenQueueSizeNew in version 4.4.4.4版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值:1024As part of establishing a TCP Fast Open (TFO) connection, the client submits a valid TFO cookie to the
mongod/mongosbefore completion of the standard TCP 3-way handshake. Themongod/mongoskeeps a queue of all such pending TFO connections.The
tcpFastOpenQueueSizeparameter sets the size of the queue of pending TFO connections. While the queue is full, themongod/mongosfalls back to the normal three-way handshake for incoming client requests and ignores the presence of TFO cookies. Once the queue size falls back below the limit, themongod/mongosbegins accepting new TFO cookies.- Increasing the default queue size may improve the effect of TFO on network performance. However, large queue sizes also increase the risk of server resource exhaustion due to excessive incoming TFO requests.
- Decreasing the default queue size may reduce the risk of resource server resource exhaustion due to excessive incoming TFO requests. However, small queue sizes may also reduce the effect of TFO on network performance.
The minimum queue size is
0. A queue of0effectively disables TFO.
This parameter has no effect on host operating systems that do not support or are not configured for TFO connections. See Support for TCP Fast Open for more information on MongoDB TFO support.
disableJavaScriptJIT-
Available for仅适用于mongodonly.mongod。The MongoDB JavaScript engine uses SpiderMonkey, which implements Just-in-Time (JIT) compilation for improved performance when running scripts.
To enable the JIT, set
disableJavaScriptJITtofalse, as in the following example:db.adminCommand( { setParameter: 1, disableJavaScriptJIT: false } )
Note$wherewill reuse existing JavaScript interpreter contexts, so changes todisableJavaScriptJITmay not take effect immediately for these operations.Alternately, you may enable the JIT at startup time by starting the
mongodinstance with the following option:mongod --setParameter disableJavaScriptJIT=false
indexMaxNumGeneratedKeysPerDocumentNew in version 5.3.5.3版新增。Default默认值: 100000Limits the maximum number of keys generated for a document to prevent out of memory errors. It is possible to raise the limit, but if an operation requires more keys than the
indexMaxNumGeneratedKeysPerDocumentparameter specifies, the operation will fail.
maxIndexBuildMemoryUsageMegabytes-
Default默认值:- 200 (For versions 4.2.3 and later)
- 500 (For versions 4.2.2 and earlier)
Limits the amount of memory that simultaneous index builds on one collection may consume for the duration of the builds. The specified amount of memory is shared between all indexes built using a single
createIndexescommand or its shell helperdb.collection.createIndexes().The memory consumed by an index build is separate from the WiredTiger cache memory (see
cacheSizeGB).Index builds may be initiated either by a user command such as
createIndexesor by an administrative process such as an initial sync. Both are subject to the limit set bymaxIndexBuildMemoryUsageMegabytes.An initial sync populates only one collection at a time and has no risk of exceeding the memory limit. However, it is possible for a user to start index builds on multiple collections in multiple databases simultaneously and potentially consume an amount of memory greater than the limit set by
maxIndexBuildMemoryUsageMegabytes.TipTo minimize the impact of building an index on replica sets and sharded clusters with replica set shards, use a rolling index build procedure as described on Rolling Index Builds on Replica Sets.
- For feature compatibility version (fcv)
"4.2"and later, the index build memory limit applies to all index builds.
reportOpWriteConcernCountersInServerStatus-
Default默认值: falseA boolean flag that determines whether the
db.serverStatus()method andserverStatuscommand returnopWriteConcernCountersinformation. [1]You can only set
reportOpWriteConcernCountersInServerStatusduring startup in the config file or on the command line.For example:例如:mongod --setParameter reportOpWriteConcernCountersInServerStatus=true[1] Enabling reportOpWriteConcernCountersInServerStatuscan have a negative performance impact; specifically, when running without TLS.
watchdogPeriodSeconds-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: -1 (disabled)Determines how frequent the Storage Node Watchdog checks the status of the monitored filesystems:
- The
--dbpathdirectory - The
journaldirectory inside the--dbpathdirectory - The directory of
--logpathfile - The directory of
--auditPathfile
Valid values for
watchdogPeriodSecondsare:-1(the default), to disable/pause Storage Node Watchdog, or- An integer greater than or equal to 60.
Note- If a filesystem on a monitored directory becomes unresponsive, it can take a maximum of nearly twice the value of
watchdogPeriodSecondsto terminate themongod. - If any of its monitored directory is a symlink to other volumes, the Storage Node Watchdog does not monitor the symlink target. For example, if the
mongodusesstorage.directoryPerDB: true(or--directoryperdb) and symlinks a database directory to another volume, the Storage Node Watchdog does not follow the symlink to monitor the target.
To enable Storage Node Watchdog,
watchdogPeriodSecondsmust be set during startup.mongod --setParameter watchdogPeriodSeconds=60
You can only enable the Storage Node Watchdog at startup. However, once enabled, you can pause the Storage Node Watchdog or change the
watchdogPeriodSecondsduring run time.Once enabled,
- To pause the Storage Node Watchdog during run time, set
watchdogPeriodSecondsto -1.db.adminCommand( { setParameter: 1, watchdogPeriodSeconds: -1 } )
- To resume or change the period during run time, set
watchdogPeriodSecondsto a number greater than or equal to 60.db.adminCommand( { setParameter: 1, watchdogPeriodSeconds: 120 } )
NoteIt is an error to set
watchdogPeriodSecondsat run time if the Storage Node Watchdog was not enabled at startup time. - The
tcmallocReleaseRateNew in version 4.2.3.4.2.3版新增。Default: 1.0
Specifies the tcmalloc release rate (TCMALLOC_RELEASE_RATE
). Per https://gperftools.github.io/gperftools/tcmalloc.html#runtime
TCMALLOC_RELEASE_RATE is described as the "Rate at which we release unused memory to the system, via madvise(MADV_DONTNEED), on systems that support it. Zero means we never release memory back to the system. Increase this flag to return memory faster; decrease it to return memory slower. Reasonable rates are in the range [0,10]."
To modify the release rate during run time, you can use the
setParametercommand;for example:例如:db.adminCommand( { setParameter: 1, tcmallocReleaseRate: 5.0 } )
You can also set
tcmallocReleaseRateat startup time;for example:例如:mongod --setParameter "tcmallocReleaseRate=5.0"
fassertOnLockTimeoutForStepUpDownNew in version 5.3.5.3版新增。Available for both可用于mongodandmongos.mongod和mongos。Default: 15 seconds
Allows a server that receives a request to step up or step down, to terminate if it is unable to comply (for example due to faulty server disks) within the timeout. This enables a cluster to successfully elect a new primary node and thus continue to be available.
fassertOnLockTimeoutForStepUpDowndefaults to 15 seconds. To disable nodes from fasserting, setfassertOnLockTimeoutForStepUpDown=0.The following example disables nodes from fasserting:
mongod --setParameter fassertOnLockTimeoutForStepUpDown=0
Logging Parameters
logLevel-
Available for both可用于mongodandmongos.mongod和mongos。Specify an integer between
0and5signifying the verbosity of the logging, where5is the most verbose. [2]The default
logLevelis0(Informational).The following example sets the
logLevelto2:db.adminCommand( { setParameter: 1, logLevel: 2 } )
TipSee also:另请参阅:[2] Starting in version 4.2, MongoDB includes the Debug verbosity level (1-5) in the log messages. For example, if the verbosity level is 2, MongoDB logs D2. In previous versions, MongoDB log messages only specifiedDfor Debug level.
logComponentVerbosity-
Available for both可用于mongodandmongos.mongod和mongos。Sets the verbosity levels of various components for log messages. The verbosity level determines the amount of Informational and Debug messages MongoDB outputs. [3]
The verbosity level can range from
0to5:0is the MongoDB's default log verbosity level, to include Informational messages.1to5increases the verbosity level to include Debug messages.
For a component, you can also specify
-1to inherit the parent's verbosity level.To specify the verbosity level, use a document similar to the following:
{
verbosity: <int>,
<component1>: { verbosity: <int> },
<component2>: {
verbosity: <int>,
<component3>: { verbosity: <int> }
},
...
}For the components, you can specify just the
<component>: <int>in the document, unless you are setting both the parent verbosity level and that of the child component(s) as well:{
verbosity: <int>,
<component1>: <int> ,
<component2>: {
verbosity: <int>,
<component3>: <int>
}
...
}The top-level
verbosityfield corresponds tosystemLog.verbositywhich sets the default level for all components. The default value ofsystemLog.verbosityis0.The components correspond to the following settings:
accessControlcommandcontrolftdcgeoindexnetworkqueryreplicationreplication.electionreplication.heartbeatsreplication.initialSyncreplication.rollbackrecoveryshardingstoragestorage.journaltransactionwrite
Unless explicitly set, the component has the verbosity level of its parent. For example,
storageis the parent ofstorage.journal. That is, if you specify astorageverbosity level, this level also applies to:storage.journalcomponents unless you specify the verbosity level forstorage.journal.storage.recoverycomponents unless you specify the verbosity level forstorage.recovery.
For example, the following sets the
default verbosity levelto1, thequeryto2, thestorageto2, and thestorage.journalto1.db.adminCommand( {
setParameter: 1,
logComponentVerbosity: {
verbosity: 1,
query: { verbosity: 2 },
storage: {
verbosity: 2,
journal: {
verbosity: 1
}
}
}
} )You can also set parameter
logComponentVerbosityat startup time, passing the verbosity level document as a string.mongod --setParameter "logComponentVerbosity={command: 3}"mongoshalso provides thedb.setLogLevel()to set the log level for a single component. For various ways to set the log verbosity level, see Configure Log Verbosity Levels.[3] Starting in version 4.2, MongoDB includes the Debug verbosity level (1-5) in the log messages. For example, if the verbosity level is 2, MongoDB logs D2. In previous versions, MongoDB log messages only specifiedDfor Debug level.
maxLogSizeKB-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: non-negative integerDefault默认值: 10Specifies the maximum size, in kilobytes, for an individual attribute field in a log entry; attributes exceeding this limit are truncated.
Truncated attribute fields print field content up to the
maxLogSizeKBlimit and excise field content past that limit, retaining valid JSON formatting. Log entries that contain truncated attributes append atruncatedobject to the end of the log entry.See log message truncation for more information.
A value of
0disables truncation entirely. Negative values for this parameter are not valid.WarningUsing a large value, or disabling truncation with a value of
0, may adversely affect system performance and negatively impact database operations.The following example sets the maximum log line size to
20kilobytes:mongod --setParameter maxLogSizeKB=20
quiet-
Available for both可用于mongodandmongos.mongod和mongos。Sets quiet logging mode. If
1,mongodwill go into a quiet logging mode which will not log the following events/activities:- connection events;
- the
dropcommand, thedropIndexescommand, thevalidatecommand; and - replication synchronization activities.
Consider the following example which sets the
quietparameter to1:db.adminCommand( { setParameter: 1, quiet: 1 } )
TipSee also:另请参阅:
redactClientLogData-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanNoteEnterprise Feature
Available in MongoDB Enterprise only.
Configure the
mongodormongosto redact any message accompanying a given log event before logging. This prevents the program from writing potentially sensitive data stored on the database to the diagnostic log. Metadata such as error or operation codes, line numbers, and source file names are still visible in the logs.Use
redactClientLogDatain conjunction with Encryption at Rest and TLS/SSL (Transport Encryption) to assist compliance with regulatory requirements.To enable log redaction at startup, you can either:
- Start
mongodwith the--redactClientLogDataoption:mongod --redactClientLogData
- Set the
security.redactClientLogDataoption in the configuration file:security:
redactClientLogData: true
...
You can't use the
--setParameteroption to setredactClientLogDataat startup.To enable log redaction on a running
mongodormongos, use the following command:db.adminCommand( { setParameter: 1, redactClientLogData : true } )
TipSee also:另请参阅: - Start
redactEncryptedFieldsNew in version 6.1.0.6.1.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值:trueConfigures
mongodandmongosto redact field values of encryptedBinarydata from all log messages.- If the
redactClientLogDataparameter or thesecurity.redactClientLogDatasetting is set tofalseandredactEncryptedFieldsis set totrue(the default), encrypted fields are redacted from all log messages. - If the
redactClientLogDataparameter orsecurity.redactClientLogDatasetting is set totrue, all fields are redacted, regardless of theredactEncryptedFieldssetting.
- If the
traceExceptions-
Available for both可用于mongodandmongos.mongod和mongos。Configures
mongodto log full source code stack traces for every database and socket C++ exception, for use with debugging. Iftrue,mongodwill log full stack traces.Consider the following example which sets the
traceExceptionstotrue:db.adminCommand( { setParameter: 1, traceExceptions: true } )
TipSee also:另请参阅:
suppressNoTLSPeerCertificateWarning-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: falseBy default, a
mongodormongoswith TLS/SSL enabled andnet.ssl.allowConnectionsWithoutCertificates:truelets clients connect without providing a certificate for validation while logging an warning. SetsuppressNoTLSPeerCertificateWarningto1ortrueto suppress those warnings.The following operation sets
suppressNoTLSPeerCertificateWarningtotrue:db.adminCommand( { setParameter: 1, suppressNoTLSPeerCertificateWarning: true} )
gEnableDetailedConnectionHealthMetricLogLinesNew in version 7.0.7.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: trueDetermines whether to enable specific log messages related to cluster connection health metrics. If
gEnableDetailedConnectionHealthMetricLogLinesis set tofalse, the following log messages are turned off, but MongoDB still collects data on the cluster connection health metrics:Log Message Description描述Accepted TLS connection from peer Indicates that the server successfully parsed the peer certificate during the TLS handshake with an accepted ingress connection. Ingress TLS handshake complete Indicates that the TLS handshake with an ingress connection is complete. Hello completed Indicates that the initial connection handshake completed on an incoming client connection.
MongoDB displays the log message only with the firsthellocommand.Auth metrics report Specifies the completion of a step in the authentication conversation. Received first command on ingress connection since session start or auth handshake Indicates that an ingress connection received the first command that is not part of the handshake. Slow network response send time Indicates that the time spent, in milliseconds, to send the response back to the client over an ingress connection takes more time than the duration defined by the slowMSserver parameter.Completed client-side verification of OCSP request If the peer doesn't include an OCSP response to the TLS handshake when an egress TLS connection is established, the server must send an OCSP request to the certificate authority. MongoDB writes this log message when the certificate authority receives the OCSP response. Slow connection establishment Indicates that the time taken to send a response back to the client over an ingress connection takes longer than the threshold specified with the slowConnectionThresholdMillisparameter. MongoDB also emits this log message when the connection establishment times out.Operation timed out while waiting to acquire connection Indicates that an operation timed out while waiting to acquire an egress connection. Acquired connection for remote operation and completed writing to wire Indicates that the server took one millisecond or longer to write an outgoing request on an egress connection, counting from the instant when the connection establishes.
Diagnostic Parameters
To facilitate analysis of the MongoDB server behavior by MongoDB engineers, MongoDB logs server statistics to diagnostic files at periodic intervals.
For mongod, the diagnostic data files are stored in the diagnostic.data directory under the mongod instance's --dbpath or storage.dbPath.
For mongos, the diagnostic data files, by default, are stored in a directory under the mongos instance's --logpath or systemLog.path directory. The diagnostic data directory is computed by truncating the logpath's file extension(s) and concatenating diagnostic.data to the remaining name.
For example, if mongos has --logpath /var/log/mongodb/mongos.log.201708015, then the diagnostic data directory is /var/log/mongodb/mongos.diagnostic.data/ directory. To specify a different diagnostic data directory for mongos, set the diagnosticDataCollectionDirectoryPath parameter.
The following parameters support diagnostic data capture (FTDC):
The default values for the diagnostic data capture interval and the maximum sizes are chosen to provide useful data to MongoDB engineers with minimal impact on performance and storage size. Typically, these values will only need modifications as requested by MongoDB engineers for specific diagnostic purposes.
diagnosticDataCollectionEnabled-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: trueDetermines whether to enable the collecting and logging of data for diagnostic purposes. Diagnostic logging is enabled by default.
For example, the following disables the diagnostic collection:
mongod --setParameter diagnosticDataCollectionEnabled=false
diagnosticDataCollectionDirectoryPath-
Available for
mongosonly.Type类型: StringWarningIf Full Time Diagnostic Data Capture (FTDC) is disabled with
diagnosticDataCollectionEnabledor ifsystemLog.destinationis set tosyslog, you must restartmongosafter settingdiagnosticDataCollectionDirectoryPath.Specify the directory for the diagnostic directory for
mongos. If the directory does not exist,mongoscreates the directory.If unspecified, the diagnostic data directory is computed by truncating the
mongosinstance's--logpathorsystemLog.pathfile extension(s) and concatenatingdiagnostic.data.For example, if
mongoshas--logpath /var/log/mongodb/mongos.log.201708015, then the diagnostic data directory is/var/log/mongodb/mongos.diagnostic.data/.If the
mongoscannot create the specified directory, the diagnostic data capture is disabled for that instance.mongosmay not be able to create the specified directory if a file with the same name already exists in the path or if the process does not have permissions to create the directory.
diagnosticDataCollectionDirectorySizeMB-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 200Specifies the maximum size, in megabytes, of the
diagnostic.datadirectory. If directory size exceeds this number, the oldest diagnostic files in the directory are automatically deleted based on the timestamp in the file name.For example, the following sets the maximum size of the directory to
250megabytes:mongod --setParameter diagnosticDataCollectionDirectorySizeMB=250
The minimum value for
diagnosticDataCollectionDirectorySizeMBis10megabytes.diagnosticDataCollectionDirectorySizeMBmust be greater than maximum diagnostic file sizediagnosticDataCollectionFileSizeMB.
diagnosticDataCollectionFileSizeMB-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 10Specifies the maximum size, in megabytes, of each diagnostic file. If the file exceeds the maximum file size, MongoDB creates a new file.
For example, the following sets the maximum size of each diagnostic file to
20megabytes:mongod --setParameter diagnosticDataCollectionFileSizeMB=20
The minimum value for
diagnosticDataCollectionFileSizeMBis1megabyte.
diagnosticDataCollectionPeriodMillis-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 1000Specifies the interval, in milliseconds, at which to collect diagnostic data.
For example, the following sets the interval to
5000milliseconds or 5 seconds:mongod --setParameter diagnosticDataCollectionPeriodMillis=5000
The minimum value for
diagnosticDataCollectionPeriodMillisis100milliseconds.
Replication and Consistency
disableSplitHorizonIPCheckNew in version 5.0.0.5.0.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: false
To configure cluster nodes for split horizon DNS, use host names instead of IP addresses.
Starting in MongoDB v5.0, replSetInitiate and replSetReconfig reject configurations that use IP addresses instead of hostnames.
Use disableSplitHorizonIPCheck to modify nodes that cannot be updated to use host names. The parameter only applies to the configuration commands.
mongod and mongos do not rely on disableSplitHorizonIPCheck for validation at startup. Legacy mongod and mongos instances that use IP addresses instead of host names will start after an upgrade.
Instances that are configured with IP addresses log a warning to use host names instead of IP addresses.
To allow configuration changes using IP addresses, set disableSplitHorizonIPCheck=true using the command line:
/usr/local/bin/mongod --setParameter disableSplitHorizonIPCheck=true -f /etc/mongod.conf
To allow configuration changes using IP addresses, set disableSplitHorizonIPCheck=true using the node's configuration file:
setParameter:
disableSplitHorizonIPCheck: true
If you attempt to update disableSplitHorizonIPCheck at run time, db.adminCommand() returns an error:
db.adminCommand( { setParameter: 1, "disableSplitHorizonIPCheck": true } )
MongoServerError: not allowed to change [disableSplitHorizonIPCheck] at run time
enableOverrideClusterChainingSettingNew in version 5.0.2.5.0.2版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: falseIf
enableOverrideClusterChainingSettingistrue, replica set secondary members can replicate data from other secondary members even ifsettings.chainingAllowedisfalse.You can only set
enableOverrideClusterChainingSettingat startup and cannot change this setting with thesetParametercommand.For example, to set the
enableOverrideClusterChainingSettingfor amongodinstance totrue:mongod --setParameter enableOverrideClusterChainingSetting=true
logicalSessionRefreshMillis-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 300000 (5 minutes)The interval (in milliseconds) at which the cache refreshes its logical session records against the main session store.
You can only set
logicalSessionRefreshMillisat startup and cannot change this setting with thesetParametercommand.For example, to set the
logicalSessionRefreshMillisfor amongodinstance to 10 minutes:mongod --setParameter logicalSessionRefreshMillis=600000
localLogicalSessionTimeoutMinutes-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 30WarningFor testing purposes only
This parameter is intended for testing purposes only and not for production use.
The time in minutes that a session remains active after its most recent use. Sessions that have not received a new read/write operation from the client or been refreshed with
refreshSessionswithin this threshold are cleared from the cache. State associated with an expired session may be cleaned up by the server at any time.This parameter applies only to the instance on which it is set. To set this parameter on replica sets and sharded clusters, you must specify the same value on every member; otherwise, sessions will not function properly.
You can only set
localLogicalSessionTimeoutMinutesat startup and cannot change this setting with thesetParametercommand.For example, to set the
localLogicalSessionTimeoutMinutesfor a testmongodinstance to 20 minutes:mongod --setParameter localLogicalSessionTimeoutMinutes=20
maxAcceptableLogicalClockDriftSecs-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 31536000 (1 year)The maximum amount by which the current cluster time can be advanced; specifically,
maxAcceptableLogicalClockDriftSecsis the maximum difference between the new value of the cluster time and the current cluster time. Cluster time is a logical time used for ordering of operations.You cannot advance the cluster time to a new value if the new cluster time differs from the current cluster time by more than
maxAcceptableLogicalClockDriftSecs.You can only set
maxAcceptableLogicalClockDriftSecsat startup and cannot change this setting with thesetParametercommand.For example, to set the
maxAcceptableLogicalClockDriftSecsfor amongodinstance to 15 minutes:mongod --setParameter maxAcceptableLogicalClockDriftSecs=900
maxSessions-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 1000000The maximum number of sessions that can be cached.
You can only set
maxSessionsduring start-up.For example, to set the
maxSessionsfor amongodinstance to 1000:mongod --setParameter maxSessions=1000
oplogBatchDelayMillisNew in version 6.0.6.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 0The number of milliseconds to delay applying batches of oplog operations on secondary nodes. By default,
oplogBatchDelayMillisis0, meaning oplog batches are applied with no delay. When there is no delay, MongoDB may apply frequent, small oplog batches to secondaries.Increasing
oplogBatchDelayMilliscauses MongoDB to apply oplog batches less frequently on secondaries, with each batch containing larger amounts of data. This reduces IOPS on secondaries, but adds latency for writes with write concern"majority".You can only set
oplogBatchDelayMillisat startup. You cannot setoplogBatchDelayMillisduring run time.For example, run the following command to set the
oplogBatchDelayMillisfor amongodinstance to 20 milliseconds:mongod --setParameter oplogBatchDelayMillis=20
storeFindAndModifyImagesInSideCollectionNew in version 5.1.5.1版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: trueDetermines whether the temporary documents required for retryable
findAndModifycommands are stored in the side collection (config.image_collection).If
storeFindAndModifyImagesInSideCollectionis:true, the temporary documents are stored in the side collection.false, the temporary documents are stored in the replica set oplog.
Keep
storeFindAndModifyImagesInSideCollectionset totrueif you:- Have a large retryable
findAndModifyworkload. - Require more temporary document space for retryable
findAndModifycommands than is available in the replica set oplog.
NoteSecondaries may experience increased CPU usage when
storeFindAndModifyImagesInSideCollectionistrue.For example, to set
storeFindAndModifyImagesInSideCollectiontofalseduring startup:mongod --setParameter storeFindAndModifyImagesInSideCollection=falseDuring run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, storeFindAndModifyImagesInSideCollection: false } )
TransactionRecordMinimumLifetimeMinutes-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 30The minimum lifetime a transaction record exists in the
transactionscollection before the record becomes eligible for cleanup.You can only set
TransactionRecordMinimumLifetimeMinutesat startup and cannot change this setting with thesetParametercommand.For example, to set the
TransactionRecordMinimumLifetimeMinutesfor amongodinstance to 20 minutes:mongod --setParameter TransactionRecordMinimumLifetimeMinutes=20
TipSee also:另请参阅:
enableFlowControlNew in version 4.2.4.2版新增。Type类型: booleanDefault默认值: trueEnables or disables the mechanism that controls the rate at which the primary applies its writes with the goal of keeping the secondary members'
majority committedlag under a configurable maximum value.NoteFor flow control to engage, the replica set/sharded cluster must have: featureCompatibilityVersion (fCV) of
4.2and read concernmajority enabled. That is, enabled flow control has no effect if fCV is not4.2or if read concern majority is disabled.
flowControlTargetLagSecondsNew in version 4.2.4.2版新增。Type类型: integerDefault默认值: 10The target maximum
majority committedlag when running with flow control. When flow control is enabled, the mechanism attempts to keep themajority committedlag under the specified seconds. The parameter has no effect if flow control is disabled.The specified value must be greater than 0.
In general, the default settings should suffice; however, if modifying from the default value, decreasing, rather than increasing, the value may prove to be more useful.
flowControlWarnThresholdSecondsNew in version 4.2.4.2版新增。Type类型: integerDefault默认值: 10The amount of time to wait to log a warning once the flow control mechanism detects the majority commit point has not moved.
The specified value must be greater than or equal to 0, with 0 to disable warnings.
initialSyncTransientErrorRetryPeriodSecondsNew in version 4.4.4.4版新增。Type类型: integerDefault默认值: 86400The amount of time in seconds a secondary performing initial sync attempts to resume the process if interrupted by a transient network error. The default value is equivalent to 24 hours.
initialSyncSourceReadPreferenceNew in version 4.4.4.4版新增。Available for仅适用于mongodonly.mongod。Type类型: StringThe preferred source for performing initial sync. Specify one of the following read preference modes:
primaryprimaryPreferred(Default for voting replica set members)secondarysecondaryPreferrednearest(Default for newly added or non-voting replica set members)
If the replica set has disabled
chaining, the defaultinitialSyncSourceReadPreferenceread preference mode isprimary.You cannot specify a tag set or
maxStalenessSecondstoinitialSyncSourceReadPreference.If the
mongodcannot find a sync source based on the specified read preference, it logs an error and restarts the initial sync process. Themongodexits with an error if it cannot complete the initial sync process after10attempts. For more information on sync source selection, see Initial Sync Source Selection.initialSyncSourceReadPreferencetakes precedence over the replica set'ssettings.chainingAllowedsetting when selecting an initial sync source. After a replica set member successfully completes initial sync, it defers to the value ofchainingAllowedwhen selecting a replication sync source.You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.
initialSyncMethodNew in version 5.2.5.2版新增。Available for仅适用于mongodonly.mongod。Type类型: StringDefault默认值:logicalAvailable only in MongoDB Enterprise.
Method used for initial sync.
Set to
logicalto use logical initial sync. Set tofileCopyBasedto use file copy based initial sync.This parameter only affects the sync method for the member on which it is specified. Setting this parameter on a single replica set member does not affect the sync method of any other replica set members.
You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.
maxNumSyncSourceChangesPerHourNew in version 5.0.5.0版新增。Type类型: integerDefault默认值: 3Sync sources are evaluated each time a sync source is updated and each time a node fetches a batch of oplog entries. If there are more than
maxNumSyncSourceChangesPerHoursource changes in an hour, the node temporarily stops re-evaluating that sync source. If this parameter is set with a high value, the node may make unnecessary source changes.This parameter will not prevent a node from starting to sync from another node if it doesn't have a sync source. The node will re-evaluate if a sync source becomes invalid. Similarly, if the primary changes and chaining is disabled, the node will update to sync from the new primary.
oplogFetcherUsesExhaustNew in version 4.4.4.4版新增。Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: trueEnables or disables streaming replication. Set the value to
trueto enable streaming replication.Set the value to
falseto disable streaming replication. If disabled, secondaries fetch batches of oplog entries by issuing a request to their sync from source and waiting for a response. This requires a network roundtrip for each batch of oplog entries.You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.
oplogInitialFindMaxSeconds-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 60Maximum time in seconds for a member of a replica set to wait for the
findcommand to finish during data synchronization.
replWriterThreadCount-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 16Maximum number of threads to use to apply replicated operations in parallel. Values can range from 1 to 256 inclusive. However, the maximum number of threads used is capped at twice the number of available cores.
You can only set
replWriterThreadCountat startup and cannot change this setting with thesetParametercommand.TipSee also:另请参阅:
replWriterMinThreadCountNew in version 5.0.5.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 0Minimum number of threads to use to apply replicated operations in parallel. Values can range from 0 to 256 inclusive. You can only set
replWriterMinThreadCountat startup and cannot change this setting with thesetParametercommand.Parallel application of replication operations uses up to
replWriterThreadCountthreads. IfreplWriterMinThreadCountis configured with a value less thanreplWriterThreadCount, the thread pool will timeout idle threads until the total count of threads in the thread pool is equal toreplWriterMinThreadCount.replWriterMinThreadCountmust be configured with a value that is less than or equal toreplWriterThreadCount.
rollbackTimeLimitSecs-
Type类型: 64-bit integerDefault默认值: 86400 (1 day)Maximum age of data that can be rolled back. Negative values for this parameter are not valid.
If the time between the end of the to-be-rolledback instance's oplog and the first operation after the common point (the last point where the source node and the to-be-rolledback node had the same data) exceeds this value, the rollback will fail.
To effectively have an unlimited rollback period, set the value to
2147483647which is the maximum value allowed and equivalent to roughly 68 years.
waitForSecondaryBeforeNoopWriteMS-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 10The length of time (in milliseconds) that a secondary must wait if the
afterClusterTimeis greater than the last applied time from the oplog. After thewaitForSecondaryBeforeNoopWriteMSpasses, if theafterClusterTimeis still greater than the last applied time, the secondary makes a no-op write to advance the last applied time.The following example sets the
waitForSecondaryBeforeNoopWriteMSto 20 milliseconds:mongod --setParameter waitForSecondaryBeforeNoopWriteMS=20
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, waitForSecondaryBeforeNoopWriteMS: 20 } )
createRollbackDataFiles-
Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: trueFlag that determines whether MongoDB creates rollback files that contains documents affected during a rollback.
By default,
createRollbackDataFilesistrueand MongoDB creates the rollback files.The following example sets
createRollbackDataFilesto false so that the rollback files are not created:mongod --setParameter createRollbackDataFiles=falseDuring run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, createRollbackDataFiles: false } )For more information, see Collect Rollback Data.
replBatchLimitBytes-
Default默认值: 104857600 (100MB)Sets the maximum oplog application batch size in bytes.
Values can range from 16777216 (16MB) to 104857600 (100MB) inclusive.
The following example sets
replBatchLimitBytesto 64 MB to limit the oplog application batch size:mongod --setParameter replBatchLimitBytes=67108864During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, replBatchLimitBytes: 64 * 1024 * 1024 } )
mirrorReadsNew in version 4.4.4.4版新增。Available for仅适用于mongodonly.mongod。Type类型: DocumentDefault默认值:{ samplingRate: 0.01, maxTimeMS: 1000 }Specifies the settings for mirrored reads for the
mongodinstance. The settings only take effect when the member is a primary.The parameter
mirrorReadstakes a JSON document with the following fields:Field字段Description描述samplingRateThe sampling rate used to mirror a subset of operations that support mirroring to a subset of electable (specifically, priority greater than 0) secondaries. That is, the primary mirrors reads to each electable secondary at the specified sampling rate.
Valid values are:0.0Turns off mirroring. 1.0The primary mirrors all operations that supports mirroring to each electable secondary. Number between 0.0and1.0(exclusive)The primary randomly samples each electable secondary at the specified rate to be sent mirrored reads. For example, given a replica set with a primary and two electable secondaries and a sampling rate of
0.10, the primary mirrors reads to each electable secondary at the sampling rate of 10 percent such that one read may be mirrored to one secondary and not to the other or to both or to neither. That is, if the primary receives100operations that can be mirrored, the sampling rate of0.10may result in8reads being mirrored to one secondary and13reads to the other or10to each, etc.The default value is
0.01.maxTimeMSThe maximum time in milliseconds for the mirrored reads. The default value is 1000.
ThemaxTimeMSfor the mirrored reads is separate from themaxTimeMSof the original read being mirrored.You can set
mirrorReadsduring startup in theconfiguration fileor with the--setParameteroption on the command line. If specifying from the configuration file or on the command line, enclose themirrorReadsdocument in quotes.For example, the following sets the mirror reads sampling rate to
0.10from the command line:mongod --setParameter mirrorReads='{ samplingRate: 0.10 }'Or, to specify in a configuration file:
setParameter:
mirrorReads: '{samplingRate: 0.10}'Or if using the
setParametercommand in amongoshsession that is connected to a runningmongod, do not enclose the document in quotes:db.adminCommand( { setParameter: 1, mirrorReads: { samplingRate: 0.10 } } )
allowMultipleArbitersNew in version 5.3.5.3版新增。Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: falseSpecifies whether the replica set allows the use of multiple arbiters.
The use of multiple arbiters is not recommended:
- Multiple arbiters prevent the reliable use of the majority write concern. MongoDB counts arbiters in calculating a membership majority, but arbiters do not store data. With the inclusion of multiple arbiters, it's possible for a majority write operation to return success before the write replicates to a majority of data bearing nodes.
- Multiple arbiters allow replica sets to accept writes even when the replica set doesn't have sufficient secondaries for data replication.
For more information, see Concerns with Multiple Arbiters.
The parameter can only be set during startup:
mongod --setParameter allowMultipleArbiters=true
Sharding Parameters
Starting in version 4.2, MongoDB removes the parameter AsyncRequestsSenderUseBaton and always enables the performance enhancement controlled by the parameter.
analyzeShardKeyCharacteristicsDefaultSampleSizeNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 10000000If
sampleRateandsampleSizeare not set when you runanalyzeShardKey, specifies the number of documents to sample when calculating shard key characteristics metrics. Must be greater than0.This example sets
analyzeShardKeyCharacteristicsDefaultSampleSizeto10000at startup:mongod --setParameter analyzeShardKeyCharacteristicsDefaultSampleSize=10000
During run time, you can set or modify the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, analyzeShardKeyCharacteristicsDefaultSampleSize: 10000 } )
analyzeShardKeyNumMostCommonValuesNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 5Specifies the number of most common shard key values to return. If the collection contains fewer unique shard keys than this value,
analyzeShardKeyNumMostCommonValuesreturns that number of most common values. Must be greater than0and less than or equal to1000.This example sets
analyzeShardKeyNumMostCommonValuesto3at startup:mongod --setParameter analyzeShardKeyNumMostCommonValues=3
During run time, you can set or modify the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, analyzeShardKeyNumMostCommonValues: 3 } )
analyzeShardKeyNumRangesNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 100Specifies the number of ranges to partition the shard key space into when calculating the hotness of shard key ranges. Must be greater than
0and less than or equal to10000.This example sets
analyzeShardKeyNumRangesto50at startup:mongod --setParameter analyzeShardKeyNumRanges=50
During run time, you can set or modify the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, analyzeShardKeyNumRanges: 50 } )
analyzeShardKeyMonotonicityCorrelationCoefficientThresholdNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: doubleDefault默认值: 0.7Specifies the
RecordIdcorrelation coefficient threshold used to determine if a shard key is monotonically changing in insertion order. Must be greater than0and less than or equal to1.This example sets
analyzeShardKeyMonotonicityCorrelationCoefficientThresholdto1at startup:mongod --setParameter analyzeShardKeyMonotonicityCorrelationCoefficientThreshold=1
During run time, you can set or modify the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, analyzeShardKeyMonotonicityCorrelationCoefficientThreshold: 1 } )
autoMergerIntervalSecsNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 3600When AutoMerger is enabled, specifies the amount of time between automerging rounds, in seconds. The default value is 3600 seconds, or one hour.
autoMergerIntervalSecscan only be set on config servers.This example sets
autoMergerIntervalSecsto 7200 milliseconds, or two hours, at startup:mongod --setParameter autoMergeInterval=7200
During run time, you can set or modify the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, autoMergeInterval: 7200 } )
autoMergerThrottlingMSNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 15000When AutoMerger is enabled, specifies the minimum amount time between merges initiated by the AutoMerger on the same collection, in milliseconds.
autoMergerThrottlingMScan only be set on config servers.This example sets
autoMergerThrottlingMSto 60000 milliseconds, or one minute, at startup:mongod --setParameter autoMergerThrottlingMS=60000
During run time, you can set or modify the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, autoMergerThrottlingMS: 60000 } )
balancerMigrationsThrottlingMsNew in version 7.0:7.0版新增:(Also available starting in 6.3.1, 6.0.6, 5.0.18)Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 1000Specifies the minimum amount of time between two consecutive balancing rounds. This allows you to throttle the balancing rate. This parameter only takes effect on config server nodes.
This example sets
balancerMigrationsThrottlingMsto 2000 milliseconds at startup:mongod --setParameter balancerMigrationsThrottlingMs=2000
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, balancerMigrationsThrottlingMs: 2000 } )
chunkDefragmentationThrottlingMSNew in version 5.3.5.3版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 0Specifies the minimum time period (in milliseconds) between consecutive split and merge commands run by the balancer when the chunks in a sharded collection are defragmented.
chunkDefragmentationThrottlingMSlimits the rate of split and merge commands.The following example sets
chunkDefragmentationThrottlingMSto10milliseconds:mongod --setParameter chunkDefragmentationThrottlingMS=10
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, chunkDefragmentationThrottlingMS: 10 } )
chunkMigrationConcurrency-
Available starting in MongoDB 7.0, 6.3, 6.0.6 (and 5.0.15).
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 1Specifies an integer that sets the number of threads on the source shard and the receiving shard for chunk migration. Chunk migrations use the number of threads that you set on the receiving shard for both the source and receiving shard.
Increasing the concurrency improves chunk migration performance, but also increases the workload and disk IOPS usage on the source shard and the receiving shard.
Maximum value is 500.
You should typically use half the total number of CPU cores as threads. For example, if the total is 16 cores, set
chunkMigrationConcurrencyto 8 threads (or fewer).If
chunkMigrationConcurrencyis greater than1, the_secondaryThrottleconfiguration setting is ignored. The_secondaryThrottlesetting determines when the chunk migration proceeds with the next document in the chunk. For details, see Range Migration and Replication.The following example sets
chunkMigrationConcurrencyto5:mongod --setParameter chunkMigrationConcurrency=5
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, chunkMigrationConcurrency: 5 } )
To configure collection balancing, see
configureCollectionBalancing.To learn about defragmenting sharded collections, see Defragment Sharded Collections.
disableResumableRangeDeleterNew in version 4.4.4.4版新增。Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: falseIf set on a shard's primary, specifies if range deletion is paused on the shard. If set to
true, cleanup of ranges containing orphaned documents is paused. The shard can continue to donate chunks to other shards, but the donated documents will not be removed from this shard until you set this parameter tofalse. This shard can continue to receive chunks from other shards as long as it does not have a pending range deletion task in theconfig.rangeDeletionscollection that overlaps with the incoming chunk's range.When
disableResumableRangeDeleteristrue, chunk migrations fail if orphaned documents exist on the recipient shard's primary in the same range as the incoming chunks.The parameter has no effect on the
mongodif it is not the shard's primary.ImportantIf you set
disableResumableRangeDeleterparameter totrue, ensure that you apply it consistently for all members in the shard's replica set. In the event of a failover, this setting's value on the new primary dictates the behavior of the range deleter.You can only set this parameter during start-up and cannot change this setting using the
setParameterdatabase command.mongod --setParameter disableResumableRangeDeleter=false
enableShardedIndexConsistencyCheckNew in version 4.4:4.4版新增:(Also available starting in 4.2.6.)Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: trueIf set on the config server's primary, enables or disables the index consistency check for sharded collections. The parameter has no effect on the
mongodif it is not the config server's primary.The following example sets
enableShardedIndexConsistencyChecktofalsefor a config server primary:mongod --setParameter enableShardedIndexConsistencyCheck=falseDuring run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, enableShardedIndexConsistencyCheck: false } )TipSee also:另请参阅:shardedIndexConsistencyCheckIntervalMSparametershardedIndexConsistencymetrics returned by theserverStatuscommand.
opportunisticSecondaryTargetingNew in version 6.1.0.6.1.0版新增。Available for
mongosonly.Type类型: booleanDefault默认值:falseDetermines whether
mongosperforms opportunistic reads against replica sets.When this parameter is set to
true,mongosdirects secondary reads to secondaries with active connections. It sends the request to the first secondary that accepts the connection. When this parameter is set tofalse,mongosholds secondary reads until it can establish a connection to a specific secondary, (except in the case of hedged reads).NoteFor example, to set
opportunisticSecondaryTargetingduring startup:mongos --setParameter opportunisticSecondaryTargeting=true
shardedIndexConsistencyCheckIntervalMSNew in version 4.4:4.4版新增:(Also available starting in 4.2.6.)Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 600000If set on the config server's primary, the interval, in milliseconds, at which the config server's primary checks the index consistency of sharded collections. The parameter has no effect on the
mongodif it is not the config server's primary.You can only set the parameter during startup, and cannot change this setting using the
setParameterdatabase command.For example, the following sets the interval at 300000 milliseconds (5 minutes) at startup:
mongod --setParameter shardedIndexConsistencyCheckIntervalMS=300000TipSee also:另请参阅:enableShardedIndexConsistencyCheckparametershardedIndexConsistencymetrics returned by theserverStatuscommandq
enableFinerGrainedCatalogCacheRefreshNew in version 4.4.4.4版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: trueThis parameter allows the catalog cache to be refreshed only if the shard needs to be refreshed. If disabled, any stale chunk will cause the entire chunk distribution for a collection to be considered stale and force all routers who contact the shard to refresh their shard catalog cache.
You can only set this parameter during start-up and cannot change this setting using the
setParameterdatabase command.mongod --setParameter enableFinerGrainedCatalogCacheRefresh=true
mongos --setParameter enableFinerGrainedCatalogCacheRefresh=trueTipSee also:另请参阅:
maxTimeMSForHedgedReadsNew in version 4.4.4.4版新增。Available for
mongosonly.Type类型: integerDefault默认值: 150Specifies the maximum time limit (in milliseconds) for the hedged read. That is, the additional read sent to hedge the read operation uses the
maxTimeMSvalue ofmaxTimeMSForHedgedReadswhile the read operation that is being hedged uses themaxTimeMSvalue specified for the operation.For example, to set the limit to 200 milliseconds, you can issue the following during startup:
mongos --setParameter maxTimeMSForHedgedReads=200
Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand( { setParameter: 1, maxTimeMSForHedgedReads: 200 } )
TipSee also:另请参阅:
maxCatchUpPercentageBeforeBlockingWritesNew in version 5.0:5.0版新增:(Also available starting in 4.4.7, 4.2.15)Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 10For
moveChunkandmoveRangeoperations, specifies the maximum percentage of untrasferred data allowed by the migration protocol (expressed in percentage of the total chunk size) to transition from thecatchupphase to thecommitphase.Setting a higher catchup percentage can decrease the amount of time it takes for the migration to complete at the cost of increased latency during concurrent
upsertanddeleteoperations.For example, to set the maximum percentage to 20, you can issue the following during startup:
mongod --setParameter maxCatchUpPercentageBeforeBlockingWrites=20
You cannot change
maxCatchUpPercentageBeforeBlockingWritesduring run time.TipSee also:另请参阅:
metadataRefreshInTransactionMaxWaitBehindCritSecMSNew in version 5.2:5.2版新增:(Also available starting in 5.1.0, 5.0.4)Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 500Limits the time a shard waits for a critical section within a transaction.
When a query accesses a shard, a chunk migration or DDL operation may already hold the critical section for the collection. If the query finds the critical section is taken, the shard waits until the critical section has been released. When the shard returns control to
mongos,mongosretries the query. However, if a multi-shard transaction interacts with an operation that takes the critical section on multiple shards, the interaction can result in a distributed deadlock.metadataRefreshInTransactionMaxWaitBehindCritSecMSlimits the maximum time a shard waits within a transaction for the critical section to be released.To reduce the maximum wait time for the critical section within a transaction, lower the value of
metadataRefreshInTransactionMaxWaitBehindCritSecMS.WarningIf
metadataRefreshInTransactionMaxWaitBehindCritSecMSis too low,mongoscould use all of its retry attempts and return an error.You can set
metadataRefreshInTransactionMaxWaitBehindCritSecMSat startup and during run time.For example, to set
metadataRefreshInTransactionMaxWaitBehindCritSecMSto 400 milliseconds:db.adminCommand( { setParameter: 1, metadataRefreshInTransactionMaxWaitBehindCritSecMS: 400 } )
queryAnalysisSamplerConfigurationRefreshSecsNew in version 7.0.7.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: integerDefault默认值: 10Interval that a sampler (
mongosormongod) refreshes its query analyzer sample rates.The sample rate configured by the
configureQueryAnalyzercommand is divided amongmongosinstances in the sharded cluster ormongodinstances in the replica set based on the traffic going through them. To make the sample rate assignment for amongosormongodmore responsive to the traffic going through it, decrease this value.We recommend using the default value.
This example sets
queryAnalysisSamplerConfigurationRefreshSecsto 60 seconds at startup on amongodinstance:mongod --setParameter queryAnalysisSamplerConfigurationRefreshSecs=60
This example sets
queryAnalysisSamplerConfigurationRefreshSecsto 60 seconds at startup on amongosinstance:mongos --setParameter queryAnalysisSamplerConfigurationRefreshSecs=60
queryAnalysisSamplerConfigurationRefreshSecsmay only be set at startup.
queryAnalysisWriterIntervalSecsNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 90Interval that sampled queries are written to disk, in seconds.
This example sets
queryAnalysisWriterIntervalSecsto 60 seconds at startup on amongodinstance:mongod --setParameter queryAnalysisWriterIntervalSecs=60
queryAnalysisWriterIntervalSecsmay only be set at startup.
queryAnalysisWriterMaxMemoryUsageBytesNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 100 * 1024 * 1024Maximum amount of memory in bytes that the query sampling writer is allowed to use. Once the limit is reached, all new queries and diffs are discarded from sampling until the buffer is flushed. Must be greater than
0.This example sets
queryAnalysisWriterMaxMemoryUsageBytesto10000000at startup on amongodinstance:mongod --setParameter queryAnalysisWriterMaxMemoryUsageBytes=10000000
queryAnalysisWriterMaxBatchSizeNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 100000Maximum number of sampled queries to write to disk at once. Must be greater than
0and less than or equal to100000.This example sets
queryAnalysisWriterMaxBatchSizeto1000at startup on amongodinstance:mongod --setParameter queryAnalysisWriterMaxBatchSize=1000
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, queryAnalysisWriterMaxBatchSize: 1000 } )
queryAnalysisSampleExpirationSecsNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 7 * 24 * 3600Amount of time that a sampled query document exists before being removed by the TTL monitor, in seconds. Must be greater than
0.This example sets
queryAnalysisSampleExpirationSecsto691200(8 * 24 * 3600) at startup on amongodinstance:mongod --setParameter queryAnalysisSampleExpirationSecs=691200
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, queryAnalysisSampleExpirationSecs: 691200 } )
readHedgingModeNew in version 4.4.4.4版新增。Available for
mongosonly.Type类型: stringDefault默认值: onSpecifies whether
mongossupports hedged reads for those read operations whose read preference have enabled the hedged read option.Available values are:
Value值Description描述onThe mongosinstance supports hedged reads for read operations whose read preference have enabled the hedged read option.offThe mongosinstance does not support hedged reads. That is, hedged reads are unavailable, even for read operations whose read preference have enabled the hedged read option.For example, to turn off hedged read support for a
mongosinstance, you can issue the following during startup:mongos --setParameter readHedgingMode=off
Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand( { setParameter: 1, readHedgingMode: "off" } )
TipSee also:另请参阅:
shutdownTimeoutMillisForSignaledShutdownNew in version 5.0.5.0版新增。Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 15000Specifies the time (in milliseconds) to wait for any ongoing database operations to complete before initiating a shutdown of
mongodin response to aSIGTERMsignal.For example, to set the time to 250 milliseconds, you can issue the following during startup:
mongod --setParameter shutdownTimeoutMillisForSignaledShutdown=250
Or if using the
setParametercommand in amongoshsession that is connected to a runningmongod:db.adminCommand( { setParameter: 1, shutdownTimeoutMillisForSignaledShutdown: 250 } )
mongosShutdownTimeoutMillisForSignaledShutdownNew in version 5.0.5.0版新增。Available for
mongosonly.Type类型: integerDefault默认值: 15000Specifies the time (in milliseconds) to wait for any ongoing database operations to complete before initiating a shutdown of
mongosin response to aSIGTERMsignal.For example, to set the time to 250 milliseconds, you can issue the following during startup:
mongos --setParameter mongosShutdownTimeoutMillisForSignaledShutdown=250
Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand( { setParameter: 1, mongosShutdownTimeoutMillisForSignaledShutdown: 250 } )
ShardingTaskExecutorPoolHostTimeoutMS-
Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: 300000 (5 minutes)
Maximum time that
mongosgoes without communication to a host beforemongosdrops all connections to the host.If set,
ShardingTaskExecutorPoolHostTimeoutMSshould be greater than the sum ofShardingTaskExecutorPoolRefreshRequirementMSandShardingTaskExecutorPoolRefreshTimeoutMS. Otherwise,mongosadjusts the value ofShardingTaskExecutorPoolHostTimeoutMSto be greater than the sum.The following example sets
ShardingTaskExecutorPoolHostTimeoutMSto120000during startup:mongos --setParameter ShardingTaskExecutorPoolHostTimeoutMS=120000
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolHostTimeoutMS: 120000 } )
ShardingTaskExecutorPoolMaxConnecting-
Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: 2
Maximum number of simultaneous initiating connections (including pending connections in setup/refresh state) each TaskExecutor connection pool can have to a
mongodinstance. You can set this parameter to control the rate at whichmongosadds connections to amongodinstance.If set,
ShardingTaskExecutorPoolMaxConnectingshould be less than or equal toShardingTaskExecutorPoolMaxSize. If it is greater,mongosignores theShardingTaskExecutorPoolMaxConnectingvalue.The following example sets
ShardingTaskExecutorPoolMaxConnectingto20during startup:mongos --setParameter ShardingTaskExecutorPoolMaxConnecting=20
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolMaxConnecting: 20 } )
ShardingTaskExecutorPoolMaxSize-
Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: 2 64 - 1
Maximum number of outbound connections each TaskExecutor connection pool can open to any given
mongodinstance. The maximum possible connections to any given host across all TaskExecutor pools is:ShardingTaskExecutorPoolMaxSize * taskExecutorPoolSize
The following example sets
ShardingTaskExecutorPoolMaxSizeto20during startup:mongos --setParameter ShardingTaskExecutorPoolMaxSize=20
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolMaxSize: 20 } )
mongoscan have up tonTaskExecutor connection pools, wherenis the number of cores. SeetaskExecutorPoolSize.TipSee also:另请参阅:
ShardingTaskExecutorPoolMaxSizeForConfigServersNew in version 6.0.6.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: -1
Optional override for
ShardingTaskExecutorPoolMaxSizeto set the maximum number of outbound connections each TaskExecutor connection pool can open to a configuration server.When set to:
-1,ShardingTaskExecutorPoolMaxSizeis used. This is the default.- an integer value greater than
-1, overrides the maximum number of outbound connections each TaskExecutor connection pool can open to a configuration server.
Parameter only applies to sharded deployments.
The following example sets
ShardingTaskExecutorPoolMaxSizeto2during startup, which sets the maximum number of outbound connections each TaskExecutor connection pool can open to a configuration server to2:mongos --setParameter ShardingTaskExecutorPoolMaxSizeForConfigServers=2
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolMaxSizeForConfigServers: 2 } )
ShardingTaskExecutorPoolMinSize-
Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: 1
Minimum number of outbound connections each TaskExecutor connection pool can open to any given
mongodinstance.ShardingTaskExecutorPoolMinSizeconnections are created the first time a connection to a new host is requested from the pool. While the pool is idle, the pool maintains this number of connections untilShardingTaskExecutorPoolHostTimeoutMSmilliseconds pass without any application using that pool.For a
mongosusing thewarmMinConnectionsInShardingTaskExecutorPoolOnStartupparameter, theShardingTaskExecutorPoolMinSizeparameter also controls how many connections to each shard host are established on startup of themongosinstance before it begins accepting incoming client connections.NoteIn MongoDB 4.4, the
warmMinConnectionsInShardingTaskExecutorPoolOnStartupparameter is enabled by default for themongos.The following example sets
ShardingTaskExecutorPoolMinSizeto2during startup:mongos --setParameter ShardingTaskExecutorPoolMinSize=2
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolMinSize: 2 } )
mongoscan have up tonTaskExecutor connection pools, wherenis the number of cores. SeetaskExecutorPoolSize.Tip
ShardingTaskExecutorPoolMinSizeForConfigServersNew in version 6.0.6.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: -1
Optional override for
ShardingTaskExecutorPoolMinSizeto set the minimum number of outbound connections each TaskExecutor connection pool can open to a configuration server.When set to:
-1,ShardingTaskExecutorPoolMinSizeis used. This is the default.- an integer value greater than
-1, overrides the minimum number of outbound connections each TaskExecutor connection pool can open to a configuration server.
Parameter only applies to sharded deployments.
The following example sets
ShardingTaskExecutorPoolMinSizeto2during startup, which sets the minimum number of outbound connections each TaskExecutor connection pool can open to a configuration server to2:mongos --setParameter ShardingTaskExecutorPoolMinSizeForConfigServers=2
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolMinSizeForConfigServers: 2 } )
ShardingTaskExecutorPoolRefreshRequirementMS-
Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: 60000 (1 minute)
Maximum time the
mongoswaits before attempting to heartbeat a resting connection in the pool. An idle connection may be discarded during the refresh if the pool is above its minimum size.If set,
ShardingTaskExecutorPoolRefreshRequirementMSshould be greater thanShardingTaskExecutorPoolRefreshTimeoutMS. Otherwise,mongosadjusts the value ofShardingTaskExecutorPoolRefreshTimeoutMSto be less thanShardingTaskExecutorPoolRefreshRequirementMS.The following example sets
ShardingTaskExecutorPoolRefreshRequirementMSto90000during startup:mongos --setParameter ShardingTaskExecutorPoolRefreshRequirementMS=90000
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolRefreshRequirementMS: 90000 } )
ShardingTaskExecutorPoolRefreshTimeoutMS-
Available for both可用于mongodandmongos.mongod和mongos。Type: integer
Default: 20000 (20 seconds)
Maximum time the
mongoswaits for a heartbeat before timing out the heartbeat.If set,
ShardingTaskExecutorPoolRefreshTimeoutMSshould be less thanShardingTaskExecutorPoolRefreshRequirementMS. Otherwise,mongosadjusts the value ofShardingTaskExecutorPoolRefreshTimeoutMSto be less thanShardingTaskExecutorPoolRefreshRequirementMS.The following example sets
ShardingTaskExecutorPoolRefreshTimeoutMSto30000during startup:mongos --setParameter ShardingTaskExecutorPoolRefreshTimeoutMS=30000
During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolRefreshTimeoutMS: 30000 } )
ShardingTaskExecutorPoolReplicaSetMatchingNew in version 4.2.4.2版新增。Changed in version 5.0.5.0版更改。(Also starting in 4.4.5 and 4.2.13)Available for both可用于mongodandmongos.mongod和mongos。Type: string
Default: "automatic"
On a
mongosinstance, this parameter sets the policy that determines the minimum size limit of its connection pools to nodes within replica sets.On a
mongodinstance, this parameter sets the policy that determines the minimum size limit of its connection pools to nodes within other replica sets.Note that this parameter only manages connections for operations that are directly related to user requests and CRUD operations.
Available values are:
Matching Policy Description描述"automatic"(Default)Starting in 5.0 (and 4.4.5 and 4.2.13), "automatic"is the new default value.
When set for amongos, the instance follows the behavior specified for the"matchPrimaryNode"option.
When set for amongod, the instance follows the behavior specified for the"disabled"option.NoteIf theShardingTaskExecutorPoolReplicaSetMatchingis set to"automatic", thereplicaSetMatchingStrategystill describes the actual policy being used, not"automatic". To find the value of theShardingTaskExecutorPoolReplicaSetMatching, usegetParameterwhich returns the value of the server parameter."matchPrimaryNode"When set for a mongos, the minimum size limit of the instance's connection pool to each secondary of a replica set in the sharded cluster (specifically, shard replica set and config servers) is equal to the size of its connection pool to that replica set's primary.
When set for amongod, the minimum size limit of the instance's connection pool to each secondary of another replica set in the sharded cluster (specifically, shard replica set and config servers) is equal to the size of its connection pool to that replica set's primary.In case of a primary stepdown,WarningIf multiple shard servers in your topology can experience a rapid influx of cross-shard operations, do not set this option on yourmongodinstances.matchPrimaryNodeensures that any secondary that becomes the primary can handle the current level of primary reads and writes."matchBusiestNode"When set for a mongos, the instance's minimum size limit of the connection pool to each member of a replica set in the sharded cluster (specifically, shard replica set and config servers) is equal to the largest among the active connection counts to the primary and each secondary member of that replica set.
When set for amongod, the instance's minimum size limit of the connection pool to each member of another replica set in the sharded cluster (specifically, shard replica set and config servers) is equal to the largest among the active connection counts to the primary and each secondary member of that replica set.
With"matchBusiestNode",mongosmaintains enough connections to each secondary to handle the current level of primary and secondary reads and writes. The number of connections to maintain in the pool decreases as the number of active connections decreases."disabled"When set for a mongos, the instance's minimum number of connections in the instance's connection pool to each node of a replica set in the sharded clusterv (specifically, shard replica set and config servers) is equal to theShardingTaskExecutorPoolMinSize.
When set for amongod, the instance's minimum number of connections in the instance's connection pool to each node of another replica set in the sharded cluster (specifically, shard replica set and config servers) is equal to theShardingTaskExecutorPoolMinSize.The following example sets the
ShardingTaskExecutorPoolReplicaSetMatchingto"automatic"during startup:mongod --setParameter ShardingTaskExecutorPoolReplicaSetMatching="automatic"During run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, ShardingTaskExecutorPoolReplicaSetMatching: "automatic" } )
taskExecutorPoolSize-
Available for
mongosonly.Type: integer
Default: 1
The number of Task Executor connection pools to use for a given
mongos.If the parameter value is
0or less, the number of Task Executor connection pools is the number of cores with the following exceptions:- If the number of cores is less than 4, the number of Task Executor connection pools is 4.
- If the number of cores is greater than 64, the number of Task Executor connection pools is 64.
When running MongoDB 6.2 or newer on Linux, you cannot modify the
taskExecutorPoolSizefrom the default value of1. You may modify this parameter when running MongoDB on Windows or macOS.The default value of
taskExecutorPoolSizeis1: In MongoDB 4.2+ deployments, MongoDB removes theAsyncRequestsSenderUseBatonparameter and always enables the performance enhancement controlled by the parameter.You can only set this parameter during start-up and cannot change this setting using the
setParameterdatabase command.mongos --setParameter taskExecutorPoolSize=6
TipSee also:另请参阅:
loadRoutingTableOnStartupNew in version 4.4.4.4版新增。Available for
mongosonly.Type: boolean
Default默认值: trueConfigures a
mongosinstance to preload the routing table for a sharded cluster on startup. With this setting enabled, themongoscaches the cluster-wide routing table for each sharded collection as part of its startup procedure, before it begins accepting client connections.Without this setting enabled, the
mongosonly loads a routing table as needed for incoming client connections, and only loads the specific routing table for the namespace of a given request.A
mongosinstance with theloadRoutingTableOnStartupparameter enabled may experience longer startup times, but will result in faster servicing of initial client connections once started.loadRoutingTableOnStartupis enabled by default.You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.
warmMinConnectionsInShardingTaskExecutorPoolOnStartupNew in version 4.4.4.4版新增。Available for
mongosonly.Type: boolean
Default默认值: trueConfigures a
mongosinstance to prewarm its connection pool on startup. With this parameter enabled, themongosattempts to establishShardingTaskExecutorPoolMinSizenetwork connections to each shard server as part of its startup procedure, before it begins accepting client connections.A timeout for this behavior can be configured with the
warmMinConnectionsInShardingTaskExecutorPoolOnStartupWaitMSparameter. If this timeout is reached, themongoswill begin accepting client connections regardless of the size of its connection pool.A
mongosinstance with this parameter enabled may experience longer startup times, but will result in faster servicing of initial client connections once started.warmMinConnectionsInShardingTaskExecutorPoolOnStartupis enabled by default.You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.
warmMinConnectionsInShardingTaskExecutorPoolOnStartupWaitMSNew in version 4.4.4.4版新增。Available for
mongosonly.Type: integer
Default默认值: 2000 (2 seconds)Sets the timeout threshold in milliseconds for a
mongosto wait forShardingTaskExecutorPoolMinSizeconnections to be established per shard host when using thewarmMinConnectionsInShardingTaskExecutorPoolOnStartupparameter. If this timeout is reached, themongoswill begin accepting client connections regardless of the size of its connection pool.You can only set this parameter on startup, using either the
setParameterconfiguration file setting or the--setParametercommand line option.Tip
migrateCloneInsertionBatchDelayMS-
Available for仅适用于mongodonly.mongod。Type: Non-negative integer
Default: 0
Time in milliseconds to wait between batches of insertions during cloning step of the migration process. This wait is in addition to the
secondaryThrottle.The default value of
0indicates no additional wait.The following sets the
migrateCloneInsertionBatchDelayMSto 200 milliseconds:mongod --setParameter migrateCloneInsertionBatchDelayMS=200
The parameter may also be set using the
setParametercommand:db.adminCommand( { setParameter: 1, migrateCloneInsertionBatchDelayMS: 200 } )
migrateCloneInsertionBatchSize-
Available for仅适用于mongodonly.mongod。Type: Non-negative integer
Default: 0
The maximum number of documents to insert in a single batch during the cloning step of the migration process.
The default value of
0indicates no maximum number of documents per batch. However, in practice, this results in batches that contain up to 16 MB of documents.The following sets the
migrateCloneInsertionBatchSizeto 100 documents:mongod --setParameter migrateCloneInsertionBatchSize=100
The parameter may also be set using the
setParametercommand:db.adminCommand( { setParameter: 1, migrateCloneInsertionBatchSize: 100 } )
orphanCleanupDelaySecs-
Available for仅适用于mongodonly.mongod。Default: 900 (15 minutes)
Minimum delay before a migrated chunk is deleted from the source shard.
Before deleting the chunk during chunk migration, MongoDB waits for
orphanCleanupDelaySecsor for in-progress queries involving the chunk to complete on the shard primary, whichever is longer.However, because the shard primary has no knowledge of in-progress queries run on the shard secondaries, queries that use the chunk but are run on secondaries may see documents disappear if these queries take longer than the time to complete the shard primary queries and the
orphanCleanupDelaySecs.NoteThis behavior only affects in-progress queries that start before the chunk migration. Queries that start after the chunk migration starts will not use the migrating chunk.
If a shard has storage constraints, consider reducing this value temporarily. If running queries that exceed 15 minutes on shard secondaries, consider increasing this value.
The following sets the
orphanCleanupDelaySecsto 20 minutes:mongod --setParameter orphanCleanupDelaySecs=1200
This may also be set using the
setParametercommand:db.adminCommand( { setParameter: 1, orphanCleanupDelaySecs: 1200 } )
TipIn all versions, the new value of
orphanCleanupDelaySecsis only applied to range deletions created after the value is changed. To apply the new value to existing range deletions, force a step down.
rangeDeleterBatchDelayMS-
Available for仅适用于mongodonly.mongod。Type: Non-negative integer
Default: 20
The amount of time in milliseconds to wait before the next batch of deletion during the cleanup stage of range migration (or the
cleanupOrphanedcommand).The _secondaryThrottle replication delay occurs after each batch deletion.
The following sets the
rangeDeleterBatchDelayMSto 200 milliseconds:mongod --setParameter rangeDeleterBatchDelayMS=200
The parameter may also be set using the
setParametercommand:db.adminCommand( { setParameter: 1, rangeDeleterBatchDelayMS: 200 } )
TipIn versions prior to 6.0.3, the new value of
rangeDeleterBatchDelayMSis only applied to range deletions created after the value is changed. To apply the new value to existing range deletions, force a step down.From 6.0.3 on, the new value of the parameter is applied to all the range deletions processed after the update, regardless of when the range deletion was created.
rangeDeleterBatchSize-
Available for仅适用于mongodonly.mongod。Type: Non-negative integer
Default: 2147483647 starting in MongoDB 5.1.2, 5.0.6, and 4.4.12 (128 in earlier MongoDB versions)
The maximum number of documents in each batch to delete during the cleanup stage of range migration (or the
cleanupOrphanedcommand).A value of
0indicates that the system chooses the default value.The following example sets
rangeDeleterBatchSizeto 32 documents:mongod --setParameter rangeDeleterBatchSize=32
The parameter may also be set using the
setParametercommand:db.adminCommand( { setParameter: 1, rangeDeleterBatchSize: 32 } )
TipIn versions prior to 6.0.3, the new value of
rangeDeleterBatchSizeis only applied to range deletions created after the value is changed. To apply the new value to existing range deletions, force a step down.From 6.0.3 on, the new value of the parameter is applied to all the range deletions processed after the update, regardless of when the range deletion was created.
rangeDeleterHighPriorityNew in version 7.0.7.0版新增。Available for仅适用于mongodonly.mongod。Type: boolean
Default: false
When
true, prioritizes cleanup of orphaned documents over user operations. By default, this is set tofalseto prioritize user operations over cleanup of orphaned documents.The following example sets
rangeDeleterHighPrioritytotrue:mongod --setParameter rangeDeleterHighPriority=trueThe parameter may also be set using the
setParametercommand:db.adminCommand( { setParameter: 1, rangeDeleterBatchSize: true } )
skipShardingConfigurationChecks-
Available for仅适用于mongodonly.mongod。Type: boolean
Default: false
When
true, allows for starting a shard member or config server member as a standalone for maintenance operations. This parameter is mutually exclusive with the--configsvror--shardsvroptions.You can only set this parameter during start-up and cannot change this setting using the
setParameterdatabase command.mongod --setParameter skipShardingConfigurationChecks=trueImportantOnce maintenance has completed, remove the
skipShardingConfigurationChecksparameter when restarting themongod.
findChunksOnConfigTimeoutMSNew in version 5.0.5.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type: Non-negative integer
Default: 900000
The timeout in milliseconds for find operations on
chunks.If there is a large number of chunks in the cluster and chunk loading fails with the error
ExceededTimeLimit, increase the parameter value:mongod --setParameter findChunksOnConfigTimeoutMS=1000000
Health Manager Parameters
activeFaultDurationSecs-
Available for
mongosonly.Type类型: DocumentThe amount of time to wait from a Health Managers Overview failure until the mongos is removed from the cluster, in seconds.
When a failure is detected and a Health Manager is configured as
critical, the server waits for the specified interval before removing themongosfrom the cluster.For example, to set the duration from failure to crash to five minutes, issue the following at startup:
mongos --setParameter activeFaultDurationSecs=300
Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand(
{
setParameter: 1,
activeFaultDurationSecs: 300
}
)Parameters set with
setParameterdo not persist across restarts. See the setParameter page for details.To make this setting persistent, set
activeFaultDurationSecsin your mongos config file using thesetParameteroption as in the following example:setParameter:
activeFaultDurationSecs: 300
healthMonitoringIntensities-
Available for
mongosonly.Type类型: Array of documentsUse this parameter to set intensity levels for Health Managers.
healthMonitoringIntensitiesaccepts an array of documents,values. Each document invaluestakes two fields:type, the Health Manager facetintensity, the intensity level
Health Managers
Facet What the Health Observer Checks configServerCluster health issues related to connectivity to the config server. dnsCluster health issues related to DNS availability and functionality. ldapCluster health issues related to LDAP availability and functionality. Intensity Levels
Intensity Level Description描述criticalThe Health Manager on this facet is enabled and has the ability to move the failing mongos out of the cluster if an error occurs. The Health Manager waits the amount of time specified by activeFaultDurationSecsbefore stopping and moving the mongos out of the cluster automatically.non-criticalThe Health Manager on this facet is enabled and logs errors, but the mongos remains in the cluster if errors are encountered. offThe Health Manager on this facet is disabled. The mongos does not perform any health checks on this facet. This is the default intensity level. For example, to set the
dnsHealth Manager facet to thecriticalintensity level, issue the following at startup:mongos --setParameter 'healthMonitoringIntensities={ values:[ { type:"dns", intensity: "critical"} ] }'Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand(
{
setParameter: 1,
healthMonitoringIntensities: { values: [ { type: "dns", intensity: "critical" } ] } } )
}
)Parameters set with
setParameterdo not persist across restarts. See the setParameter page for details.To make this setting persistent, set
healthMonitoringIntensitiesin your mongos config file using thesetParameteroption as in the following example:setParameter:
healthMonitoringIntensities: "{ values:[ { type:\"dns\", intensity: \"critical\"} ] }"
healthMonitoringIntervals-
Available for
mongosonly.Type类型: Array of documentsHow often this Health Manager will run, in milliseconds.
healthMonitoringIntervalsaccepts an array of documents,values. Each document invaluestakes two fields:type, the Health Manager facetinterval, the time interval it runs at, in milliseconds
Health Managers
Facet What the Health Observer Checks configServerCluster health issues related to connectivity to the config server. dnsCluster health issues related to DNS availability and functionality. ldapCluster health issues related to LDAP availability and functionality. For example, to set the
ldapHealth Manager facet to the run health checks every 30 seconds, issue the following at startup:mongos --setParameter 'healthMonitoringIntervals={ values:[ { type:"ldap", interval: "30000"} ] }'Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand(
{
setParameter: 1,
healthMonitoringIntervals: { values: [ { type: "ldap", interval: "30000" } ] } } )
}
)Parameters set with
setParameterdo not persist across restarts. See the setParameter page for details.To make this setting persistent, set
healthMonitoringIntervalsin your mongos config file using thesetParameteroption as in the following example:setParameter:
healthMonitoringIntervals: "{ values: [{type: \"ldap\", interval: 200}] }"
progressMonitor-
Available for
mongosonly.Type类型: DocumentProgress Monitor runs tests to ensure that Health Manager checks do not become stuck or unresponsive. Progress Monitor runs these tests in intervals specified by
interval. If a health check begins but does not complete within the timeout given bydeadline, Progress Monitor stops the mongos and removes it from the cluster.progressMonitorFieldsField字段Description描述Units intervalHow often to ensure Health Managers are not stuck or unresponsive. Milliseconds deadlineTimeout before automatically failing the mongos if a Health Manager check is not making progress. Seconds To set the
intervalto 1000 milliseconds and thedeadlineto 300 seconds, issue the following at startup:mongos --setParameter 'progressMonitor={"interval": 1000, "deadline": 300}'Or if using the
setParametercommand in amongoshsession that is connected to a runningmongos:db.adminCommand(
{
setParameter: 1,
progressMonitor: { interval: 1000, deadline: 300 } )
}
)Parameters set with
setParameterdo not persist across restarts. See the setParameter page for details.To make this setting persistent, set
progressMonitorin your mongos config file using thesetParameteroption as in the following example:setParameter:
progressMonitor: "{ interval: 1000, deadline: 300 }"
Storage Parameters
honorSystemUmask-
Available for仅适用于mongodonly.mongod。Default默认值:falseIf
honorSystemUmaskis set totrue, new files created by MongoDB have permissions in accordance with the user'sumasksettings. You cannot setprocessUmaskifhonorSystemUmaskis set totrue.If
honorSystemUmaskis set tofalse, new files created by MongoDB have permissions set to600, which gives read and write permissions only to the owner. New directories have permissions set to700. You can useprocessUmaskto override the default permissions for groups and other users on all new files created by MongoDB.You can only set this parameter during start-up and cannot change this setting using the
setParameterdatabase command.mongod --setParameter honorSystemUmask=trueNotehonorSystemUmaskis not available on Windows systems.
journalCommitInterval-
Available for仅适用于mongodonly.mongod。Specify an integer between
1and500signifying the number of milliseconds (ms) between journal commits.Consider the following example which sets the
journalCommitIntervalto200ms:db.adminCommand( { setParameter: 1, journalCommitInterval: 200 } )
TipSee also:另请参阅:
minSnapshotHistoryWindowInSecondsNew in version 5.0.5.0版新增。Available for仅适用于mongodonly.mongod。Default默认值:300The minimum time window in seconds for which the storage engine keeps the snapshot history. If you query data using read concern
"snapshot"and specify an atClusterTime value older than the specifiedminSnapshotHistoryWindowInSeconds,mongodreturns aSnapshotTooOlderror.Specify an integer greater than or equal to (
>=) 0.Consider the following example which sets the
minSnapshotHistoryWindowInSecondsto600seconds:db.adminCommand( { setParameter: 1, minSnapshotHistoryWindowInSeconds: 600 } )
NoteIncreasing the value of
minSnapshotHistoryWindowInSecondsincreases disk usage. For more information, see Snapshot History Retention.To modify this value for a MongoDB Atlas cluster, you must contact Atlas Support.
processUmaskNew in version 4.4.4.4版新增。Available for仅适用于mongodonly.mongod。Overrides the default permissions used for groups and other users when
honorSystemUmaskis set tofalse. By default, whenhonorSystemUmaskis set tofalse, new files created by MongoDB have permissions set to600. Use theprocessUmaskparameter to override this default with a customumaskvalue. The file owner inherits permissions from the systemumask.You cannot set this parameter if
honorSystemUmaskis set totrue. You can only set this parameter during start-up and cannot change this setting using thesetParameterdatabase command.Consider the following example, which sets the permissions for groups and other users to read/write only and retains the system
umasksettings for the owner:mongod --setParameter processUmask=011
NoteprocessUmaskis not available on Windows systems.
syncdelay-
Available for仅适用于mongodonly.mongod。Specify the interval in seconds between fsync operations where
mongodflushes its working memory to disk. By default,mongodflushes memory to disk every 60 seconds. In almost every situation you should not set this value and use the default setting.Consider the following example which sets the
syncdelayto60seconds:db.adminCommand( { setParameter: 1, syncdelay: 60 } )
TipSee also:另请参阅:
temporarilyUnavailableBackoffBaseMs-
Available for仅适用于mongodonly.mongod。Specifies the initial delay before retying a write operation that was rolled back due to cache pressure.
In rare circumstances, a write can fail due to cache pressure. When this happens MongoDB issues a
TemporarilyUnavailableerror and increments thetemporarilyUnavailableErrorscounter in two places: the slow query log and the Full Time Diagnostic Data Capture (FTDC).Individual operations within multi-document transactions never return
TemporarilyUnavailableerrors.Adjust the write retry properties by modifying the
temporarilyUnavailableBackoffBaseMsandtemporarilyUnavailableMaxRetriesparameters.The parameter accepts:
Value值Description描述integer >= 0Defaults to 1 second. The initial delay between retries. The value increases with each retry to a maximum of 55 seconds. A larger value increases the chance that the cache pressure will be reduced before the next retry.
To configure number of retries, usetemporarilyUnavailableMaxRetries.To set a new value, use
db.adminCommand():db.adminCommand( { setParameter: 1, temporarilyUnavailableBackoffBaseMs: 3 } )
New in version 6.1.0.6.1.0版新增。
temporarilyUnavailableMaxRetries-
Available for仅适用于mongodonly.mongod。Specifies the maximum number of retries when a write operation is rolled back due to cache pressure.
In rare circumstances, a write can fail due to cache pressure. When this happens MongoDB issues a
TemporarilyUnavailableerror and increments thetemporarilyUnavailableErrorscounter in two places: the slow query log and the Full Time Diagnostic Data Capture (FTDC).Individual operations within multi-document transactions never return
TemporarilyUnavailableerrors.Adjust the write retry properties by modifying the
temporarilyUnavailableBackoffBaseMsandtemporarilyUnavailableMaxRetriesparameters.The parameter accepts:
Value值Description描述integer >= 0Defaults to 10. The maximum number of retries.
There is an increasing delay between retries. To configure the backoff time, usetemporarilyUnavailableBackoffBaseMs.To set a new value, use
db.adminCommand():db.adminCommand( { setParameter: 1, temporarilyUnavailableMaxRetries: 5 } )
New in version 6.1.0.6.1.0版新增。
WiredTiger Parameters
wiredTigerMaxCacheOverflowSizeGB- Note
Deprecated in MongoDB 4.4
MongoDB deprecates the
wiredTigerMaxCacheOverflowSizeGBparameter. The parameter has no effect starting in MongoDB 4.4.Available for仅适用于mongodonly.mongod。Default默认值: 0 (No specified maximum)Specify the maximum size (in GB) for the "lookaside (or cache overflow) table" file
WiredTigerLAS.wtfor MongoDB 4.2.1-4.2.x. The file no longer exists starting in version 4.4.The parameter can accept the following values:
Value值Description描述0The default value. If set to 0, the file size is unbounded.number >= 0.1 The maximum size (in GB). If the WiredTigerLAS.wtfile exceeds this size,mongodexits with a fatal assertion. You can clear theWiredTigerLAS.wtfile and restartmongod.You can only set this parameter during run time using the
setParameterdatabase command:db.adminCommand( { setParameter: 1, wiredTigerMaxCacheOverflowSizeGB: 100 } )
To set the maximum size during start up, use the
storage.wiredTiger.engineConfig.maxCacheOverflowFileSizeGBinstead.New in version 4.2.1.4.2.1版新增。
wiredTigerConcurrentReadTransactionsChanged in version 7.0.7.0版更改。Available for仅适用于mongodonly.mongod。Starting in MongoDB 7.0, this parameter is available for all storage engines. In earlier versions, this parameter is available for the WiredTiger storage engine only.
Specify the maximum number of concurrent read transactions allowed into the storage engine.
ImportantStarting in MongoDB 7.0, this parameter disables an algorithm that dynamically adjusts the number of concurrent storage engine transactions.
db.adminCommand( { setParameter: 1, wiredTigerConcurrentReadTransactions: <num> } )
TipSee also:另请参阅:
wiredTigerConcurrentWriteTransactionsChanged in version 7.0.7.0版更改。Available for仅适用于mongodonly.mongod。Starting in MongoDB 7.0, this parameter is available for all storage engines. In earlier versions, this parameter is available for the WiredTiger storage engine only.
Specify the maximum number of concurrent write transactions allowed into the WiredTiger storage engine.
ImportantStarting in MongoDB 7.0, this parameter disables an algorithm that dynamically adjusts the number of concurrent storage engine transactions.
db.adminCommand( { setParameter: 1, wiredTigerConcurrentWriteTransactions: <num> } )
TipSee also:另请参阅:
wiredTigerEngineRuntimeConfig-
Available for仅适用于mongodonly.mongod。Specify
wiredTigerstorage engine configuration options for a runningmongodinstance. You can only set this parameter using thesetParametercommand and not using the command line or configuration file option.WarningAvoid modifying the
wiredTigerEngineRuntimeConfigunless under the direction from MongoDB engineers as this setting has major implication across both WiredTiger and MongoDB.Consider the following operation prototype:
db.adminCommand({
"setParameter": 1,
"wiredTigerEngineRuntimeConfig": "<option>=<setting>,<option>=<setting>"
})See the WiredTiger documentation for all available WiredTiger configuration options.
Auditing Parameters
auditAuthorizationSuccess-
Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: falseNoteAvailable only in MongoDB Enterprise
and MongoDB Atlas
.
Enables the auditing of authorization successes for the authCheck action.
When
auditAuthorizationSuccessisfalse, the audit system only logs the authorization failures forauthCheck.To enable the audit of authorization successes, issue the following command:
db.adminCommand( { setParameter: 1, auditAuthorizationSuccess: true } )
Enabling
auditAuthorizationSuccessdegrades performance more than logging only the authorization failures.If runtime audit configuration is enabled, the
auditAuthorizationSuccessparameter should not appear in themongodormongosconfiguration file. The server will fail to start if the parameter is present.TipSee also:另请参阅:
auditConfigPollingFrequencySecsNew in version 5.0.5.0版新增。Type类型: integerDefault默认值: 300A sharded cluster may have servers which maintain audit configuration settings for the cluster. Set the interval, in seconds, for non-configured servers to poll a config server for the current audit generation. If this value returned differs from the previously known value, the initiating node will request the current configuration and update its internal state.
NoteUsing the default value of 300 seconds, non-config nodes may lag up to 5 minutes behind a setAuditConfig command.
auditEncryptionHeaderMetadataFileNew in version 6.0.6.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: stringNoteAvailable only in MongoDB Enterprise
. MongoDB Enterprise and Atlas have different configuration requirements.
Path and file name for logging metadata audit headers for audit log encryption. A header is placed at the top of each audit log file and contains metadata for decrypting the audit log. The headers are also stored in the audit log.
You can only set
auditEncryptionHeaderMetadataFileduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following sets the path and file forauditEncryptionHeaderMetadataFile:mongod --setParameter auditEncryptionHeaderMetadataFile=/auditFiles/auditHeadersMetadataFile.log
auditEncryptKeyWithKMIPGetNew in version 6.0.6.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Type类型: booleanDefault默认值: falseNoteAvailable only in MongoDB Enterprise
. MongoDB Enterprise and Atlas have different configuration requirements.
Enables audit log encryption for Key Management Interoperability Protocol (KMIP) servers that only support KMIP protocol version 1.0 or 1.1.
You can only set
auditEncryptKeyWithKMIPGetduring startup in theconfiguration fileor with the--setParameteroption on the command line. For example, the following setsauditEncryptKeyWithKMIPGettotrue:mongod --setParameter auditEncryptKeyWithKMIPGet=true
Transaction Parameters
coordinateCommitReturnImmediatelyAfterPersistingDecisionNew in version 5.0.5.0版新增。Updated in version 6.1
Available for仅适用于mongodonly.mongod。Type类型: booleanDefault默认值: falseBehavior When
falseThe shard transaction coordinator waits for all members to acknowledge the decision to either commit or cancel a multi-document transaction before returning the result to the client.
Behavior When
trueThe shard transaction coordinator returns a multi-document transaction commit decision to the client as soon as the decision is made durable with the requested transaction write concern.
If the client requested a write concern that is less than
"majority", the commit may roll back after the decision is returned to the client.Transactions may not have "read your writes" consistency. That is, a read operation may not reflect the results of a write operation that preceded it. This can happen in the following cases:
- A transaction has to write to multiple shards.
- The read and the earlier write take place in different sessions.
Causal consistency only guarantees the causal relationship of reads and writes that occur within the same session.
Example实例The following example sets
coordinateCommitReturnImmediatelyAfterPersistingDecisiontotrue:mongod --setParameter coordinateCommitReturnImmediatelyAfterPersistingDecision=trueDuring run time, you can also set the parameter with the
setParametercommand:db.adminCommand( { setParameter: 1, coordinateCommitReturnImmediatelyAfterPersistingDecision: true } )
internalSessionsReapThresholdNew in version 6.0.6.0版新增。Available for both可用于mongodandmongos.mongod和mongos。Default默认值: 1000Session limit for internal session metadata deletion. The metadata:
- Contains session transaction information for user operations.
- Is stored in the
config.transactionscollection.
When the number of internal sessions is greater than
internalSessionsReapThreshold, the metadata is deleted.If you set
internalSessionsReapThresholdto0, the internal session metadata is only deleted when the user session ends.The following example sets
internalSessionsReapThresholdto500sessions:db.adminCommand( { setParameter: 1, internalSessionsReapThreshold: 500 } )
You can also set
internalSessionsReapThresholdat startup.For example:例如:mongod --setParameter internalSessionsReapThreshold=500
transactionLifetimeLimitSeconds-
Available for仅适用于mongodonly.mongod。Default默认值: 60Specifies the lifetime of multi-document transactions. Transactions that exceed this limit are considered expired and will be aborted by a periodic cleanup process. The cleanup process runs every
transactionLifetimeLimitSeconds/2 seconds or at least once every 60 seconds.The cleanup process helps relieve storage cache pressure.
The minimum value for transactionLifetimeLimitSeconds is
1second.The following sets the
transactionLifetimeLimitSecondsto30seconds:db.adminCommand( { setParameter: 1, transactionLifetimeLimitSeconds: 30 } )
You can also set parameter
transactionLifetimeLimitSecondsat startup time.mongod --setParameter "transactionLifetimeLimitSeconds=30"To set the parameter for a sharded cluster, the parameter must be modified for all shard replica set members.
Starting in MongoDB 5.0, if you change the
transactionLifetimeLimitSecondsparameter, you must also changetransactionLifetimeLimitSecondsto the same value on all config server replica set members. Keeping this value consistent:- Ensures the routing table history is retained for at least as long as the transaction lifetime limit on the shard replica set members.
- Reduces the transaction retry frequency and therefore improves performance.
transactionTooLargeForCacheThresholdNew in version 6.2.6.2版新增。Available for仅适用于mongodonly.mongod。Type类型: decimalDefault默认值: 0.75The threshold value for retrying transactions that fail due to cache pressure. The value is a percentage of the dirty cache size. The default value,
0.75, means 75% of the dirty cache.The dirty cache is limited to 20% of the total cache size. When
transactionTooLargeForCacheThresholdis set to0.75, the server only retries transactions that use less than 15% (0.75 * 20%) of the total storage engine cache.The limit only applies to retries. Large transactions can use more than
transactionTooLargeForCacheThresholdpercent of the dirty cache. However, if a large transaction is rolled back due to cache pressure, the server issues aTransactionTooLargeForCacheerror and does not retry the transaction.To disable this behavior, set
transactionTooLargeForCacheThresholdto1.0.For more information on WiredTiger storage, see:
storage.wiredTigerOptions.
maxTransactionLockRequestTimeoutMillis-
Available for仅适用于mongodonly.mongod。Type类型: integerDefault默认值: 5The maximum amount of time in milliseconds that multi-document transactions should wait to acquire locks required by the operations in the transaction.
If the transaction cannot acquire the locks after waiting
maxTransactionLockRequestTimeoutMillis, the transaction aborts.By default, multi-document transactions wait
5milliseconds. That is, if the transaction cannot acquire the locks within5milliseconds, the transaction aborts. If an operation provides a greater timeout in a lock request,maxTransactionLockRequestTimeoutMillisoverrides the operation-specific timeout.You can set
maxTransactionLockRequestTimeoutMillisto:0such that if the transaction cannot acquire the required locks immediately, the transaction aborts.- A number greater than
0to wait the specified time to acquire the required locks. This can help obviate transaction aborts on momentary concurrent lock acquisitions, like fast-running metadata operations. However, this could possibly delay the abort of deadlocked transaction operations. -1to use the operation specific timeout.
The following sets the
maxTransactionLockRequestTimeoutMillisto20milliseconds:db.adminCommand( { setParameter: 1, maxTransactionLockRequestTimeoutMillis: 20 } )
You can also set this parameter during start-up:
mongod --setParameter maxTransactionLockRequestTimeoutMillis=20
shouldMultiDocTxnCreateCollectionAndIndexes-
Removed in 5.0
Type类型: booleanDefault默认值: trueA flag that enables or disables the creation of a collection or an index inside transactions. Set the parameter to:
trueto enable. (Default默认值)falseto disable.
You can set the parameter during startup or run time.
ImportantWhen setting the parameter for a sharded cluster, set the parameter on all shards.
To set the parameter at startup, specify the parameter in the
configuration fileor with the--setParameteroption on the command line.For example:例如:mongod --setParameter shouldMultiDocTxnCreateCollectionAndIndexes=falseTo modify during run time, you can use the
setParametercommand;for example:例如:db.adminCommand( { setParameter: 1, shouldMultiDocTxnCreateCollectionAndIndexes: false } )
Slot-Based Execution Parameters
planCacheSizeNew in version 6.3.6.3版新增。Available for仅适用于mongodonly.mongod。Type类型: stringDefault默认值: 5%NoteAlthough the
planCacheSizeparameter existed in prior versions of MongoDB, it had no effect on the plan cache until version 6.3.Sets the size of the plan cache only for the slot-based query execution engine.
You can set the
planCacheSizevalue to either:- A percentage of the system's total physical memory to allocate for the plan cache. For example,
"8.5%". - The exact amount of data to allocate for the plan cache in either
MBorGB. For example,"100MB"or"1GB".
Increasing the plan cache size adds more cached query shapes for the query planner. This can improve query performance, but increases memory usage.
The following startup command sets
planCacheSizeto 80 megabytes:mongod --setParameter planCacheSize="80MB"You can also use the
setParametercommand within the MongoDB Shell:db.adminCommand( { setParameter: 1, planCacheSize: "80MB" } )
- A percentage of the system's total physical memory to allocate for the plan cache. For example,