Mongodb参数说明

Mongodb启动命令mongod参数说明

mongod的主要参数有:

 基本配置

--------------------------------------------------------------------------------

--quiet# 安静输出
--port arg# 指定服务端口号,默认端口27017
--bind_ip arg# 绑定服务IP,若绑定127.0.0.1,则只能本机访问,不指定默认本地所有IP
--logpath arg# 指定MongoDB日志文件,注意是指定文件不是目录
--logappend# 使用追加的方式写日志
--pidfilepath arg# PID File 的完整路径,如果没有设置,则没有PID文件
--keyFile arg# 集群的私钥的完整路径,只对于Replica Set 架构有效
--unixSocketPrefix arg# UNIX域套接字替代目录,(默认为 /tmp)
--fork# 以守护进程的方式运行MongoDB,创建服务器进程
--auth# 启用验证
--cpu# 定期显示CPU的CPU利用率和iowait
--dbpath arg# 指定数据库路径
--diaglog arg# diaglog选项 0=off 1=W 2=R 3=both 7=W+some reads
--directoryperdb# 设置每个数据库将被保存在一个单独的目录
--journal# 启用日志选项,MongoDB的数据操作将会写入到journal文件夹的文件里
--journalOptions arg# 启用日志诊断选项
--ipv6# 启用IPv6选项
--jsonp# 允许JSONP形式通过HTTP访问(有安全影响)
--maxConns arg# 最大同时连接数 默认2000
--noauth# 不启用验证
--nohttpinterface# 关闭http接口,默认关闭27018端口访问
--noprealloc# 禁用数据文件预分配(往往影响性能)
--noscripting# 禁用脚本引擎
--notablescan# 不允许表扫描
--nounixsocket# 禁用Unix套接字监听
--nssize arg (=16)# 设置信数据库.ns文件大小(MB)
--objcheck# 在收到客户数据,检查的有效性,
--profile arg# 档案参数 0=off 1=slow, 2=all
--quota# 限制每个数据库的文件数,设置默认为8
--quotaFiles arg# number of files allower per db, requires --quota
--rest# 开启简单的rest API
--repair# 修复所有数据库run repair on all dbs
--repairpath arg# 修复库生成的文件的目录,默认为目录名称dbpath
--slowms arg (=100)# value of slow for profile and console log
--smallfiles# 使用较小的默认文件
--syncdelay arg (=60)# 数据写入磁盘的时间秒数(0=never,不推荐)
--sysinfo# 打印一些诊断系统信息
--upgrade# 如果需要升级数据库
 * Replicaton 参数

--------------------------------------------------------------------------------

--fastsync# 从一个dbpath里启用从库复制服务,该dbpath的数据库是主库的快照,可用于快速启用同步
--autoresync# 如果从库与主库同步数据差得多,自动重新同步,
--oplogSize arg# 设置oplog的大小(MB)
 * 主/从参数

--------------------------------------------------------------------------------

--master# 主库模式
--slave# 从库模式
--source arg# 从库 端口号
--only arg# 指定单一的数据库复制
--slavedelay arg# 设置从库同步主库的延迟时间
 * Replica set(副本集)选项:

--------------------------------------------------------------------------------

--replSet arg# 设置副本集名称
 * Sharding(分片)选项

--------------------------------------------------------------------------------
--configsvr# 声明这是一个集群的config服务,默认端口27019,默认目录/data/configdb
--shardsvr# 声明这是一个集群的分片,默认端口27018
--noMoveParanoia# 关闭偏执为moveChunk数据保存

# 上述参数都可以写入 mongod.conf 配置文档里例如:

dbpath = /data/mongodb
logpath = /data/mongodb/mongodb.log
logappend = true
port = 27017
fork = true
auth = true
 

e.g:./mongod -shardsvr -replSet shard1 -port 16161 -dbpath /data/mongodb/data/shard1a -oplogSize 100 -logpath /data/mongodb/logs/shard1a.log -logappend -fork -rest



mongod

Synopsis

mongod is the primary daemon process for the MongoDBsystem. It handles data requests, manages data format, and performsbackground management operations.

This document provides a complete overview of all command line optionsfor mongod. These options are primarily useful for testingpurposes. In common operation, use theconfiguration fileoptions to control the behavior ofyour database, which is fully capable of all operations describedbelow.

Options

Core Options

mongod

--help , -h

Returns information on the options and use of mongod.

--version

Returns the mongod release number.

--config <filename> , -f

Specifies a configuration file for runtime configuration options. Theconfiguration file is the preferred method for runtime configuration ofmongod. The options are equivalent to the command-lineconfiguration options. See Configuration File Options formore information.

Ensure the configuration file uses ASCII encoding. The mongodinstance does not support configuration files with non-ASCII encoding,including UTF-8.

--verbose , -v

Increases the amount of internal reporting returned on standard outputor in log files. Increase the verbosity with the-v form byincluding the option multiple times, (e.g.-vvvvv.)

--quiet

Runs the mongod in a quiet mode that attempts to limit the amountof output. This option suppresses:

  • output from database commands
  • replication activity
  • connection accepted events
  • connection closed events
--port <port>

Default: 27017

Specifies the TCP port on which the MongoDB instance listens forclient connections.

--bind_ip <ip address>

Default: All interfaces. .. versionchanged:: 2.6.0 The deb andrpm packages include a default configuration file that sets{{role}} to127.0.0.1.

Specifies the IP address that mongod binds to in order to listenfor connections from applications. You may attachmongod to anyinterface. When attachingmongod to a publicly accessibleinterface, ensure that you have implemented proper authentication andfirewall restrictions to protect the integrity of your database.

--maxConns <number>

The maximum number of simultaneous connections that mongod willaccept. This setting has no effect if it is higher than your operatingsystem’s configured maximum connection tracking threshold.

Changed in version 2.6: MongoDB removed the upward limit on themaxIncomingConnections setting.

--syslog

Sends all logging output to the host’s syslog system ratherthan to standard output or to a log file. , as with--logpath.

The --syslog option is not supported on Windows.

--syslogFacility <string>

Default: user

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

--logpath <path>

Sends all diagnostic logging information to a log file instead of tostandard output or to the host’ssyslog system. MongoDB createsthe log file at the path you specify.

By default, MongoDB overwrites the log file when the process restarts.To instead append to the log file, set the--logappend option.

--logappend

Appends new entries to the end of the log file rather than overwritingthe content of the log when themongod instance restarts.

--timeStampFormat <string>

Default: iso8601-local

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

ValueDescription
ctimeDisplays timestamps as WedDec 3118:17:54.811.
iso8601-utcDisplays timestamps in Coordinated Universal Time (UTC) in theISO-8601 format. For example, for New York at the start of theEpoch:1970-01-01T00:00:00.000Z
iso8601-localDisplays timestamps in local time in the ISO-8601format. For example, for New York at the start of the Epoch:1969-12-31T19:00:00.000+0500
--diaglog <value>

Default: 0

Deprecated since version 2.6.

--diaglog is for internal use and not intended for most users.

Creates a very verbose diagnostic log for troubleshooting andrecording various errors. MongoDB writes these log files in thedbPath directory in a series of files that begin with thestring diaglog and end with the initiation time of the logging as ahex string.

The specified value configures the level of verbosity:

ValueSetting
0Off. No logging.
1Log write operations.
2Log read operations.
3Log both read and write operations.
7Log write and some read operations.

You can use the mongosniff tool to replay this output forinvestigation. Given a typical diaglog file located at/data/db/diaglog.4f76a58c, you might use a command in the followingform to read these files:

  mongosniff --source DIAGLOG /data/db/diaglog.4f76a58c

.. warning::

   Setting the diagnostic level to ``0`` will cause :program:`mongod`
   to stop writing data to the :term:`diagnostic log` file. However,
   the :program:`mongod` instance will continue to keep the file open,
   even if it is no longer writing data to the file. If you want to
   rename, move, or delete the diagnostic log you must cleanly shut
   down the :program:`mongod` instance before doing so.
--traceExceptions

For internal diagnostic use only.

--pidfilepath <path>

Specifies a file location to hold the process ID of the mongodprocess. This is useful for tracking the mongod process incombination with the --fork option. Without a specified--pidfilepath option, the process creates no PID file.

--keyFile <file>

Specifies the path to a key file to that stores the shared secretthat MongoDB processes use to authenticate to each other in asharded cluster or replica set.--keyFile implies--auth. See Authentication Between MongoDB Instances for moreinformation.

--setParameter <options>

Specifies one of the MongoDB parameters described inMongoDB Server Parameters. You can specify multiplesetParameterfields.

--httpinterface

New in version 2.6.

Enables the HTTP interface. Enabling the interface can increasenetwork exposure.

Leave the HTTP interface disabled for production deployments. If youdo enable this interface, you should only allow trusted clients toaccess this port. SeeFirewalls.

Note

In MongoDB Enterprise, the HTTP Console does not support KerberosAuthentication.

--nohttpinterface

Deprecated since version 2.6: MongoDB disables the HTTP interface by default.

Disables the HTTP interface.

Do not use in conjunction with --rest or --jsonp.

Note

In MongoDB Enterprise, the HTTP Console does not support KerberosAuthentication.

--nounixsocket

Disables listening on the UNIX domain socket. The mongod processalways listens on the UNIX socket unless one of the following is true:

New in version 2.6: mongod installed from official.deb and .rpm packageshave the bind_ip configuration set to 127.0.0.1 bydefault.

--unixSocketPrefix <path>

Default: /tmp

The path for the UNIX socket. If this option has no value, themongod process creates a socket with/tmp as a prefix. MongoDBcreates and listens on a UNIX socket unless one of the following is true:

--fork

Enables a daemon mode that runs themongod process in thebackground. By defaultmongod does not run as a daemon:typically you will runmongod as a daemon, either by using--fork or by using a controlling process that handles thedaemonization process (e.g. as withupstart and systemd).

--auth

Enables authorization to control user’s access to database resourcesand operations. When authorization is enabled, MongoDB requires allclients to authenticate themselves first in order to determine theaccess for the client.

Configure users via the mongo shell. If no users exist, the localhost interfacewill continue to have access to the database until you createthe first user.

See Securityfor more information.

--noauth

Disables authentication. Currently the default. Exists for futurecompatibility and clarity.

--ipv6

Enables IPv6 support and allows the mongod to connect to theMongoDB instance using an IPv6 network. All MongoDB programs andprocesses disable IPv6 support by default.

--jsonp

Permits JSONP access via an HTTP interface. Enabling theinterface can increase network exposure. The--jsonp option enables theHTTP interface, even if theHTTPinterfaceoption is disabled.

--rest

Enables the simple REST API. Enabling theREST APIenables the HTTP interface, even if theHTTPinterface option is disabled, and as a result can increasenetwork exposure.

--slowms <value>

Default: 100

The threshold in milliseconds at which the database profiler considers aquery slow. MongoDB records all slow queries to the log, even when thedatabase profiler is off. When the profiler is on, it writes to thesystem.profile collection. See the profile command formore information on the database profiler.

--profile <level>

Default: 0

Changes the level of database profiling, which inserts information aboutoperation performance into standard output or a log file. Specify oneof the following levels:

LevelSetting
0Off. No profiling.
1On. Only includes slow operations.
2On. Includes all operations.

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

--cpu

Forces the mongod process to report the percentage of CPU time inwrite lock. The process generates output every four seconds and writesthe data to standard output or, if you are using thesystemLog.pathoption, to the log file.

--sysinfo

Returns diagnostic system information and then exits. Theinformation provides the page size, the number of physical pages,and the number of available physical pages.

--dbpath <path>

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

The directory where the mongod instance stores its data. If youinstalled MongoDB using a package management system, check the/etc/mongodb.conf file provided by your packages to see whichdirectory is specified.

--directoryperdb

Stores each database’s files in its own folder in the datadirectory. When applied to an existing system, thedirectoryPerDB option alters the storage pattern of the datadirectory.

Use this option in conjunction with your file system and deviceconfiguration so that MongoDB will store data on a number of distinctdisk devices to increase write throughput or disk capacity.

Warning

To enable this option for an existing system, migrate thedatabase-specific data files to the new directory structure beforeenablingdirectoryPerDB. Database-specific data filesbegin with the name of an existing database and end with either“ns” or a number. For example, the following data directoryincludes files for the local and test databases:

journal
mongod.lock
local.0
local.1
local.ns
test.0
test.1
test.ns

After migration, the data directory would have the following structure:

journal
mongod.lock
local/local.0
local/local.1
local/local.ns
test/test.0
test/test.1
test/test.ns
--noIndexBuildRetry

Stops the mongod from rebuilding incomplete indexes on the nextstart up. This applies in cases where themongod restarts after ithas shut down or stopped in the middle of an index build. In such cases,themongod always removes any incomplete indexes, and then also, bydefault, attemps to rebuild them. To stop themongod fromrebuilding incomplete indexes on start up, include this option on thecommand-line.

--noprealloc

Disables the preallocation of data files. This shortens thestart up time in some cases and can cause significant performancepenalties during normal operations.

--nssize <value>

Default: 16

Specifies the default size for namespace files, which are files that endin .ns. Each collection and index counts as a namespace.

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

--quota

Enables a maximum limit for the number data files each database canhave. When running with the--quota option, MongoDB has a maximum of 8data files per database. Adjust the quota with--quotaFiles.

--quotaFiles <number>

Default: 8

Modifies the limit on the number of data files per database. --quotaFilesoption requires that you set--quota.

--smallfiles

Sets MongoDB to use a smaller default file size. The --smallfiles optionreduces the initial size for data files and limits the maximum size to512 megabytes.--smallfiles also reduces the size of eachjournalfile from 1 gigabyte to 128 megabytes. Use--smallfiles if you have a largenumber of databases that each holds a small quantity of data.

The --smallfiles option can lead themongod instance to create a largenumber of files, which can affect performance for larger databases.

--syncdelay <value>

Default: 60

Controls how much time can pass before MongoDB flushes data to the datafiles via anfsync operation.Do not set this value onproduction systems. In almost every situation, you should use thedefault setting.

Warning

If you set --syncdelay to0, MongoDB will not sync thememory mapped files to disk.

The mongod process writes data very quickly to the journal andlazily to the data files.syncPeriodSecs has no effect on thejournal files or journaling.

The serverStatus command reports the background flushthread’s status via thebackgroundFlushing field.

--upgrade

Upgrades the on-disk data format of the files specified by the--dbpath to the latest version, if needed.

This option only affects the operation of the mongod if the datafiles are in an old format.

In most cases you should not set this value, so you can exercise themost control over your upgrade process. See the MongoDBrelease notes (on the download page) for moreinformation about the upgrade process.

--repair

Runs a repair routine on all databases. This is equivalentto shutting down and running therepairDatabase databasecommand on all databases.

Warning

During normal operations, only use the repairDatabasecommand and wrappers includingdb.repairDatabase() in themongo shell and mongod --repair, to compactdatabase files and/or reclaim disk space. Be aware that theseoperations remove and do not save any corrupt data during therepair process.

If you are trying to repair a replica set member, and youhave access to an intact copy of your data (e.g. a recent backup oran intact member of thereplica set), you should restorefrom that intact copy, andnot use repairDatabase.

When using journaling, there is almost neverany need to runrepairDatabase. In the event of anunclean shutdown, the server will be able restore the data filesto a pristine state automatically.

Changed in version 2.1.2.

If you run the repair option and have data in a journal file, themongod instance refuses to start. In these cases you should startthemongod without the--repair option, which allows themongod to recover data from the journal. This completes morequickly and is more likely to produce valid data files. To continue therepair operation despite the journal files, shut down themongodcleanly and restart with the--repair option.

The --repair option copies data from the source data files into new datafiles in therepairPath and then replaces the original datafiles with the repaired data files. IfrepairPath is on thesame device asdbPath, you may interrupt amongodrunning the --repair option without affecting the integrity of the data set.

--repairpath <path>

Default: A _tmp directory within the path specified by thedbPath option.

Specifies the root directory containing MongoDB data files to usefor the --repair operation.

--objcheck

Forces the mongod to validate all requests from clients uponreceipt to ensure that clients never insert invalid documents into thedatabase. For objects with a high degree of sub-document nesting, the--objcheck option can have a small impact on performance. You can set--noobjcheck to disable object checking at runtime.

Changed in version 2.4: MongoDB enables the--objcheck option by default in order to preventany client from inserting malformed or invalid BSON into a MongoDBdatabase.

--noobjcheck

New in version 2.4.

Disables the default document validation that MongoDB performs on allincoming BSON documents.

--noscripting

Disables the scripting engine.

--notablescan

Forbids operations that require a table scan.

--journal

Enables the durability journal to ensure data files remain validand recoverable. This option applies only when you specify the--dbpath option. The mongod enables journaling by defaulton 64-bit builds of versions after 2.0.

--nojournal

Disables the durability journaling. The mongod instanceenables journaling by default in 64-bit versions after v2.0.

--journalOptions <arguments>

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

--journalCommitInterval <value>

Default: 100 or 30

The maximum amount of time the mongod process allows betweenjournal operations. Values can range from 2 to 300 milliseconds. Lowervalues increase the durability of the journal, at the expense of diskperformance.

The default journal commit interval is 100 milliseconds if a singleblock device (e.g. physical volume, RAID device, or LVM volume) containsboth the journal and the data files.

If the journal is on a different block device than the data files thedefault journal commit interval is 30 milliseconds.

To force mongod to commit to the journal more frequently, youcan specifyj:true. When a write operation with j:true ispending, mongod will reduce commitIntervalMsto a third of the set value.

--shutdown

Used in control scripts, the--shutdown optioncleanly and safely terminates themongod process. When invokingmongod with this option you must set the--dbpath optioneither directly or by way of theconfiguration file and the --config option.

The --shutdown option is available only on Linux systems.

Replication Options

--replSet <setname>

Configures replication. Specify a replica set name as an argument tothis set. All hosts in the replica set must have the same set name.

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

--oplogSize <value>

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

--replIndexPrefetch

Default: all

New in version 2.2.

Determines which indexes secondary members of areplicaset load into memory before applying operations from the oplog. Bydefault secondaries load all indexes related to an operation into memorybefore applying operations from the oplog. This option can have one ofthe following values:

ValueDescription
noneSecondaries do not load indexes into memory.
allSecondaries load all indexes related to an operation.
_id_onlySecondaries load no additional indexes into memory beyond thealready existing_id index.

Master-Slave Replication

These options provide access to conventional master-slave databasereplication. While this functionality remains accessible in MongoDB,replica sets are the preferred configuration for database replication.

--master

Configures the mongod to run as a replicationmaster.

--slave

Configures the mongod to run as a replicationslave.

--source <host><:port>

For use with the --slave option, the--source optiondesignates the server that this instance will replicate.

--only <arg>

For use with the --slave option, the--only optionspecifies only a single database to replicate.

--slavedelay <value>

For use with the --slave option, the--slavedelayoption configures a “delay” in seconds, for this slave to wait toapply operations from themaster node.

--autoresync

For use with the --slave option. When set,the--autoresync option allows this slave to automaticallyresync if it is more than 10 seconds behind the master. Thissetting may be problematic if the--oplogSize specifiesa too small oplog.

If the oplog is not large enough to store the difference inchanges between the master’s current state and the state of the slave,this instance will forcibly resync itself unnecessarily. If you don’tspecify--autoresync, the slave will not attempt an automatic resync morethan once in a ten minute period.

--fastsync

In the context of replica set replication, set this optionif you have seeded this member with a snapshot of thedbpath of another member of the set. Otherwise themongod will attempt to perform an initial sync,as though the member were a new member.

Warning

If the data is not perfectly synchronized andthe mongod starts with fastsync, then thesecondary or slave will be permanently out of sync with theprimary, which may cause significant consistency problems.

Sharded Cluster Options

--configsvr

Declares that this mongod instance serves as theconfig database of a sharded cluster. When running withthis option, clients will not be able to write data to any databaseother thanconfig and admin. The default port for amongod with this option is27019 and the default--dbpath directory is /data/configdb, unlessspecified.

Changed in version 2.2: The --configsvr option also sets--smallfiles.

Changed in version 2.4: The --configsvr option creates a localoplog.

Do not use the --configsvr option with--replSet or--shardsvr. Config servers cannot be a shardserver or part of a replica set.

--shardsvr

Configures this mongod instance as a shard in apartitioned cluster. The default port for these instances is27018. The only effect of--shardsvr is to changethe port number.

--moveParanoia

New in version 2.4.

During chunk migrations, the --moveParanoia option forces themongod instances to save to themoveChunk directory ofthe storage.dbPath all the documents migrated from thisshard. MongoDB does not delete data stored inmoveChunk.

Prior to 2.4, --moveParanoia was the default behavior of MongoDB.

SSL Options

See

Configure mongod and mongos for SSL for fulldocumentation of MongoDB’s support.

--sslOnNormalPorts

Deprecated since version 2.6.

Enables SSL for mongod.

With --sslOnNormalPorts, amongod requires SSL encryption for allconnections on the default MongoDB port, or the port specified by--port. By default, --sslOnNormalPorts isdisabled.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslMode <mode>

New in version 2.6.

Enables SSL or mixed SSL on a port. The argument to the --sslMode optioncan be one of the following:

ValueDescription
disabledThe server does not use SSL.
allowSSLConnections between servers do not use SSL. For incomingconnections, the server accepts both SSL and non-SSL.
preferSSLConnections between servers use SSL. For incomingconnections, the server accepts both SSL and non-SSL.
requireSSLThe server uses and accepts only SSL encrypted connections.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslPEMKeyFile <filename>

New in version 2.2.

Specifies the .pem file that contains both the SSL certificateand key. Specify the file name of the.pem file using relativeor absolute paths.

When SSL is enabled, you must specify --sslPEMKeyFile.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslPEMKeyPassword <value>

New in version 2.2.

Specifies the password to de-crypt the certificate-key file (i.e.--sslPEMKeyFile). Use the--sslPEMKeyPassword option only if thecertificate-key file is encrypted. In all cases, themongod willredact the password from all logging and reporting output.

Changed in version 2.6: If the private key in the PEM file is encrypted and you do notspecify the--sslPEMKeyPassword option, themongod will prompt for apassphrase. SeeSSL Certificate Passphrase.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--clusterAuthMode <option>

Default: keyFile

New in version 2.6.

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

ValueDescription
keyFileUse a keyfile for authentication.Accept only keyfiles.
sendKeyFileFor rolling upgrade purposes. Send a keyfile forauthentication but can accept both keyfiles and x.509certificates.
sendX509For rolling upgrade purposes. Send the x.509 certificate forauthentication but can accept both keyfiles and x.509certificates.
x509Recommended. Send the x.509 certificate for authentication andaccept only x.509 certificates.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslClusterFile <filename>

New in version 2.6.

Specifies the .pem file that contains the x.509 certificate-keyfile formembership authenticationfor the cluster or replica set.

If --sslClusterFile does not specify the.pem file for internal clusterauthentication, the cluster uses the.pem file specified in the--sslPEMKeyFile option.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslClusterPassword <value>

New in version 2.6.

Specifies the password to de-crypt the x.509 certificate-key filespecified with--sslClusterFile. Use the --sslClusterPassword option onlyif the certificate-key file is encrypted. In all cases, themongodwill redact the password from all logging and reporting output.

If the x.509 key file is encrypted and you do not specify the--sslClusterPassword option, the mongod will prompt for a passphrase. SeeSSL Certificate Passphrase.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslCAFile <filename>

New in version 2.4.

Specifies the .pem file that contains the root certificate chainfrom the Certificate Authority. Specify the file name of the.pem file using relative or absolute paths.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslCRLFile <filename>

New in version 2.4.

Specifies the .pem file that contains the Certificate RevocationList. Specify the file name of the.pem file using relative orabsolute paths.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslAllowInvalidCertificates

New in version 2.6.

Bypasses the validation checks for SSL certificates on other serversin the cluster and allows the use of invalid certificates. When usingtheallowInvalidCertificates setting, MongoDBlogs as a warning the use of the invalid certificate.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslWeakCertificateValidation

New in version 2.4.

Disables the requirement for SSL certificate validation that--sslCAFile enables. With the--sslWeakCertificateValidation option, themongodwill accept connections when the client does not present a certificatewhen establishing the connection.

If the client presents a certificate and the mongod has --sslWeakCertificateValidationenabled, themongod will validate the certificate using the rootcertificate chain specified by--sslCAFile and reject clientswith invalid certificates.

Use the --sslWeakCertificateValidation option if you have a mixed deployment that includesclients that do not or cannot present certificates to themongod.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslFIPSMode

New in version 2.4.

Directs the mongod to use the FIPS mode of the installed OpenSSLlibrary. Your system must have a FIPS compliant OpenSSL library to usethe--sslFIPSMode option.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

Audit Options

--auditDestination

New in version 2.6.

Enables auditing. The --auditDestination option can have one of the following values:

ValueDescription
syslog

Output the audit events to syslog in JSON format. Not available onWindows. Audit messages have a syslog severity level ofinfoand a facility level of user.

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

consoleOutput the audit events to stdout in JSON format.
fileOutput the audit events to the file specified in--auditPath in the format specified in--auditFormat.

Note

The audit system isavailable only in MongoDB Enterprise.

--auditFormat

New in version 2.6.

Specifies the format of the output file if --auditDestinationisfile. The --auditFormat option can have one of the following values:

ValueDescription
JSONOutput the audit events in JSON format to the file specifiedin --auditPath.
BSONOutput the audit events in BSON binary format to the filespecified in --auditPath.

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

Note

The audit system isavailable only in MongoDB Enterprise.

--auditPath

New in version 2.6.

Specifies the output file for auditing if --auditDestinationhas value offile. The --auditPath option can take either a full pathname or a relative path name.

Note

The audit system isavailable only in MongoDB Enterprise.

--auditFilter

New in version 2.6.

Specifies the filter to limit the types of operations the audit system records. The optiontakes a document of the form:

{ atype: <expression> }

For authentication operations, the option can also take a document ofthe form:

{ atype: <expression>, "param.db": <database> }

Note

The audit system isavailable only in MongoDB Enterprise.

SNMP Options

--snmp-subagent

Runs SNMP as a subagent. For more information, seeMonitor MongoDB With SNMP on Linux.

--snmp-master

Runs SNMP as a master. For more information, seeMonitor MongoDB With SNMP on Linux.



mongos

Synopsis

mongos for “MongoDB Shard,” is a routing service forMongoDB shard configurations that processes queries from theapplication layer, and determines the location of this data in thesharded cluster, in order to complete these operations.From the perspective of the application, amongos instance behaves identically to any other MongoDBinstance.

Options

Core Options

mongos

--help , -h

Returns information on the options and use of mongos.

--version

Returns the mongos release number.

--config <filename> , -f

Specifies a configuration file for runtime configuration options. Theconfiguration file is the preferred method for runtime configuration ofmongos. The options are equivalent to the command-lineconfiguration options. See Configuration File Options formore information.

Ensure the configuration file uses ASCII encoding. The mongosinstance does not support configuration files with non-ASCII encoding,including UTF-8.

--verbose , -v

Increases the amount of internal reporting returned on standard outputor in log files. Increase the verbosity with the-v form byincluding the option multiple times, (e.g.-vvvvv.)

--quiet

Runs the mongos in a quiet mode that attempts to limit the amountof output. This option suppresses:

  • output from database commands
  • replication activity
  • connection accepted events
  • connection closed events
--port <port>

Default: 27017

Specifies the TCP port on which the MongoDB instance listens forclient connections.

--bind_ip <ip address>

Default: All interfaces. .. versionchanged:: 2.6.0 The deb andrpm packages include a default configuration file that sets{{role}} to127.0.0.1.

Specifies the IP address that mongos binds to in order to listenfor connections from applications. You may attachmongos to anyinterface. When attachingmongos to a publicly accessibleinterface, ensure that you have implemented proper authentication andfirewall restrictions to protect the integrity of your database.

--maxConns <number>

Specifies the maximum number of simultaneous connections thatmongos will accept. This setting will have no effect if thevalue of this setting is higher than your operating system’s configuredmaximum connection tracking threshold.

This setting is particularly useful for mongos if youhave a client that creates a number of connections but allows themto timeout rather than close the connections. When you setmaxIncomingConnections, ensure the value is slightlyhigher than the size of the connection pool or the total number ofconnections to prevent erroneous connection spikes from propagatingto the members of asharded cluster.

Changed in version 2.6: MongoDB removed the upward limit on themaxIncomingConnections setting.

--syslog

Sends all logging output to the host’s syslog system ratherthan to standard output or to a log file. , as with--logpath.

The --syslog option is not supported on Windows.

--syslogFacility <string>

Default: user

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

--logpath <path>

Sends all diagnostic logging information to a log file instead of tostandard output or to the host’ssyslog system. MongoDB createsthe log file at the path you specify.

By default, MongoDB overwrites the log file when the process restarts.To instead append to the log file, set the--logappend option.

--logappend

Appends new entries to the end of the log file rather than overwritingthe content of the log when themongos instance restarts.

--timeStampFormat <string>

Default: iso8601-local

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

ValueDescription
ctimeDisplays timestamps as WedDec 3118:17:54.811.
iso8601-utcDisplays timestamps in Coordinated Universal Time (UTC) in theISO-8601 format. For example, for New York at the start of theEpoch:1970-01-01T00:00:00.000Z
iso8601-localDisplays timestamps in local time in the ISO-8601format. For example, for New York at the start of the Epoch:1969-12-31T19:00:00.000+0500
--pidfilepath <path>

Specifies a file location to hold the process ID of the mongosprocess. This is useful for tracking the mongos process incombination with the --fork option. Without a specified--pidfilepath option, the process creates no PID file.

--keyFile <file>

Specifies the path to a key file to that stores the shared secretthat MongoDB processes use to authenticate to each other in asharded cluster or replica set.--keyFile implies--auth. See Authentication Between MongoDB Instances for moreinformation.

--setParameter <options>

Specifies one of the MongoDB parameters described inMongoDB Server Parameters. You can specify multiplesetParameterfields.

--httpinterface

New in version 2.6.

Enables the HTTP interface. Enabling the interface can increasenetwork exposure.

Leave the HTTP interface disabled for production deployments. If youdo enable this interface, you should only allow trusted clients toaccess this port. SeeFirewalls.

Note

In MongoDB Enterprise, the HTTP Console does not support KerberosAuthentication.

--nounixsocket

Disables listening on the UNIX domain socket. The mongos processalways listens on the UNIX socket unless one of the following is true:

New in version 2.6: mongos installed from official.deb and .rpm packageshave the bind_ip configuration set to 127.0.0.1 bydefault.

--unixSocketPrefix <path>

Default: /tmp

The path for the UNIX socket. If this option has no value, themongos process creates a socket with/tmp as a prefix. MongoDBcreates and listens on a UNIX socket unless one of the following is true:

--fork

Enables a daemon mode that runs themongos process in thebackground. By defaultmongos does not run as a daemon:typically you will runmongos as a daemon, either by using--fork or by using a controlling process that handles thedaemonization process (e.g. as withupstart and systemd).

Sharded Cluster Options

--configdb <config1>,<config2>,<config3>

Specifies the configuration database for thesharded cluster. You must specify either 1 or 3 configurationservers, in a comma separated list.

All mongos instancesmust specify the hosts in the--configdb option in the in the same order.

If your configuration databases reside in more that one data center,order the hosts so that the config database that is closest to themajority of yourmongos instances is first servers in thelist.

Warning

Never remove a config server from this setting, even if the configserver is not available or offline.

--localThreshold

Default: 15

Affects the logic that mongos uses when selectingreplica set members to pass read operations to from clients.Specify a value in milliseconds. The default value of 15corresponds to the default value in all of the client drivers.

When mongos receives a request that permits reads tosecondary 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 of15 milliseconds of the nearest suitable member of the set.

    If you specify a value for the --localThreshold option,mongos willconstruct the list of replica members that are within the latencyallowed by this value.

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

The ping time used for a member compared by the --localThreshold setting is amoving average of recent ping times, calculated at most every 10seconds. As a result, some queries may reach members above the thresholduntil themongos recalculates the average.

See the Member Selectionsection of the read preferencedocumentation for more information.

--upgrade

Updates the meta data format used by the config database.

--chunkSize <value>

Default: 64

Determines the size in megabytes of each chunk in thesharded cluster. A size of 64 megabytes is ideal in mostdeployments: larger chunk size can lead to uneven data distribution;smaller chunk size can lead to inefficient movement of chunks betweennodes.

This option affects chunk size only when you initialize the clusterfor the first time. If you later modify the option, the new value has noeffect. See theModify Chunk Size in a Sharded Clusterprocedure if you need to change the chunk size on an existing shardedcluster.

--noAutoSplit

Prevents mongos from automatically inserting metadata splitsin asharded collection. If set on allmongos instances, this prevents MongoDB from creating newchunks as the data in a collection grows.

Because any mongos in a cluster can create a split, tototally disable splitting in a cluster you must set--noAutoSplit on allmongos.

Warning

With --noAutoSplit enabled, the data in your shardedcluster may become imbalanced over time. Enable with caution.

SSL Options

See

Configure mongod and mongos for SSL for fulldocumentation of MongoDB’s support.

--sslOnNormalPorts

Deprecated since version 2.6.

Enables SSL for mongos.

With --sslOnNormalPorts, amongos requires SSL encryption for allconnections on the default MongoDB port, or the port specified by--port. By default, --sslOnNormalPorts isdisabled.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslMode <mode>

New in version 2.6.

Enables SSL or mixed SSL on a port. The argument to the --sslMode optioncan be one of the following:

ValueDescription
disabledThe server does not use SSL.
allowSSLConnections between servers do not use SSL. For incomingconnections, the server accepts both SSL and non-SSL.
preferSSLConnections between servers use SSL. For incomingconnections, the server accepts both SSL and non-SSL.
requireSSLThe server uses and accepts only SSL encrypted connections.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslPEMKeyFile <filename>

New in version 2.2.

Specifies the .pem file that contains both the SSL certificateand key. Specify the file name of the.pem file using relativeor absolute paths.

When SSL is enabled, you must specify --sslPEMKeyFile.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslPEMKeyPassword <value>

New in version 2.2.

Specifies the password to de-crypt the certificate-key file (i.e.--sslPEMKeyFile). Use the--sslPEMKeyPassword option only if thecertificate-key file is encrypted. In all cases, themongos willredact the password from all logging and reporting output.

Changed in version 2.6: If the private key in the PEM file is encrypted and you do notspecify the--sslPEMKeyPassword option, themongos will prompt for apassphrase. SeeSSL Certificate Passphrase.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--clusterAuthMode <option>

Default: keyFile

New in version 2.6.

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

ValueDescription
keyFileUse a keyfile for authentication.Accept only keyfiles.
sendKeyFileFor rolling upgrade purposes. Send a keyfile forauthentication but can accept both keyfiles and x.509certificates.
sendX509For rolling upgrade purposes. Send the x.509 certificate forauthentication but can accept both keyfiles and x.509certificates.
x509Recommended. Send the x.509 certificate for authentication andaccept only x.509 certificates.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslClusterFile <filename>

New in version 2.6.

Specifies the .pem file that contains the x.509 certificate-keyfile formembership authenticationfor the cluster or replica set.

If --sslClusterFile does not specify the.pem file for internal clusterauthentication, the cluster uses the.pem file specified in the--sslPEMKeyFile option.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslClusterPassword <value>

New in version 2.6.

Specifies the password to de-crypt the x.509 certificate-key filespecified with--sslClusterFile. Use the --sslClusterPassword option onlyif the certificate-key file is encrypted. In all cases, themongoswill redact the password from all logging and reporting output.

If the x.509 key file is encrypted and you do not specify the--sslClusterPassword option, the mongos will prompt for a passphrase. SeeSSL Certificate Passphrase.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslCAFile <filename>

New in version 2.4.

Specifies the .pem file that contains the root certificate chainfrom the Certificate Authority. Specify the file name of the.pem file using relative or absolute paths.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslCRLFile <filename>

New in version 2.4.

Specifies the .pem file that contains the Certificate RevocationList. Specify the file name of the.pem file using relative orabsolute paths.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslWeakCertificateValidation

New in version 2.4.

Disables the requirement for SSL certificate validation that--sslCAFile enables. With the--sslWeakCertificateValidation option, themongoswill accept connections when the client does not present a certificatewhen establishing the connection.

If the client presents a certificate and the mongos has --sslWeakCertificateValidationenabled, themongos will validate the certificate using the rootcertificate chain specified by--sslCAFile and reject clientswith invalid certificates.

Use the --sslWeakCertificateValidation option if you have a mixed deployment that includesclients that do not or cannot present certificates to themongos.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslAllowInvalidCertificates

New in version 2.6.

Bypasses the validation checks for SSL certificates on other serversin the cluster and allows the use of invalid certificates. When usingtheallowInvalidCertificates setting, MongoDBlogs as a warning the use of the invalid certificate.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslFIPSMode

New in version 2.4.

Directs the mongos to use the FIPS mode of the installed OpenSSLlibrary. Your system must have a FIPS compliant OpenSSL library to usethe--sslFIPSMode option.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

Audit Options

--auditDestination

New in version 2.6.

Enables auditing. The --auditDestination option can have one of the following values:

ValueDescription
syslog

Output the audit events to syslog in JSON format. Not available onWindows. Audit messages have a syslog severity level ofinfoand a facility level of user.

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

consoleOutput the audit events to stdout in JSON format.
fileOutput the audit events to the file specified in--auditPath in the format specified in--auditFormat.

Note

The audit system isavailable only in MongoDB Enterprise.

--auditFormat

New in version 2.6.

Specifies the format of the output file if --auditDestinationisfile. The --auditFormat option can have one of the following values:

ValueDescription
JSONOutput the audit events in JSON format to the file specifiedin --auditPath.
BSONOutput the audit events in BSON binary format to the filespecified in --auditPath.

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

Note

The audit system isavailable only in MongoDB Enterprise.

--auditPath

New in version 2.6.

Specifies the output file for auditing if --auditDestinationhas value offile. The --auditPath option can take either a full pathname or a relative path name.

Note

The audit system isavailable only in MongoDB Enterprise.

--auditFilter

New in version 2.6.

Specifies the filter to limit the types of operations the audit system records. The optiontakes a document of the form:

{ atype: <expression> }

For authentication operations, the option can also take a document ofthe form:

{ atype: <expression>, "param.db": <database> }

Note

The audit system isavailable only in MongoDB Enterprise.

Additional Options

--ipv6

Enables IPv6 support and allows the mongos to connect to theMongoDB instance using an IPv6 network. All MongoDB programs andprocesses disable IPv6 support by default.

--jsonp

Permits JSONP access via an HTTP interface. Enabling theinterface can increase network exposure. The--jsonp option enables theHTTP interface, even if theHTTPinterfaceoption is disabled.

--noscripting

Disables the scripting engine.


mongo

Description

mongo is an interactive JavaScript shell interface toMongoDB, which provides a powerful interface for systemsadministrators as well as a way for developers to test queries andoperations directly with the database. mongo also providesa fully functional JavaScript environment for use with a MongoDB. Thisdocument addresses the basic invocation of themongo shelland an overview of its usage.

Options

Core Options

mongo

--shell

Enables the shell interface. If you invoke the mongo commandand specify a JavaScript file as an argument, or use --eval tospecify JavaScript on the command line, the--shell optionprovides the user with a shell prompt after the file finishes executing.

--nodb

Prevents the shell from connecting to any database instances. Later, toconnect to a database within the shell, seeOpening New Connections.

--norc

Prevents the shell from sourcing and evaluating ~/.mongorc.js onstart up.

--quiet

Silences output from the shell during the connection process.

--port <port>

Specifies the port where the mongod or mongosinstance is listening. If--port is not specified,mongo attempts to connect to port27017.

--host <hostname>

Specifies the name of the host machine where the mongod ormongos is running. If this is not specified,mongo attempts to connect to a MongoDB process running onthe localhost.

--eval <javascript>

Evaluates a JavaScript expression that is specified as an argument.mongo does not load its own environment when evaluating code.As a result many options of the shell environment are not available.

--username <username> , -u

Specifies a username with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the--password and--authenticationDatabase options.

--password <password> , -p

Specifies a password with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the--username and--authenticationDatabase options.

--help , -h

Returns information on the options and use of mongo.

--version

Returns the mongo release number.

--verbose

Increases the verbosity of the output of the shell during the connectionprocess.

--ipv6

Enables IPv6 support and allows the mongo to connect to theMongoDB instance using an IPv6 network. All MongoDB programs andprocesses disable IPv6 support by default.

<db address>

Specifies the “database address” of the database to connect to. Forexample:

mongo admin

The above command will connect the mongo shell to theadmin database on the local machine. You may specify a remotedatabase instance, with the resolvable hostname or IP address. Separatethe database name from the hostname using a/ character. See thefollowing examples:

mongo mongodb1.example.net
mongo mongodb1/admin
mongo 10.8.8.10/test

This syntax is the only way to connect to a specific database.

To specify alternate hosts and a database, you must use this syntax and cannotuse--host or --port.

<file.js>

Specifies a JavaScript file to run and then exit. Generally this shouldbe the last option specified.

Optional

To specify a JavaScript file to execute and allowmongo to prompt you for a password using--password, pass the filename as the first parameter with--username and --password as the last options, asin the following:

mongo file.js --username username --password

Use the --shell option to return to a shell after the filefinishes running.

Authentication Options

--authenticationDatabase <dbname>

New in version 2.4.

Specifies the database that holds the user’s credentials. If you do notspecify an authentication database, themongo assumes that thedatabase specified as the argument to the--db option holdsthe user’s credentials.

--authenticationMechanism <name>

Default: MONGODB-CR

New in version 2.4.

Changed in version 2.6: Added support for thePLAIN and MONGODB-X509 authenticationmechanisms.

Specifies the authentication mechanism the mongo instance uses toauthenticate to the mongod or mongos.

ValueDescription
MONGODB-CRMongoDB challenge/response authentication.
MONGODB-X509MongoDB SSL certificate authentication.
PLAINExternal authentication using LDAP. You can also use PLAINfor authenticating in-database users. PLAIN transmitspasswords in plain text. This mechanism is available only inMongoDB Enterprise.
GSSAPIExternal authentication using Kerberos. This mechanism isavailable only in MongoDB Enterprise.

SSL Options

--ssl

New in version 2.2.

Enables connection to a mongod or mongos that hasSSL support enabled.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslPEMKeyFile <filename>

New in version 2.4.

Specifies the .pem file that contains both the SSL certificateand key. Specify the file name of the.pem file using relativeor absolute paths.

This option is required when using the --ssl option to connectto amongod or mongos that hasCAFile enabled withoutweakCertificateValidation.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslPEMKeyPassword <value>

New in version 2.4.

Specifies the password to de-crypt the certificate-key file (i.e.--sslPEMKeyFile). Use the--sslPEMKeyPassword option only if thecertificate-key file is encrypted. In all cases, themongo willredact the password from all logging and reporting output.

Changed in version 2.6: If the private key in the PEM file is encrypted and you do notspecify the--sslPEMKeyPassword option, themongo will prompt for apassphrase. SeeSSL Certificate Passphrase.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslCAFile <filename>

New in version 2.4.

Specifies the .pem file that contains the root certificate chainfrom the Certificate Authority. Specify the file name of the.pem file using relative or absolute paths.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslCRLFile <filename>

New in version 2.4.

Specifies the .pem file that contains the Certificate RevocationList. Specify the file name of the.pem file using relative orabsolute paths.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslFIPSMode

New in version 2.4.

Directs the mongo to use the FIPS mode of the installed OpenSSLlibrary. Your system must have a FIPS compliant OpenSSL library to usethe--sslFIPSMode option.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

--sslAllowInvalidCertificates

New in version 2.6.

Bypasses the validation checks for server certificates and allowsthe use of invalid certificates. When using theallowInvalidCertificates setting, MongoDB logs as awarning the use of the invalid certificate.

The default distribution of MongoDB does not contain support for SSL.For more information on MongoDB and SSL, seeConfigure mongod and mongos for SSL.

Files

~/.dbshell

mongo maintains a history of commands in the.dbshellfile.

Note

mongo does not recorded interaction related toauthentication in the history file, includingauthenticate and db.addUser().

Warning

Versions of Windows mongo.exe earlier than 2.2.0 willsave the .dbshell file in the mongo.exe workingdirectory.

~/.mongorc.js

mongo will read the.mongorc.js file from the homedirectory of the user invokingmongo. In the file, userscan define variables, customize themongo shell prompt,or update information that they would like updated every time theylaunch a shell. If you use the shell to evaluate a JavaScript fileor expression either on the command line with--eval orby specifyinga .js file to mongo,mongo will read the.mongorc.js file after theJavaScript has finished processing.

Specify the --norc option to disablereading.mongorc.js.

/etc/mongorc.js

Global mongorc.js file which themongo shellevaluates upon start-up. If a user also has a.mongorc.jsfile located in the HOME directory, themongoshell evaluates the global/etc/mongorc.js file beforeevaluating the user’s.mongorc.js file.

/etc/mongorc.js must have read permission for the userrunning the shell. The--norc option formongosuppresses only the user’s.mongorc.js file.

On Windows, the global mongorc.js</etc/mongorc.js> existsin the %ProgramData%\MongoDB directory.

/tmp/mongo_edit<time_t>.js
Created by mongo when editing a file. If the file exists, mongo will append an integer from 1 to 10 to thetime value to attempt to create a unique file.
%TEMP%mongo_edit<time_t>.js
Created by mongo.exe on Windows when editing a file. Ifthe file exists, mongo will append an integer from 1to 10 to the time value to attempt to create a unique file.

Environment

EDITOR

Specifies the path to an editor to use with the edit shellcommand. A JavaScript variableEDITOR will override the value ofEDITOR.

HOME

Specifies the path to the home directory where mongo willread the .mongorc.js file and write the.dbshellfile.

HOMEDRIVE

On Windows systems, HOMEDRIVE specifies the path thedirectory where mongo will read the .mongorc.jsfile and write the.dbshell file.

HOMEPATH

Specifies the Windows path to the home directory wheremongo will read the.mongorc.js file and writethe .dbshell file.

Keyboard Shortcuts

The mongo shell supports the following keyboard shortcuts:[1]

KeybindingFunction
Up arrowRetrieve previous command from history
Down-arrowRetrieve next command from history
HomeGo to beginning of the line
EndGo to end of the line
TabAutocomplete method/command
Left-arrowGo backward one character
Right-arrowGo forward one character
Ctrl-left-arrowGo backward one word
Ctrl-right-arrowGo forward one word
Meta-left-arrowGo backward one word
Meta-right-arrowGo forward one word
Ctrl-AGo to the beginning of the line
Ctrl-BGo backward one character
Ctrl-CExit the mongo shell
Ctrl-DDelete a char (or exit the mongo shell)
Ctrl-EGo to the end of the line
Ctrl-FGo forward one character
Ctrl-GAbort
Ctrl-JAccept/evaluate the line
Ctrl-KKill/erase the line
Ctrl-L or type clsClear the screen
Ctrl-MAccept/evaluate the line
Ctrl-NRetrieve next command from history
Ctrl-PRetrieve previous command from history
Ctrl-RReverse-search command history
Ctrl-SForward-search command history
Ctrl-TTranspose characters
Ctrl-UPerform Unix line-discard
Ctrl-WPerform Unix word-rubout
Ctrl-YYank
Ctrl-ZSuspend (job control works in linux)
Ctrl-HBackward-delete a character
Ctrl-IComplete, same as Tab
Meta-BGo backward one word
Meta-CCapitalize word
Meta-DKill word
Meta-FGo forward one word
Meta-LChange word to lowercase
Meta-UChange word to uppercase
Meta-YYank-pop
Meta-BackspaceBackward-kill word
Meta-<Retrieve the first command in command history
Meta->Retrieve the last command in command history
[1]MongoDB accommodates multiple keybinding.Since 2.0, mongo includes support for basic emacskeybindings.

Use

Typically users invoke the shell with the mongo command atthe system prompt. Consider the following examples for otherscenarios.

To connect to a database on a remote host using authentication and anon-standard port, use the following form:

mongo --username <user> --password <pass> --host <host> --port 28015

Alternatively, consider the following short form:

mongo -u <user> -p <pass> --host <host> --port 28015

Replace <user>, <pass>, and <host> with the appropriatevalues for your situation and substitute or omit the--portas needed.

To execute a JavaScript file without evaluating the ~/.mongorc.jsfile before starting a shell session, use the following form:

mongo --shell --norc alternate-environment.js

To execute a JavaScript file with authentication, with password promptedrather than provided on the command-line, use the following form:

mongo script-file.js -u <user> -p

To print return a query as JSON, from the system prompt usingthe--eval option, use the following form:

mongo --eval 'db.collection.find().forEach(printjson)'

Use single quotes (e.g. ') to enclose the JavaScript, as well asthe additional JavaScript required to generate this output.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值