翻译或纠错本页面

配置文件选项

本页将会描述MongoDB 3.4 中可用的配置选项。请查阅其它合适版本的MongoDB手册查找其它版本的配置文件选项。

配置文件

您可以在启动的时候使用一个配置文件配置 mongodmongos 。配置文件中包含那些等同于 mongodmongos 命令行选项的设置。

Using a configuration file makes managing mongod and mongos options easier, especially for large-scale deployments. You can also add comments to the configuration file to explain the server’s settings.

使用配置文件使得管理 mongodmongos 更加方便,特别是对于大型可扩展的部署而言。您也可以向配置文件添加注释以解释服务器的配置。

文件形式

重要

在 2.6 版更改: MongoDB 2.6 introduces a YAML-based configuration file format. The 2.4 configuration file format remains for backward compatibility.

MongoDB configuration files use the YAML format [1].

The following sample configuration file contains several mongod settings that you may adapt to your local configuration:

注解

YAML does not support tab characters for indentation: use spaces instead.

systemLog:
   destination: file
   path: "/var/log/mongodb/mongod.log"
   logAppend: true
storage:
   journal:
      enabled: true
processManagement:
   fork: true
net:
   bindIp: 127.0.0.1
   port: 27017
setParameter:
   enableLocalhostAuthBypass: false
...

The Linux package init scripts included in the official MongoDB packages depend on specific values for systemLog.path, storage.dbpath, and processManagement.fork. If you modify these settings in the default configuration file, mongod may not start.

[1]YAML is a superset of JSON.

Use the Configuration File

To start mongod or mongos using a config file, specify the config file with the --config option or the -f option, as in the following examples:

The following examples use the --config option for mongod and mongos:

mongod --config /etc/mongod.conf

mongos --config /etc/mongos.conf

You can also use the -f alias to specify the configuration file, as in the following:

mongod -f /etc/mongod.conf

mongos -f /etc/mongos.conf

使用配置文件使得管理 mongodmongos 更加方便,特别是对于大型可扩展的部署而言。您也可以向配置文件添加注释以解释服务器的配置。

Core Options

systemLog Options

systemLog:
   verbosity: <int>
   quiet: <boolean>
   traceAllExceptions: <boolean>
   syslogFacility: <string>
   path: <string>
   logAppend: <boolean>
   logRotate: <string>
   destination: <string>
   timeStampFormat: <string>
   component:
      accessControl:
         verbosity: <int>
      command:
         verbosity: <int>

      # COMMENT additional component verbosity settings omitted for brevity
systemLog.verbosity

Type: integer

Default: 0

在 3.0 版更改.

The default log message verbosity level for components. The verbosity level determines the amount of Informational and Debug messages MongoDB outputs.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.

To use a different verbosity level for a named component, use the component’s verbosity setting. For example, use the systemLog.component.accessControl.verbosity to set the verbosity level specifically for ACCESS components.

See the systemLog.component.<name>.verbosity settings for specific component verbosity settings.

For various ways to set the log verbosity level, see Configure Log Verbosity Levels.

systemLog.quiet

Type: boolean

Run mongos or mongod in a quiet mode that attempts to limit the amount of output.

systemLog.quiet is not recommended for production systems as it may make tracking problems during particular connections much more difficult.

systemLog.traceAllExceptions

Type: boolean

Print verbose information for debugging. Use for additional logging for support-related troubleshooting.

systemLog.syslogFacility

Type: string

Default: user

The facility level used when logging messages to syslog. The value you specify must be supported by your operating system’s implementation of syslog. To use this option, you must enable the --syslog option.

systemLog.path

Type: string

The path of the log file to which mongod or mongos should send all diagnostic logging information, rather than the standard output or the host’s syslog. MongoDB creates the log file at the specified path.

The Linux package init scripts do not expect systemLog.path to change from the defaults. If you use the Linux packages and change systemLog.path, you will have to use your own init scripts and disable the built-in scripts.

systemLog.logAppend

Type: boolean

Default: False

When true, mongos or mongod appends new entries to the end of the existing log file when the mongos or mongod instance restarts. Without this option, mongod will back up the existing log and create a new file.

systemLog.logRotate

Type: string

Default: rename

3.0.0 新版功能.

The behavior for the logRotate command. Specify either rename or reopen:

  • rename renames the log file.

  • reopen closes and reopens the log file following the typical Linux/Unix log rotate behavior. Use reopen when using the Linux/Unix logrotate utility to avoid log loss.

    If you specify reopen, you must also set systemLog.logAppend to true.

systemLog.destination

Type: string

The destination to which MongoDB sends all log output. Specify either file or syslog. If you specify file, you must also specify systemLog.path.

If you do not specify systemLog.destination, MongoDB sends all log output to standard output.

systemLog.timeStampFormat

Type: string

Default: iso8601-local

The time format for timestamps in log messages. Specify one of the following values:

Value Description
ctime Displays timestamps as Wed Dec 31 18:17:54.811.
iso8601-utc Displays timestamps in Coordinated Universal Time (UTC) in the ISO-8601 format. For example, for New York at the start of the Epoch: 1970-01-01T00:00:00.000Z
iso8601-local Displays timestamps in local time in the ISO-8601 format. For example, for New York at the start of the Epoch: 1969-12-31T19:00:00.000-0500

systemLog.component Options

systemLog:
   component:
      accessControl:
         verbosity: <int>
      command:
         verbosity: <int>

      # COMMENT some component verbosity settings omitted for brevity

      storage:
         verbosity: <int>
         journal:
            verbosity: <int>
      write:
         verbosity: <int>
systemLog.component.accessControl.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to access control. See ACCESS components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.command.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to commands. See COMMAND components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.control.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to control operations. See CONTROL components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.ftdc.verbosity

Type: integer

Default: 0

3.2 新版功能.

The log message verbosity level for components related to diagnostic data collection operations. See FTDC components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.geo.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to geospatial parsing operations. See GEO components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.index.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to indexing operations. See INDEX components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.network.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to networking operations. See NETWORK components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.query.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to query operations. See QUERY components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.replication.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to replication. See REPL components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.sharding.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to sharding. See SHARDING components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.storage.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to storage. See STORAGE components.

If systemLog.component.storage.journal.verbosity is unset, systemLog.component.storage.verbosity level also applies to journaling components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.storage.journal.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to journaling. See JOURNAL components.

If systemLog.component.storage.journal.verbosity is unset, the journaling components have the same verbosity level as the parent storage components: i.e. either the systemLog.component.storage.verbosity level if set or the default verbosity level.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.
systemLog.component.write.verbosity

Type: integer

Default: 0

3.0 新版功能.

The log message verbosity level for components related to write operations. See WRITE components.

The verbosity level can range from 0 to 5:

  • 0 is the MongoDB’s default log verbosity level, to include Informational messages.
  • 1 to 5 increases the verbosity level to include Debug messages.

processManagement Options

processManagement:
   fork: <boolean>
   pidFilePath: <string>
processManagement.fork

Type: boolean

Default: False

Enable a daemon mode that runs the mongos or mongod process in the background. By default mongos or mongod does not run as a daemon: typically you will run mongos or mongod as a daemon, either by using processManagement.fork or by using a controlling process that handles the daemonization process (e.g. as with upstart and systemd).

The Linux package init scripts do not expect processManagement.fork to change from the defaults. If you use the Linux packages and change processManagement.fork, you will have to use your own init scripts and disable the built-in scripts.

processManagement.pidFilePath

Type: string

Specifies a file location to hold the process ID of the mongos or mongod process where mongos or mongod will write its PID. This is useful for tracking the mongos or mongod process in combination with the --fork option. Without a specified processManagement.pidFilePath option, the process creates no PID file.

net Options

net:
   port: <int>
   bindIp: <string>
   maxIncomingConnections: <int>
   wireObjectCheck: <boolean>
   ipv6: <boolean>
   unixDomainSocket:
      enabled: <boolean>
      pathPrefix: <string>
      filePermissions: <int>
   http:
      enabled: <boolean>
      JSONPEnabled: <boolean>
      RESTInterfaceEnabled: <boolean>
   ssl:
      sslOnNormalPorts: <boolean>  # deprecated since 2.6
      mode: <string>
      PEMKeyFile: <string>
      PEMKeyPassword: <string>
      clusterFile: <string>
      clusterPassword: <string>
      CAFile: <string>
      CRLFile: <string>
      allowConnectionsWithoutCertificates: <boolean>
      allowInvalidCertificates: <boolean>
      allowInvalidHostnames: <boolean>
      disabledProtocols: <string>
      FIPSMode: <boolean>
net.port

Type: integer

Default: 27017

The TCP port on which the MongoDB instance listens for client connections.

net.bindIp

Type: string

Default: All interfaces.

在 2.6.0 版更改: The deb and rpm packages include a default configuration file (/etc/mongod.conf) that sets net.bindIp to 127.0.0.1.

The IP address that mongos or mongod binds to in order to listen for connections from applications. You may attach mongos or mongod to any interface. When attaching mongos or mongod to a publicly accessible interface, ensure that you have implemented proper authentication and firewall restrictions to protect the integrity of your database.

To bind to multiple IP addresses, enter a list of comma separated values.

net.maxIncomingConnections

Type: integer

Default: 65536

The maximum number of simultaneous connections that mongos or mongod will accept. This setting has no effect if it is higher than your operating system’s configured maximum connection tracking threshold.

Do not assign too low of a value to this option, or you will encounter errors during normal application operation.

This is particularly useful for a mongos if you have a client that creates multiple connections and allows them to timeout rather than closing them.

In this case, set maxIncomingConnections to a value slightly higher than the maximum number of connections that the client creates, or the maximum size of the connection pool.

This setting prevents the mongos from causing connection spikes on the individual shards. Spikes like these may disrupt the operation and memory allocation of the sharded cluster.

net.wireObjectCheck

Type: boolean

Default: True

When true, the mongod or mongos instance validates all requests from clients upon receipt to prevent clients from inserting malformed or invalid BSON into a MongoDB database.

For objects with a high degree of sub-document nesting, net.wireObjectCheck can have a small impact on performance.

net.ipv6

Type: boolean

Default: False

Removed in version 3.0.

Enable or disable IPv6 support and allows mongos or mongod to connect to the MongoDB instance using an IPv6 network. Prior to MongoDB 3.0, you had to specify net.ipv6 to use IPv6. In MongoDB 3.0 and later, IPv6 is always enabled.

net.unixDomainSocket Options

net:
   unixDomainSocket:
      enabled: <boolean>
      pathPrefix: <string>
      filePermissions: <int>
net.unixDomainSocket.enabled

Type: boolean

Default: True

Enable or disable listening on the UNIX domain socket. net.unixDomainSocket.enabled applies only to Unix-based systems.

When net.unixDomainSocket.enabled is true, mongos or mongod listens on the UNIX socket.

The mongos or mongod process always listens on the UNIX socket unless one of the following is true:

  • net.unixDomainSocket.enabled is false
  • --nounixsocket is set. The command line option takes precedence over the configuration file setting.
  • net.bindIp is not set
  • net.bindIp does not specify 127.0.0.1

2.6 新版功能: mongos or mongod installed from official .deb and .rpm packages have the bind_ip configuration set to 127.0.0.1 by default.

net.unixDomainSocket.pathPrefix

Type: string

Default: /tmp

The path for the UNIX socket. net.unixDomainSocket.pathPrefix applies only to Unix-based systems.

If this option has no value, the mongos or mongod process creates a socket with /tmp as a prefix. MongoDB creates and listens on a UNIX socket unless one of the following is true:

  • net.unixDomainSocket.enabled is false
  • --nounixsocket is set
  • net.bindIp is not set
  • net.bindIp does not specify 127.0.0.1
net.unixDomainSocket.filePermissions

Type: int

Default: 0700

Sets the permission for the UNIX domain socket file.

net.unixDomainSocket.filePermissions applies only to Unix-based systems.

net.http Options

net:
   http:
      enabled: <boolean>
      JSONPEnabled: <boolean>
      RESTInterfaceEnabled: <boolean>

警告

Ensure that the HTTP status interface, the REST API, and the JSON API are all disabled in production environments to prevent potential data exposure and vulnerability to attackers.

net.http.enabled

Type: boolean

Default: False

3.2 版后已移除: HTTP interface for MongoDB

Enable or disable the HTTP interface. Enabling the interface can increase network exposure.

Leave the HTTP interface disabled for production deployments. If you do enable this interface, you should only allow trusted clients to access this port. See Firewalls.

注解

  • While MongoDB Enterprise does support Kerberos authentication, Kerberos is not supported in HTTP status interface in any version of MongoDB.

2.6 新版功能.

net.http.JSONPEnabled

Type: boolean

Default: False

Enable or disable JSONP access via an HTTP interface. Enabling the interface can increase network exposure. The net.http.JSONPEnabled option enables the HTTP interface, even if the HTTP interface option is disabled.

3.2 版后已移除: HTTP interface for MongoDB

The net.http.JSONPEnabled setting is available only for mongod.

net.http.RESTInterfaceEnabled

Type: boolean

Default: False

Enable or disable the simple REST API. Enabling the REST API enables the HTTP interface, even if the HTTP interface option is disabled, and as a result can increase network exposure.

3.2 版后已移除: HTTP interface for MongoDB

The net.http.RESTInterfaceEnabled setting is available only for mongod.

net.ssl Options

net:
   ssl:
      sslOnNormalPorts: <boolean>  # deprecated since 2.6
      mode: <string>
      PEMKeyFile: <string>
      PEMKeyPassword: <string>
      clusterFile: <string>
      clusterPassword: <string>
      CAFile: <string>
      CRLFile: <string>
      allowConnectionsWithoutCertificates: <boolean>
      allowInvalidCertificates: <boolean>
      allowInvalidHostnames: <boolean>
      disabledProtocols: <string>
      FIPSMode: <boolean>
net.ssl.sslOnNormalPorts

Type: boolean

2.6 版后已移除.

Enable or disable TLS/SSL for mongos or mongod.

With net.ssl.sslOnNormalPorts, a mongos or mongod requires TLS/SSL encryption for all connections on the default MongoDB port, or the port specified by --port. By default, --sslOnNormalPorts is disabled.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.mode

Type: string

2.6 新版功能.

Enable or disable TLS/SSL or mixed TLS/SSL used for all network connections. The argument to the net.ssl.mode setting can be one of the following:

Value Description
disabled The server does not use TLS/SSL.
allowSSL Connections between servers do not use TLS/SSL. For incoming connections, the server accepts both TLS/SSL and non-TLS/non-SSL.
preferSSL Connections between servers use TLS/SSL. For incoming connections, the server accepts both TLS/SSL and non-TLS/non-SSL.
requireSSL The server uses and accepts only TLS/SSL encrypted connections.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.PEMKeyFile

Type: string

The .pem file that contains both the TLS/SSL certificate and key. Specify the file name of the .pem file using relative or absolute paths.

You must specify net.ssl.PEMKeyFile when TLS/SSL is enabled.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.PEMKeyPassword

Type: string

The password to de-crypt the certificate-key file (i.e. PEMKeyFile). Use the net.ssl.PEMKeyPassword option only if the certificate-key file is encrypted. In all cases, the mongos or mongod will redact the password from all logging and reporting output.

在 2.6 版更改: If the private key in the PEM file is encrypted and you do not specify the net.ssl.PEMKeyPassword option, the mongos or mongod will prompt for a passphrase. See SSL Certificate Passphrase.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.clusterFile

Type: string

2.6 新版功能.

The .pem file that contains the x.509 certificate-key file for membership authentication for the cluster or replica set.

If net.ssl.clusterFile does not specify the .pem file for internal cluster authentication, the cluster uses the .pem file specified in the PEMKeyFile setting.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.clusterPassword

Type: string

2.6 新版功能.

The password to de-crypt the x.509 certificate-key file specified with --sslClusterFile. Use the net.ssl.clusterPassword option only if the certificate-key file is encrypted. In all cases, the mongos or mongod will redact the password from all logging and reporting output.

If the x.509 key file is encrypted and you do not specify the net.ssl.clusterPassword option, the mongos or mongod will prompt for a passphrase. See SSL Certificate Passphrase.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.CAFile

Type: string

2.4 新版功能.

The .pem file that contains the root certificate chain from the Certificate Authority. Specify the file name of the .pem file using relative or absolute paths.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

警告

If the --sslCAFile option and its target file are not specified, x.509 client and member authentication will not function. mongod, and mongos in sharded systems, will not be able to verify the certificates of processes connecting to it against the trusted certificate authority (CA) that issued them, breaking the certificate chain.

As of version 2.6.4, mongod will not start with x.509 authentication enabled if the CA file is not specified.

net.ssl.CRLFile

Type: string

2.4 新版功能.

The the .pem file that contains the Certificate Revocation List. Specify the file name of the .pem file using relative or absolute paths.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.allowConnectionsWithoutCertificates

Type: boolean

2.4 新版功能.

在 3.0.0 版更改: net.ssl.weakCertificateValidation became net.ssl.allowConnectionsWithoutCertificates. For compatibility, MongoDB processes continue to accept net.ssl.weakCertificateValidation, but all users should update their configuration files.

Enable or disable the requirement for TLS/SSL certificate validation that CAFile enables. With the net.ssl.allowConnectionsWithoutCertificates option, the mongos or mongod will accept connections when the client does not present a certificate when establishing the connection.

If the client presents a certificate and the mongos or mongod has net.ssl.allowConnectionsWithoutCertificates enabled, the mongos or mongod will validate the certificate using the root certificate chain specified by CAFile and reject clients with invalid certificates.

Use the net.ssl.allowConnectionsWithoutCertificates option if you have a mixed deployment that includes clients that do not or cannot present certificates to the mongos or mongod.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.allowInvalidCertificates

Type: boolean

2.6 新版功能.

Enable or disable the validation checks for TLS/SSL certificates on other servers in the cluster and allows the use of invalid certificates.

When using the net.ssl.allowInvalidCertificates setting, MongoDB logs a warning regarding the use of the invalid certificate.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.allowInvalidHostnames

Type: boolean

Default: False

3.0 新版功能.

When net.ssl.allowInvalidHostnames is true, MongoDB disables the validation of the hostnames in TLS/SSL certificates, allowing mongod to connect to MongoDB instances if the hostname their certificates do not match the specified hostname.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

net.ssl.disabledProtocols

Type: string

3.0.7 新版功能.

Prevents a MongoDB server running with SSL from accepting incoming connections that use a specific protocol or protocols. net.ssl.disabledProtocols recognizes the following protocols: TLS1_0, TLS1_1, and TLS1_2. Specifying an unrecognized protocol will prevent the server from starting.

To specify multiple protocols, use a comma separated list of protocols.

Members of replica sets and sharded clusters must speak at least one protocol in common.

net.ssl.FIPSMode

Type: boolean

2.4 新版功能.

Enable or disable the use of the FIPS mode of the installed OpenSSL library for the mongos or mongod. Your system must have a FIPS compliant OpenSSL library to use the net.ssl.FIPSMode option.

注解

FIPS-compatible SSL is available only in MongoDB Enterprise. See Configure MongoDB for FIPS for more information.

security Options

security:
   keyFile: <string>
   clusterAuthMode: <string>
   authorization: <string>
   transitionToAuth: <boolean>
   javascriptEnabled:  <boolean>
   redactClientLogData: <boolean>
   sasl:
      hostName: <string>
      serviceName: <string>
      saslauthdSocketPath: <string>
   enableEncryption: <boolean>
   encryptionCipherMode: <string>
   encryptionKeyFile: <string>
   kmip:
      keyIdentifier: <string>
      rotateMasterKey: <boolean>
      serverName: <string>
      port: <string>
      clientCertificateFile: <string>
      clientCertificatePassword: <string>
      serverCAFile: <string>
   ldap:
      servers: <string>
      bind:
         method: <string>
         saslMechanism: <string>
         queryUser: <string>
         queryPassword: <string>
         useOSDefaults: <boolean>
      transportSecurity: <string>
      timeoutMS: <int>
      userToDNMapping: <string>
      authz:
         queryTemplate: <string>
security.keyFile

Type: string

The path to a key file that stores the shared secret that MongoDB instances use to authenticate to each other in a sharded cluster or replica set. keyFile implies security.authorization. See Internal Authentication for more information.

security.clusterAuthMode

Type: string

Default: keyFile

2.6 新版功能.

The authentication mode used for cluster authentication. If you use internal x.509 authentication, specify so here. This option can have one of the following values:

Value Description
keyFile Use a keyfile for authentication. Accept only keyfiles.
sendKeyFile For rolling upgrade purposes. Send a keyfile for authentication but can accept both keyfiles and x.509 certificates.
sendX509 For rolling upgrade purposes. Send the x.509 certificate for authentication but can accept both keyfiles and x.509 certificates.
x509 Recommended. Send the x.509 certificate for authentication and accept only x.509 certificates.

在 3.0 版更改: Most MongoDB distributions now include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.

security.authorization

Type: string

Default: disabled

Enable or disable Role-Based Access Control (RBAC) to govern each user’s access to database resources and operations.

Set this option to one of the following:

Value Description
enabled A user can access only the database resources and actions for which they have been granted privileges.
disabled A user can access any database and perform any action.

See Role-Based Access Control for more information.

The security.authorization setting is available only for mongod.

security.transitionToAuth

Type: boolean

Default: False

3.4 新版功能: Allows the mongod or mongos to accept and create authenticated and non-authenticated connections to and from other mongod and mongos instances in the deployment. Used for performing rolling transition of replica sets or sharded clusters from a no-auth configuration to internal authentication. Requires specifying a internal authentication mechanism such as --keyfile.

For example, if using keyfiles for internal authentication, the mongod or mongos creates an authenticated connection with any mongod or mongos in the deployment using a matching keyfile. If the security mechanisms do not match, the mongod or mongos utilizes a non-authenticated connection instead.

A mongod or mongos running with security.transitionToAuth does not enforce user access controls. Users may connect to your deployment without any access control checks and perform read, write, and administrative operations.

注解

A mongod or mongos running with internal authentication and without security.transitionToAuth requires clients to connect using user access controls. Update clients to connect to the mongod or mongos using the appropriate user prior to restarting mongod or mongos without security.transitionToAuth.

security.javascriptEnabled

Type: boolean

Default: True

Enables or disables the server-side JavaScript execution. When disabled, you cannot use operations that perform server-side execution of JavaScript code, such as the $where query operator, mapReduce command and the db.collection.mapReduce() method, group command and the db.collection.group() method.

security.redactClientLogData

Type: boolean

3.4 新版功能: Available in MongoDB Enterprise only.

A mongod or mongos running with security.redactClientLogData redacts any message accompanying a given log event before logging. This prevents the mongod or mongos 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 security.redactClientLogData in conjunction with encryption to assist compliance with regulatory requirements.

For example, a MongoDB deployment might store Personally Identifiable Information (PII) in one or more collections. The mongod or mongos logs events such as those related to CRUD operations, sharding metadata, etc. It is possible that the mongod or mongos may expose PII as a part of these logging operations. A mongod or mongos running with security.redactClientLogData removes any message accompanying these events before being output to the log, effectively removing the PII.

Diagnostics on a mongod or mongos running with security.redactClientLogData may be more difficult due to the lack of data related to a log event. See the process logging manual page for an example of the effect of security.redactClientLogData on log output.

You can enable or disable log redaction on a running mongod or mongos using the setParameter database command.

db.getSiblingDB("admin").runCommand(
  { setParameter: { redactClientLogData : "true | false" } }
)

Key Management Configuration Options

security:
   enableEncryption: <boolean>
   encryptionCipherMode: <string>
   encryptionKeyFile: <string>
   kmip:
      keyIdentifier: <string>
      rotateMasterKey: <boolean>
      serverName: <string>
      port: <string>
      clientCertificateFile: <string>
      clientCertificatePassword: <string>
      serverCAFile: <string>
security.enableEncryption

Type: boolean

Default: False

3.2 新版功能: Enables encryption for the WiredTiger storage engine. You must set to true to pass in encryption keys and configurations.

Enterprise Feature

Available in MongoDB Enterprise only.

security.encryptionCipherMode

Type: string

Default: AES256-CBC

3.2 新版功能.

The cipher mode to use for encryption at rest:

Mode Description
AES256-CBC 256-bit Advanced Encryption Standard in Cipher Block Chaining Mode
AES256-GCM 256-bit Advanced Encryption Standard in Galois/Counter Mode

Enterprise Feature

Available in MongoDB Enterprise only.

security.encryptionKeyFile

Type: string

3.2 新版功能.

The path to the local keyfile when managing keys via process other than KMIP. Only set when managing keys via process other than KMIP. If data is already encrypted using KMIP, MongoDB will throw an error.

Requires security.enableEncryption to be true.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.keyIdentifier

Type: string

3.2 新版功能.

Unique KMIP identifier for an existing key within the KMIP server. Include to use the key associated with the identifier as the system key. You can only use the setting the first time you enable encryption for the mongod instance. Requires security.enableEncryption to be true.

If unspecified, MongoDB will request that the KMIP server create a new key to utilize as the system key.

If the KMIP server cannot locate a key with the specified identifier or the data is already encrypted with a key, MongoDB will throw an error.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.rotateMasterKey

Type: boolean

Default: False

3.2 新版功能.

If true, rotate the master key and re-encrypt the internal keystore.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.serverName

Type: string

3.2 新版功能.

Hostname or IP address of key management solution running a KMIP server. Requires security.enableEncryption to be true.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.port

Type: string

Default: 5696

3.2 新版功能.

Port number the KMIP server is listening on. Requires that a security.kmip.serverName be provided. Requires security.enableEncryption to be true.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.clientCertificateFile

Type: string

3.2 新版功能.

String containing the path to the client certificate used for authenticating MongoDB to the KMIP server. Requires that a security.kmip.serverName be provided.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.clientCertificatePassword

Type: string

3.2 新版功能.

The password to decrypt the client certificate (i.e. security.kmip.clientCertificateFile), used to authenticate MongoDB to the KMIP server. Use the option only if the certificate is encrypted.

Enterprise Feature

Available in MongoDB Enterprise only.

security.kmip.serverCAFile

Type: string

3.2 新版功能.

Path to CA File. Used for validating secure client connection to KMIP server.

Enterprise Feature

Available in MongoDB Enterprise only.

security.sasl Options

security:
   sasl:
      hostName: <string>
      serviceName: <string>
      saslauthdSocketPath: <string>
security.sasl.hostName

Type: string

A fully qualified server domain name for the purpose of configuring SASL and Kerberos authentication. The SASL hostname overrides the hostname only for the configuration of SASL and Kerberos.

For mongo shell and other MongoDB tools to connect to the new hostName, see the gssapiHostName option in the mongo shell and other tools.

security.sasl.serviceName

Type: string

Registered name of the service using SASL. This option allows you 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 permits setting this option only at startup. The setParameter can not change this setting.

This option is available only in MongoDB Enterprise.

重要

Ensure that your driver supports alternate service names. For mongo shell and other MongoDB tools to connect to the new serviceName, see the gssapiServiceName option.

security.sasl.saslauthdSocketPath

Type: string

The path to the UNIX domain socket file for saslauthd.

security.ldap Options

security:
   ldap:
      servers: <string>
      bind:
         method: <string>
         saslMechanism: <string>
         queryUser: <string>
         queryPassword: <string>
         useOSDefaults: <boolean>
      transportSecurity: <string>
      timeoutMS: <int>
      userToDNMapping: <string>
      authz:
         queryTemplate: <string>
security.ldap.servers

Type: string

3.4 新版功能: Available in MongoDB Enterprise only.

Takes a quote-enclosed comma-separated string of one or more LDAP servers, each in host:port format. mongod or mongos executes LDAP operations against these servers to authenticate users or determine what actions a user is authorized to perform on a given database.

This setting can be configured on a running mongod or mongos using setParameter.

If unset, mongod or mongos cannot use LDAP authentication or authorization.

security.ldap.bind.queryUser

Type: string

3.4 新版功能: Available in MongoDB Enterprise only.

The identity with which mongod or mongos binds as, when connecting to or performing queries on an LDAP server.

Only required if any of the following are true:

  • Using LDAP authorization.
  • Using an LDAP query for security.ldap.userToDNMapping.
  • The LDAP server disallows anonymous binds

You must use queryUser with queryPassword.

If unset, mongod or mongos will not attempt to bind to the LDAP server.

This setting can be configured on a running mongod or mongos using setParameter.

注解

Windows MongoDB deployments can use bindWithOSDefaults instead of queryUser and queryPassword. You cannot specify both queryUser and bindWithOSDefaults at the same time.

security.ldap.bind.queryPassword

Type: string

3.4 新版功能: Available in MongoDB Enterprise only.

The password used to bind to an LDAP server when using queryUser. You must use queryPassword with queryUser.

If unset, mongod or mongos will not attempt to bind to the LDAP server.

This setting can be configured on a running mongod or mongos using setParameter.

注解

Windows MongoDB deployments can use --ldapBindWithOSDefaults instead of queryPassword and --ldapQueryPassword. You cannot specify both queryPassword and --ldapBindWithOSDefaults at the same time.

security.ldap.bind.useOSDefaults

Type: boolean

Default: False

3.4 新版功能: Available in MongoDB Enterprise for the Windows platform only.

Allows mongod or mongos to authenticate, or bind, using your Windows login credentials when connecting to the LDAP server.

Only required if:

Use useOSDefaults to replace --ldapQueryUser and --ldapQueryPassword.

security.ldap.bind.method

Type: string

Default: simple

3.4 新版功能: Available in MongoDB Enterprise only.

The method mongod or mongos uses to authenticate to an LDAP server. Use with queryUser and queryPassword to connect to the LDAP server.

method supports the following values:

If you specify sasl, you can configure the available SASL mechanisms using . mongod or mongos defaults to using DIGEST-MD5 mechanism.

security.ldap.bind.saslMechanisms

Type: string

Default: DIGEST-MD5

3.4 新版功能: Available in MongoDB Enterprise only.

A comma-separated list of SASL mechanisms mongod or mongos can use when authenticating to the LDAP server. The mongod or mongos and the LDAP server must agree on at least one mechanism.

Set method to sasl to use this option.

注解

A complete list of SASL mechanisms is out of scope for this documentation. See the IANA list of SASL mechanisms, as well as the documentation for your LDAP service.

security.ldap.transportSecurity

Type: string

Default: tls

3.4 新版功能: Available in MongoDB Enterprise only.

By default, mongod or mongos creates a TLS/SSL secured connection to the LDAP server.

For Linux deployments, you must configure the appropriate TLS Options in /etc/openldap/ldap.conf file. Your operating system’s package manager creates this file as part of the MongoDB Enterprise installation, via the libldap dependency. See the documentation for TLS Options in the ldap.conf OpenLDAP documentation for more complete instructions.

For Windows deployment, you must add the LDAP server CA certificates to the Windows certificate management tool. The exact name and functionality of the tool may vary depending on operating system version. Please see the documentation for your version of Windows for more information on certificate management.

Set transportSecurity to none to disable TLS/SSL between mongod or mongos and the LDAP server.

警告

Setting transportSecurity to none transmits plaintext information and possibly credentials between mongod or mongos and the LDAP server.

security.ldap.timeoutMS

Type: int

Default: 10000

3.4 新版功能: Available in MongoDB Enterprise only.

The amount of time in milliseconds mongod or mongos should wait for an LDAP server to respond to a request.

Increasing the value of timeoutMS may prevent connection failure between the MongoDB server and the LDAP server, if the source of the failure is a connection timeout. Decreasing the value of timeoutMS reduces the time MongoDB waits for a response from the LDAP server.

This setting can be configured on a running mongod or mongos using setParameter.

security.ldap.userToDNMapping

Type: string

3.4 新版功能: Available in MongoDB Enterprise only.

Maps the username provided to mongod or mongos for authentication to a LDAP Distinguished Name (DN). You may need to use userToDNMapping to transform a username into an LDAP DN in the following scenarios:

  • Performing LDAP authentication with simple LDAP binding, where users authenticate to MongoDB with usernames that are not full LDAP DNs.
  • Using an LDAP authorization query template that requires a DN.
  • Transforming the usernames of clients authenticating to Mongo DB using different authentication mechanisms (e.g. x.509, kerberos) to a full LDAP DN for authorization.

userToDNMapping expects a quote-enclosed JSON-string representing an ordered array of documents. Each document contains a regular expression match and either a substitution or ldapQuery template used for transforming the incoming username.

Each document in the array has the following form:

{
  match: "<regex>"
  substitution: "<LDAP DN>" | ldapQuery: "<LDAP Query>"
}
Field Description Example
match An ECMAScript-formatted regular expression (regex) to match against a provided username. Each parenthesis-enclosed section represents a regex capture group used by substitution or ldapQuery. "(.+)ENGINEERING" "(.+)DBA"
substitution An LDAP distinguished name (DN) formatting template that converts the authentication name matched by the match regex into a LDAP DN. Each curly bracket-enclosed numeric value is replaced by the corresponding regex capture group extracted from the authentication username via the match regex. "cn={0},ou=engineering, dc=example,dc=com"
ldapQuery A LDAP query formatting template that inserts the authentication name matched by the match regex into an LDAP query URI encoded respecting RFC4515 and RFC4516. Each curly bracket-enclosed numeric value is replaced by the corresponding regex capture group extracted from the authentication username via the match expression. mongod or mongos executes the query against the LDAP server to retrieve the LDAP DN for the authenticated user. mongod or mongos requires exactly one returned result for the transformation to be successful, or mongod or mongos skips this transformation. "ou=engineering,dc=example, dc=com??one?(user={0})"

For each document in the array, you must use either substitution or ldapQuery. You cannot specify both in the same document.

When performing authentication or authorization, mongod or mongos steps through each document in the array in the given order, checking the authentication username against the match filter. If a match is found, mongod or mongos applies the transformation and uses the output for authenticating the user. mongod or mongos does not check the remaining documents in the array.

If the given document does not match the provided authentication name, or the transformation described by the document fails, mongod or mongos continues through the list of documents to find additional matches. If no matches are found in any document, mongod or mongos returns an error.

Example

The following shows two transformation documents. The first document matches against any string ending in @ENGINEERING, placing anything preceeding the suffix into a regex capture group. The second document matches against any string ending in @DBA, placing anything preceeding the suffix into a regex capture group.

重要

You must pass the array to userToDNMapping as a string.

"[
   {
      match: "(.+)@ENGINEERING.EXAMPLE.COM",
      substitution: "cn={0},ou=engineering,dc=example,dc=com"
   },
   {
      match: "(.+)@DBA.EXAMPLE.COM",
      ldapQuery: "ou=dba,dc=example,dc=com??one?(user={0})"

   }

]"

A user with username alice@ENGINEERING.EXAMPLE.COM matches the first document. The regex capture group {0} corresponds to the string alice. The resulting output is the DN "cn=alice,ou=engineering,dc=example,dc=com".

A user with username bob@DBA.EXAMPLE.COM matches the second document. The regex capture group {0} corresponds to the string bob. The resulting output is the LDAP query "ou=dba,dc=example,dc=com??one?(user=bob)". mongod or mongos executes this query against the LDAP server, returning the result "cn=bob,ou=dba,dc=example,dc=com".

If userToDNMapping is unset, mongod or mongos applies no transformations to the username when attempting to authenticate or authorize a user against the LDAP server.

This setting can be configured on a running mongod or mongos using the setParameter database command.

注解

An explanation of RFC4515, RFC4516 or LDAP queries is out of scope for the MongoDB Documentation. Please review the RFC directly or use your preferred LDAP resource.

security.ldap.authz.queryTemplate

Type: string

3.4 新版功能: Available in MongoDB Enterprise only.

A relative LDAP query URL formatted conforming to RFC4515 and RFC4516 that mongod executes to obtain the LDAP groups to which the authenticated user belongs to. The query is relative to the host or hosts specified in --ldapServer.

Use the {USER} placeholder in the URL to substitute the authenticated username, or the transformed username if a userToDNMapping is specified.

When constructing the query URL, ensure that the order of LDAP parameters respects RFC4516:

[ dn  [ ? [attributes] [ ? [scope] [ ? [filter] [ ? [Extensions] ] ] ] ] ]

If your query includes an attribute, mongod assumes that the query retrieves a the DNs which this entity is member of.

If your query does not include an attribute, mongod assumes the query retrieves all entities which the user is member of.

For each LDAP DN returned by the query, mongod assigns the authorized user a corresponding role on the admin database. If a role on the on the admin database exactly matches the DN, mongod grants the user the roles and privileges assigned to that role. See the db.createRole() method for more information on creating roles.

Example

This LDAP query returns any groups listed in the LDAP user object’s memberOf attribute.

"{USER}?memberOf?base"

Your LDAP configuration may not include the memberOf attribute as part of the user schema, may possess a different attribute for reporting group membership, or may not track group membership through attributes. Configure your query with respect to your own unique LDAP configuration.

If unset, mongod cannot authorize users using LDAP.

This setting can be configured on a running mongod using the setParameter database command.

注解

An explanation of RFC4515, RFC4516 or LDAP queries is out of scope for the MongoDB Documentation. Please review the RFC directly or use your preferred LDAP resource.

setParameter Option

setParameter

Set MongoDB parameter or parameters described in MongoDB Server Parameters

To set parameters in the YAML configuration file, use the following format:

setParameter:
   <parameter1>: <value1>
   <parameter2>: <value2>

For example, to specify the enableLocalhostAuthBypass in the configuration file:

setParameter:
   enableLocalhostAuthBypass: false

LDAP Parameters

setParameter.ldapUserCacheInvalidationInterval

Type: int

Default: 30

For use with mongod or mongos servers using LDAP Authorization.

The interval (in seconds) mongod or mongos waits between external user cache flushes. After mongod or mongos flushes the external user cache, the next operation an LDAP-authorized user, MongoDB reacquires authorization data from the LDAP server.

Increasing the value specified increases the amount of time mongod or mongos and the LDAP server can be out of sync, but reduces the load on the LDAP server. Conversely, decreasing the value specified decreases the time mongod or mongos and the LDAP server can be out of sync while increasing the load on the LDAP server.

setParameter:
   ldapUserCacheInvalidationInterval: <int>

storage Options

storage:
   dbPath: <string>
   indexBuildRetry: <boolean>
   repairPath: <string>
   journal:
      enabled: <boolean>
      commitIntervalMs: <num>
   directoryPerDB: <boolean>
   syncPeriodSecs: <int>
   engine: <string>
   mmapv1:
      preallocDataFiles: <boolean>
      nsSize: <int>
      quota:
         enforced: <boolean>
         maxFilesPerDB: <int>
      smallFiles: <boolean>
      journal:
         debugFlags: <int>
         commitIntervalMs: <num>
   wiredTiger:
      engineConfig:
         cacheSizeGB: <number>
         journalCompressor: <string>
         directoryForIndexes: <boolean>
      collectionConfig:
         blockCompressor: <string>
      indexConfig:
         prefixCompression: <boolean>
   inMemory:
      engineConfig:
         inMemorySizeGB: <number>
storage.dbPath

Type: string

Default: /data/db on Linux and OS X, \data\db on Windows

The directory where the mongod instance stores its data.

If you installed MongoDB using a package management system, check the /etc/mongod.conf file provided by your packages to see the directory is specified.

The storage.dbPath setting is available only for mongod.

The Linux package init scripts do not expect storage.dbPath to change from the defaults. If you use the Linux packages and change storage.dbPath, you will have to use your own init scripts and disable the built-in scripts.

storage.indexBuildRetry

Type: boolean

Default: True

Specifies whether mongod rebuilds incomplete indexes on the next start up. This applies in cases where mongod restarts after it has shut down or stopped in the middle of an index build. In such cases, mongod always removes any incomplete indexes, and then, by default, attempts to rebuild them. To stop mongod from rebuilding indexes, set this option to false.

The storage.indexBuildRetry setting is available only for mongod.

Not available for mongod instances that use the in-memory storage engine.

storage.repairPath

Type: string

Default: A _tmp_repairDatabase_<num> directory under the dbPath.

The working directory that MongoDB will use during the --repair operation. When --repair completes, the storage.repairPath directory is empty, and dbPath contains the repaired files.

The storage.repairPath setting is available only for mongod.

Not available for mongod instances that use the in-memory storage engine.

storage.journal.enabled

Type: boolean

Default: true on 64-bit systems, false on 32-bit systems

Enable or disable the durability journal to ensure data files remain valid and recoverable. This option applies only when you specify the --dbpath option. The mongod enables journaling by default on 64-bit builds of versions after 2.0.

The storage.journal.enabled setting is available only for mongod.

Not available for mongod instances that use the in-memory storage engine.

If any voting member of a replica set runs without journaling (i.e. either runs an in-memory storage engine or runs with journaling disabled), you must set writeConcernMajorityJournalDefault to false.

storage.journal.commitIntervalMs

Type: number

Default: 100 or 30

3.2 新版功能.

The maximum amount of time in milliseconds that the mongod process allows between journal operations. Values can range from 1 to 500 milliseconds. Lower values increase the durability of the journal, at the expense of disk performance. The default journal commit interval is 100 milliseconds.

On MMAPv1, if the journal is on a different block device (e.g. physical volume, RAID device, or LVM volume) than the data files, the default journal commit interval is 30 milliseconds. Additionally, on MMAPv1, when a write operation with j:true is pending, mongod will reduce commitIntervalMs to a third of the set value.

On WiredTiger, the default journal commit interval is 100 milliseconds. Additionally, a write with j:true will cause an immediate sync of the journal.

The storage.journal.commitIntervalMs setting is available only for mongod.

Not available for mongod instances that use the in-memory storage engine.

storage.directoryPerDB

Type: boolean

Default: False

When true, MongoDB uses a separate directory to store data for each database. The directories are under the storage.dbPath directory, and each subdirectory name corresponds to the database name.

在 3.0 版更改: To change the storage.directoryPerDB option for existing deployments, you must restart the mongod instances with the new storage.directoryPerDB value and a new data directory (storage.dbPath value), and then repopulate the data.

  • For standalone instances, you can use mongodump on the existing instance, stop the instance, restart with the new storage.directoryPerDB value and a new data directory, and use mongorestore to populate the new data directory.
  • For replica sets, you can update in a rolling manner by stopping a secondary member, restart with the new storage.directoryPerDB value and a new data directory, and use initial sync to populate the new data directory. To update all members, start with the secondary members first. Then step down the primary, and update the stepped-down member.

The storage.directoryPerDB setting is available only for mongod.

Not available for mongod instances that use the in-memory storage engine.

storage.syncPeriodSecs

Type: number

Default: 60

The amount of time that can pass before MongoDB flushes data to the data files via an fsync operation.

Do not set this value on production systems. In almost every situation, you should use the default setting.

警告

If you set storage.syncPeriodSecs to 0, MongoDB will not sync the memory mapped files to disk.

The mongod process writes data very quickly to the journal and lazily to the data files. storage.syncPeriodSecs has no effect on the journal files or journaling.

The serverStatus command reports the background flush thread’s status via the backgroundFlushing field.

The storage.syncPeriodSecs setting is available only for mongod.

Not available for mongod instances that use the in-memory storage engine.

storage.engine

Default: wiredTiger

3.0 新版功能.

在 3.2 版更改: Starting in MongoDB 3.2, wiredTiger is the default.

The storage engine for the mongod database. Available values include:

Value Description
mmapv1 To specify the MMAPv1 Storage Engine.
wiredTiger To specify the WiredTiger Storage Engine.
inMemory

To specify the 内存存储引擎.

3.2 新版功能: Available in MongoDB Enterprise only.

If you attempt to start a mongod with a storage.dbPath that contains data files produced by a storage engine other than the one specified by storage.engine, mongod will refuse to start.

storage.mmapv1 Options

storage:
   mmapv1:
      preallocDataFiles: <boolean>
      nsSize: <int>
      quota:
         enforced: <boolean>
         maxFilesPerDB: <int>
      smallFiles: <boolean>
      journal:
         debugFlags: <int>
         commitIntervalMs: <num>
storage.mmapv1.preallocDataFiles

Type: boolean

Default: True

2.6 版后已移除.

Enable or disable the preallocation of data files. Currently the default. Exists for future compatibility and clarity.

The storage.mmapv1.preallocDataFiles setting is available only for mongod.

storage.mmapv1.nsSize

Type: integer

Default: 16

The default size for namespace files, which are files that end in .ns. Each collection and index counts as a namespace.

Use this setting to control size for newly created namespace files. This option has no impact on existing files. The maximum size for a namespace file is 2047 megabytes. The default value of 16 megabytes provides for approximately 24,000 namespaces.

The storage.mmapv1.nsSize setting is available only for mongod.

storage.mmapv1.quota.enforced

Type: Boolean

Default: false

Enable or disable the enforcement of a maximum limit for the number data files each database can have. When running with the storage.mmapv1.quota.enforced option, MongoDB has a maximum of 8 data files per database. Adjust the quota with storage.quota.maxFilesPerDB.

The storage.mmapv1.quota.enforced setting is available only for mongod.

storage.mmapv1.quota.maxFilesPerDB

Type: integer

Default: 8

The limit on the number of data files per database. storage.mmapv1.quota.maxFilesPerDB option requires that you set storage.quota.enforced.

The storage.mmapv1.quota.maxFilesPerDB setting is available only for mongod.

storage.mmapv1.smallFiles

Type: boolean

Default: False

When true, MongoDB uses a smaller default file size. The storage.mmapv1.smallFiles option reduces the initial size for data files and limits the maximum size to 512 megabytes. storage.mmapv1.smallFiles also reduces the size of each journal file from 1 gigabyte to 128 megabytes. Use storage.mmapv1.smallFiles if you have a large number of databases that each holds a small quantity of data.

The storage.mmapv1.smallFiles option can lead the mongod instance to create a large number of files, which can affect performance for larger databases.

The storage.mmapv1.smallFiles setting is available only for mongod.

storage.mmapv1.journal.debugFlags

Type: integer

Provides functionality for testing. Not for general use, and will affect data file integrity in the case of abnormal system shutdown.

The storage.mmapv1.journal.debugFlags option is available only for mongod.

storage.mmapv1.journal.commitIntervalMs

Type: number

3.2 版后已移除: MongoDB 3.2 deprecates the storage.mmapv1.journal.commitIntervalMs setting. Use storage.journal.commitIntervalMs instead.

The deprecated setting acts as an alias to the new storage.journal.commitIntervalMS setting and applies to either the MMAPv1 or the WiredTiger storage engine.

storage.wiredTiger Options

storage:
   wiredTiger:
      engineConfig:
         cacheSizeGB: <number>
         journalCompressor: <string>
         directoryForIndexes: <boolean>
      collectionConfig:
         blockCompressor: <string>
      indexConfig:
         prefixCompression: <boolean>
storage.wiredTiger.engineConfig.cacheSizeGB

Type: float

The maximum size of the internal cache that WiredTiger will use for all data.

在 3.4 版更改: Values can range from 256MB to 10TB and can be a float. In addition, the default value has also changed.

Starting in 3.4, the WiredTiger internal cache, by default, will use the larger of either:

  • 50% of RAM minus 1 GB, or
  • 256 MB.

Avoid increasing the WiredTiger internal cache size above its default value.

With WiredTiger, MongoDB utilizes both the WiredTiger internal cache and the filesystem cache.

Via the filesystem cache, MongoDB automatically uses all free memory that is not used by the WiredTiger cache or by other processes. Data in the filesystem cache is compressed.

注解

The storage.wiredTiger.engineConfig.cacheSizeGB limits the size of the WiredTiger internal cache. The operating system will use the available free memory for filesystem cache, which allows the compressed MongoDB data files to stay in memory. In addition, the operating system will use any free RAM to buffer file system blocks and file system cache.

To accommodate the additional consumers of RAM, you may have to decrease WiredTiger internal cache size.

The default WiredTiger internal cache size value assumes that there is a single mongod instance per machine. If a single machine contains multiple MongoDB instances, then you should decrease the setting to accommodate the other mongod instances.

If you run mongod in a container (e.g. lxc, cgroups, Docker, etc.) that does not have access to all of the RAM available in a system, you must set storage.wiredTiger.engineConfig.cacheSizeGB to a value less than the amount of RAM available in the container. The exact amount depends on the other processes running in the container.

storage.wiredTiger.engineConfig.journalCompressor

Default: snappy

3.0.0 新版功能.

The type of compression to use to compress WiredTiger journal data.

Available compressors are:

storage.wiredTiger.engineConfig.directoryForIndexes

Type: boolean

Default: false

3.0.0 新版功能.

When storage.wiredTiger.engineConfig.directoryForIndexes is true, mongod stores indexes and collections in separate subdirectories under the data (i.e. storage.dbPath) directory. Specifically, mongod stores the indexes in a subdirectory named index and the collection data in a subdirectory named collection.

By using a symbolic link, you can specify a different location for the indexes. Specifically, when mongod instance is not running, move the index subdirectory to the destination and create a symbolic link named index under the data directory to the new destination.

storage.wiredTiger.collectionConfig.blockCompressor

Default: snappy

3.0.0 新版功能.

The default type of compression to use to compress collection data. You can override this on a per-collection basis when creating collections.

Available compressors are:

storage.wiredTiger.collectionConfig.blockCompressor affects all collections created. If you change the value of storage.wiredTiger.collectionConfig.blockCompressor on an existing MongoDB deployment, all new collections will use the specified compressor. Existing collections will continue to use the compressor specified when they were created, or the default compressor at that time.

storage.wiredTiger.indexConfig.prefixCompression

Default: true

3.0.0 新版功能.

Enables or disables prefix compression for index data.

Specify true for storage.wiredTiger.indexConfig.prefixCompression to enable prefix compression for index data, or false to disable prefix compression for index data.

The storage.wiredTiger.indexConfig.prefixCompression setting affects all indexes created. If you change the value of storage.wiredTiger.indexConfig.prefixCompression on an existing MongoDB deployment, all new indexes will use prefix compression. Existing indexes are not affected.

storage.inmemory Options

storage:
   inMemory:
      engineConfig:
         inMemorySizeGB: <number>
storage.inMemory.engineConfig.inMemorySizeGB

Type: float

Default: 50% of physical RAM less 1 GB

在 3.4 版更改: Values can range from 256MB to 10TB and can be a float.

Maximum amount of memory to allocate for in-memory storage engine data, including indexes, oplog if the mongod is part of replica set, replica set or sharded cluster metadata, etc.

By default, the in-memory storage engine uses 50% of physical RAM minus 1 GB.

Enterprise Feature

Available in MongoDB Enterprise only.

operationProfiling Options

operationProfiling:
   slowOpThresholdMs: <int>
   mode: <string>
operationProfiling.slowOpThresholdMs

Type: integer

Default: 100

The threshold in milliseconds at which the database profiler considers a query slow. MongoDB records all slow queries to the log, even when the database profiler is off. When the profiler is on, it writes to the system.profile collection. See the profile command for more information on the database profiler.

The operationProfiling.slowOpThresholdMs setting is available only for mongod.

operationProfiling.mode

Type: string

Default: off

The level of database profiling, which inserts information about operation performance into the system.profile collection. Specify one of the following levels:

Level Setting
off Off. No profiling.
slowOp On. Only includes slow operations.
all On. Includes all operations.

Database profiling can impact database performance. Enable this option only after careful consideration.

The operationProfiling.mode setting is available only for mongod.

replication Options

replication:
   oplogSizeMB: <int>
   replSetName: <string>
   secondaryIndexPrefetch: <string>
   enableMajorityReadConcern: <boolean>
replication.oplogSizeMB

Type: integer

The maximum size in megabytes for the replication operation log (i.e., the oplog). The mongod process creates an oplog based on the maximum amount of space available. For 64-bit systems, the oplog is typically 5% of available disk space. Once the mongod has created the oplog for the first time, changing the replication.oplogSizeMB option will not affect the size of the oplog.

See Oplog大小 for more information.

The replication.oplogSizeMB setting is available only for mongod.

replication.replSetName

Type: string

The name of the replica set that the mongod is part of. All hosts in the replica set must have the same set name.

If your application connects to more than one replica set, each set should have a distinct name. Some drivers group replica set connections by replica set name.

The replication.replSetName setting is available only for mongod.

replication.secondaryIndexPrefetch

Type: string

Default: all

Storage Engine Specific Feature

replication.secondaryIndexPrefetch is only available with the mmapv1 storage engine.

The indexes that secondary members of a replica set load into memory before applying operations from the oplog. By default secondaries load all indexes related to an operation into memory before applying operations from the oplog.

Set this setting to one of the following:

Value Description
none Secondaries do not load indexes into memory.
all Secondaries load all indexes related to an operation.
_id_only Secondaries load no additional indexes into memory beyond the already existing _id index.

The replication.secondaryIndexPrefetch setting is available only for mongod.

replication.enableMajorityReadConcern

Type: boolean

Default: False

3.2 新版功能.

Enables read concern level of "majority".

sharding Options

sharding:
   clusterRole: <string>
   archiveMovedChunks: <boolean>
sharding.clusterRole

Type: string

The role that the mongod instance has in the sharded cluster. Set this setting to one of the following:

Value Description
configsvr Start this instance as a config server. The instance starts on port 27019 by default.
shardsvr Start this instance as a shard. The instance starts on port 27018 by default.

The sharding.clusterRole setting is available only for mongod.

sharding.archiveMovedChunks

Type: boolean

在 3.2 版更改: Starting in 3.2, MongoDB uses false as the default.

During chunk migration, a shard does not save documents migrated from the shard.

auditLog Options

注解

Available only in MongoDB Enterprise.

auditLog:
   destination: <string>
   format: <string>
   path: <string>
   filter: <string>
auditLog.destination

Type: string

2.6 新版功能.

When set, auditLog.destination enables auditing and specifies where mongos or mongod sends all audit events.

auditLog.destination can have one of the following values:

Value Description
syslog

Output the audit events to syslog in JSON format. Not available on Windows. Audit messages have a syslog severity level of info and a facility level of user.

The syslog message limit can result in the truncation of audit messages. The auditing system will neither detect the truncation nor error upon its occurrence.

console Output the audit events to stdout in JSON format.
file Output the audit events to the file specified in --auditPath in the format specified in --auditFormat.

注解

Available only in MongoDB Enterprise.

auditLog.format

Type: string

2.6 新版功能.

The format of the output file for auditing if destination is file. The auditLog.format option can have one of the following values:

Value Description
JSON Output the audit events in JSON format to the file specified in --auditPath.
BSON Output the audit events in BSON binary format to the file specified in --auditPath.

Printing audit events to a file in JSON format degrades server performance more than printing to a file in BSON format.

注解

Available only in MongoDB Enterprise.

auditLog.path

Type: string

2.6 新版功能.

The output file for auditing if destination has value of file. The auditLog.path option can take either a full path name or a relative path name.

注解

Available only in MongoDB Enterprise.

auditLog.filter

Type: string representation of a document

2.6 新版功能.

The filter to limit the types of operations the audit system records. The option takes a string representation of a query document of the form:

{ <field1>: <expression1>, ... }

The <field> can be any field in the audit message, including fields returned in the param document. The <expression> is a query condition expression.

To specify an audit filter, enclose the filter document in single quotes to pass the document as a string.

To specify the audit filter in a configuration file, you must use the YAML format of the configuration file.

注解

Available only in MongoDB Enterprise.

snmp Options

snmp:
   subagent: <boolean>
   master: <boolean>
snmp.subagent

Type: boolean

When snmp.subagent is true, SNMP runs as a subagent. For more information, see Monitor MongoDB With SNMP on Linux.

The snmp.subagent setting is available only for mongod.

snmp.master

Type: boolean

When snmp.master is true, SNMP runs as a master. For more information, see Monitor MongoDB With SNMP on Linux.

The snmp.master setting is available only for mongod.

Text Search Options

basisTech
basisTech.rootDirectory

Type: string

3.2 新版功能.

Specify the path to the root directory of the Basis Technology Rosette Linguistics Platform installation to support additional languages for text search operations.

Enterprise Feature

Available in MongoDB Enterprise only.

mongos-only Options

在 3.4 版更改: MongoDB 3.4 removes sharding.chunkSize and sharding.autoSplit settings.

replication:
   localPingThresholdMs: <int>

sharding:
   configDB: <string>
replication.localPingThresholdMs

Type: integer

Default: 15

The ping time, in milliseconds, that mongos uses to determine which secondary replica set members to pass read operations from clients. The default value of 15 corresponds to the default value in all of the client drivers.

When mongos receives a request that permits reads to secondary members, the mongos will:

  • Find the member of the set with the lowest ping time.

  • Construct a list of replica set members that is within a ping time of 15 milliseconds of the nearest suitable member of the set.

    If you specify a value for the replication.localPingThresholdMs option, mongos will construct the list of replica members that are within the latency allowed by this value.

  • Select a member to read from at random from this list.

The ping time used for a member compared by the replication.localPingThresholdMs setting is a moving average of recent ping times, calculated at most every 10 seconds. As a result, some queries may reach members above the threshold until the mongos recalculates the average.

See the Read Preference for Replica Sets section of the read preference documentation for more information.

sharding.configDB

Type: string

在 3.2 版更改.

The configuration servers for the sharded cluster.

Starting in MongoDB 3.2, config servers for sharded clusters can be deployed as a replica set. The replica set config servers must run the WiredTiger storage engine. MongoDB 3.2 deprecates the use of three mirrored mongod instances for config servers.

Specify the config server replica set name and the hostname and port of at least one of the members of the config server replica set.

sharding:
  configDB: <configReplSetName>/cfg1.example.net:27017, cfg2.example.net:27017,...

The mongos instances for the sharded cluster must specify the same config server replica set name but can specify hostname and port of different members of the replica set.

Windows Service Options

processManagement:
   windowsService:
      serviceName: <string>
      displayName: <string>
      description: <string>
      serviceUser: <string>
      servicePassword: <string>
processManagement.windowsService.serviceName

Type: string

Default: MongoDB

The service name of mongos or mongod when running as a Windows Service. Use this name with the net start <name> and net stop <name> operations.

You must use processManagement.windowsService.serviceName in conjunction with either the --install or --remove install option.

processManagement.windowsService.displayName

Type: string

Default: MongoDB

The name listed for MongoDB on the Services administrative application.

processManagement.windowsService.description

Type: string

Default: MongoDB Server

Run mongos or mongod service description.

You must use processManagement.windowsService.description in conjunction with the --install option.

For descriptions that contain spaces, you must enclose the description in quotes.

processManagement.windowsService.serviceUser

Type: string

The mongos or mongod service in the context of a certain user. This user must have “Log on as a service” privileges.

You must use processManagement.windowsService.serviceUser in conjunction with the --install option.

processManagement.windowsService.servicePassword

Type: string

The password for <user> for mongos or mongod when running with the --serviceUser option.

You must use processManagement.windowsService.servicePassword in conjunction with the --install option.