Description
mongo is an interactive JavaScript shell interface to
MongoDB, which provides a powerful interface for system
administrators as well as a way for developers to test queries and
operations directly with the database. mongo also provides
a fully functional JavaScript environment for use with a MongoDB.
The mongo shell is included as part of the MongoDB
server installation. If you have already installed the
server, the mongo shell is installed to the same location
as the server binary.
Alternatively, if you would like to download the mongo
shell separately from the MongoDB Server, you can install the shell as
a standalone package by following these steps:
Access the Download Center for your Edition of MongoDB:
Select your preferred Version and Platform from the dropdowns.
Select the Package to download according to your platform:
Copy the
mongoshell from the archive to a location on your filesystem.
For additional installation guidance specific to your platform, or to
install the mongo shell as part of a MongoDB Server
installation, see the installation guide for your platform.
Note
Starting in MongoDB 4.2 (and 4.0.13), the
mongoshell displays a warning message when connected to non-genuine MongoDB instances as these instances may behave differently from the official MongoDB instances; e.g. missing or incomplete features, different feature behaviors, etc.mongodisables support for TLS 1.0 encryption on systems where TLS 1.1+ is available. For more details, see Disable TLS 1.0.
Syntax
You can run
mongoshell without any command-line options use the default settings:mongo You can run
mongoshell with a connection string that specifies the host and port and other connection options. For example, the following includes thetls:mongo "mongodb://mongodb0.example.com:27017/testdb?tls=true" The
tlsoption is available starting in MongoDB 4.2. In earlier version, use thessloption.To connect
mongoshell to a replica set, you can specify in the connection string the replica set members and name:mongo "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA" For more information on the connection string options, see Connection Strings.
You can run
mongoshell with various command-line options. For example:mongo --host mongodb0.example.com:27017 [additional options] mongo --host mongodb0.example.com --port 27017 [additional options] For more information on the options available, see Options.
Options
Changed in version 4.2:
MongoDB deprecates the SSL options and insteads adds new corresponding TLS options.
Core Options
--shellEnables the shell interface. If you invoke the
mongocommand and specify a JavaScript file as an argument, or use--evalto specify JavaScript on the command line, the--shelloption provides the user with a shell prompt after the file finishes executing.
--nodbPrevents the shell from connecting to any database instances. Later, to connect to a database within the shell, see Opening New Connections.
--port <port>Specifies the port where the
mongodormongosinstance is listening. If--portis not specified,mongoattempts to connect to port27017.
--host <hostname>Specifies the name of the host machine where the
mongodormongosis running. If this is not specified,mongoattempts to connect to a MongoDB process running on the localhost.- To connect to a replica set,
Specify the
replica set nameand a seed list of set members. Use the following form:<replSetName>/<hostname1><:port>,<hostname2><:port>,<...> - For TLS/SSL connections (
--ssl), - The
mongoshell verifies that the hostname (specified in--hostoption or the connection string) matches theSAN(or, ifSANis not present, theCN) in the certificate presented by themongodormongos. IfSANis present,mongodoes not match against theCN. If the hostname does not match theSAN(orCN), themongoshell will fail to connect.Starting in MongoDB 4.2, when performing comparison of SAN, MongoDB supports comparison of DNS names or IP addresses. In previous versions, MongoDB only supports comparisons of DNS names. - For DNS seedlist connections,
Specify the connection protocol as
mongodb+srv, followed by the DNS SRV hostname record and any options. TheauthSourceandreplicaSetoptions, if included in the connection string, will override any corresponding DNS-configured options set in the TXT record. Use of themongodb+srv:connection string implicitly enables TLS/SSL (normally set withssl=true) for the client connection. The TLS/SSL option can be turned off by settingssl=falsein the query string.Example:
mongodb+srv://server.example.com/?connectionTimeout=3000ms New in version 3.6.
--eval <javascript>Evaluates a JavaScript expression that is specified as an argument.
mongodoes not load its own environment when evaluating code. As a result many options of the shell environment are not available.
--username <username>, -u <username>Specifies a username with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--passwordand--authenticationDatabaseoptions.If connecting to a MongoDB Atlas cluster using the
MONGODB-AWSauthentication mechanism, specify your AWS access key ID in this field, or in the connection string. Alternatively, this value may also be supplied as the environment variableAWS_ACCESS_KEY_ID. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.
--password <password>, -p <password>Specifies a password with which to authenticate to a MongoDB database that uses authentication. Use in conjunction with the
--usernameand--authenticationDatabaseoptions. To forcemongoto prompt for a password, enter the--passwordoption as the last option and leave out the argument.If connecting to a MongoDB Atlas cluster using the
MONGODB-AWSauthentication mechanism, specify your AWS secret access key in this field, or in the connection string. Alternatively, this value may also be supplied as the environment variableAWS_SECRET_ACCESS_KEY. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.
--awsIamSessionToken <aws session token>If connecting to a MongoDB Atlas cluster using the
MONGODB-AWSauthentication mechanismand using session tokens in addition to your AWS access key ID and secret access key, specify your AWS session token in this field, or in the connection string. Alternatively, this value may also be supplied as the environment variableAWS_SESSION_TOKEN. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.Only valid when using the
MONGODB-AWSauthentication mechanism.
--help, -hReturns information on the options and use of
mongo.
--versionReturns the
mongorelease number.
--networkMessageCompressors <string>New in version 3.4.
Enables network compression for communication between this
mongoshell and:You can specify the following compressors:
Important
Messages are compressed when both parties enable network compression. Otherwise, messages between the parties are uncompressed.
If you specify multiple compressors, then the order in which you list the compressors matter as well as the communication initiator. For example, if a
mongoshell specifies the following network compressorszlib,snappyand themongodspecifiessnappy,zlib, messages betweenmongoshell andmongoduseszlib.If the parties do not share at least one common compressor, messages between the parties are uncompressed. For example, if a
mongoshell specifies the network compressorzlibandmongodspecifiessnappy, messages betweenmongoshell andmongodare not compressed.
--ipv6Enables IPv6 support.
mongodisables IPv6 by default.To connect to a MongoDB cluster via IPv6, you must specify both
--ipv6and--host <mongod/mongos IPv6 address>when starting themongoshell.mongodandmongosdisable IPv6 support by default. Specifying--ipv6when connecting to amongod/mongosdoes not enable IPv6 support on themongod/mongos. For documentation on enabling IPv6 support on themongod/mongos, seenet.ipv6.
<db name>Specifies the name of the database to connect to. For example:
mongo admin The above command will connect the
mongoshell to the admin database of the MongoDB deployment running on the local machine. You may specify a remote database instance, with the resolvable hostname or IP address. Separate the database name from the hostname using a/character. See the following examples:mongo mongodb1.example.net/test 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 cannot use
--hostor--port.
--disableJavaScriptJITChanged in version 4.0: The JavaScript engine's JIT compiler is now disabled by default.
Disables the JavaScript engine's JIT compiler.
--disableJavaScriptProtectionNew in version 3.4.
Allows fields of type javascript and javascriptWithScope (*Deprecated*) to be automatically marshalled to JavaScript functions in the
mongoshell.With the
--disableJavaScriptProtectionflag set, it is possible to immediately execute JavaScript functions contained in documents. The following example demonstrates this behavior within the shell:> db.test.insert({ _id: 1, jsFunc: function(){ print("hello") } } ) WriteResult({ "nInserted" : 1 }) > var doc = db.test.findOne({ _id: 1 }) > doc { "_id" : 1, "jsFunc" : function (){ print ("hello") } } > typeof doc.jsFunc function > doc.jsFunc() hello The default behavior (when
mongostarts without the--disableJavaScriptProtectionflag) is to convert embedded JavaScript functions to the non-executable MongoDB shell typeCode. The following example demonstrates the default behavior within the shell:> db.test.insert({ _id: 1, jsFunc: function(){ print("hello") } } ) WriteResult({ "nInserted" : 1 }) > var doc = db.test.findOne({ _id: 1 }) > doc { "_id" : 1, "jsFunc" : { "code" : "function (){print(\"hello\")}" } } > typeof doc.func object > doc.func instanceof Code true > doc.jsFunc() 2016-11-09T12:30:36.808-08:00 E QUERY [thread1] TypeError: doc.jsFunc is not a function : @(shell):1:1
<file.js>Specifies a JavaScript file to run and then exit. Generally this should be the last option specified.
Note
Optional
To specify a JavaScript file to execute and allow
mongoto prompt you for a password using--password, pass the filename as the first parameter with--usernameand--passwordas the last options, as in the following:mongo file.js --username username --password Use the
--shelloption to return to a shell after the file finishes running.
Authentication Options
--authenticationDatabase <dbname>Specifies the authentication database where the specified
--usernamehas been created. See Authentication Database.If you do not specify a value for
--authenticationDatabase,mongouses the database specified in the connection string.If using the GSSAPI (Kerberos), PLAIN (LDAP SASL), or
MONGODB-AWSauthentication mechanisms, you must set--authenticationDatabaseto$external.
--authenticationMechanism <name>Default: SCRAM-SHA-1
Specifies the authentication mechanism the
mongoinstance uses to authenticate to themongodormongos.Changed in version 4.4: With MongoDB 4.4, the
mongoshell adds support for the newMONGODB-AWSauthentication mechanism when connecting to a MongoDB Atlas cluster.ValueDescriptionRFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.
RFC 7677 standard Salted Challenge Response Authentication Mechanism using the SHA-256 hash function.
Requires featureCompatibilityVersion set to
4.0.New in version 4.0.
MongoDB TLS/SSL certificate authentication.
MONGODB-AWSExternal authentication using AWS IAM credentials for use in connecting to a MongoDB Atlas cluster. See Connect to a MongoDB Atlas Cluster using AWS IAM Credentials.
New in version 4.4.
GSSAPI (Kerberos)
External authentication using Kerberos. This mechanism is available only in MongoDB Enterprise.
PLAIN (LDAP SASL)
External authentication using LDAP. You can also use
PLAINfor authenticating in-database users.PLAINtransmits passwords in plain text. This mechanism is available only in MongoDB Enterprise.
--gssapiHostNameSpecify the hostname of a service using GSSAPI/Kerberos. Only required if the hostname of a machine does not match the hostname resolved by DNS.
This option is available only in MongoDB Enterprise.
--gssapiServiceNameSpecify the name of the service using GSSAPI/Kerberos. Only required if the service does not use the default name of
mongodb.This option is available only in MongoDB Enterprise.
TLS Options
Note
mongo disables support for TLS 1.0
encryption on systems where TLS 1.1+ is available. For
more details, see Disable TLS 1.0.
--tlsNew in version 4.2.
Enables connection to a
mongodormongosthat has TLS/SSL support enabled.Starting in version 3.2.6, if
--tlsCAFileornet.tls.CAFile(or their aliases--sslCAFileorssl.CAFile) is not specified, the system-wide CA certificate store will be used when connecting to an TLS/SSL-enabled server. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.To use x.509 authentication,
--tlsCAFileornet.tls.CAFilemust be specified unless using--tlsCertificateSelectoror--net.tls.certificateSelector. Or if using thesslaliases,--sslCAFileornet.ssl.CAFilemust be specified unless using--sslCertificateSelectorornet.ssl.certificateSelector.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--tlsCertificateKeyFile <filename>New in version 4.2.
Specifies the
.pemfile that contains both the TLS/SSL certificate and key for themongoshell. Specify the file name of the.pemfile using relative or absolute paths.This option is required when using the
--tlsoption to connect to amongodormongosinstance that requires client certificates. That is, themongoshell present this certificate to the server.Changed in version 4.4:
mongod/mongoslogs a warning on connection if the presented x.509 certificate expires within30days of themongod/mongoshost system time. See x.509 Certificates Nearing Expiry Trigger Warnings for more information.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--tlsCertificateKeyFilePassword <value>New in version 4.2.
Specifies the password to de-crypt the certificate-key file (i.e.
--tlsCertificateKeyFile).Use the
--tlsCertificateKeyFilePasswordoption only if the certificate-key file is encrypted. In all cases, themongowill redact the password from all logging and reporting output.If the private key in the PEM file is encrypted and you do not specify the
--tlsCertificateKeyFilePasswordoption, themongowill prompt for a passphrase. See TLS/SSL Certificate Passphrase.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--tlsCAFile <filename>New in version 4.2.
Specifies the
.pemfile that contains the root certificate chain from the Certificate Authority. This file is used to validate the certificate presented by themongod/mongosinstance.Specify the file name of the
.pemfile using relative or absolute paths.Starting in version 3.2.6, if
--tlsCAFileornet.tls.CAFile(or their aliases--sslCAFileorssl.CAFile) is not specified, the system-wide CA certificate store will be used when connecting to an TLS/SSL-enabled server. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.To use x.509 authentication,
--tlsCAFileornet.tls.CAFilemust be specified unless using--tlsCertificateSelectoror--net.tls.certificateSelector. Or if using thesslaliases,--sslCAFileornet.ssl.CAFilemust be specified unless using--sslCertificateSelectorornet.ssl.certificateSelector.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--tlsCRLFile <filename>New in version 4.2: In MongoDB 4.0 and earlier, see
--sslCRLFile.Specifies the
.pemfile that contains the Certificate Revocation List. Specify the file name of the.pemfile using relative or absolute paths.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .Note
Starting in version 4.4, to check for certificate revocation, MongoDB
enablesthe use of OCSP (Online Certificate Status Protocol) by default as an alternative to specifying a CRL file or using the system SSL certificate store.
--tlsAllowInvalidHostnamesNew in version 4.2.
Disables the validation of the hostnames in the certificate presented by the
mongod/mongosinstance. Allowsmongoto connect to MongoDB instances even if the hostname in the server certificates do not match the server's host.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--tlsAllowInvalidCertificatesNew in version 4.2.
Bypasses the validation checks for the certificates presented by the
mongod/mongosinstance and allows connections to servers that present invalid certificates.Note
Starting in MongoDB 4.0, if you specify any of the following x.509 authentication options, an invalid certificate is sufficient only to establish a TLS connection but it is insufficient for authentication:
--sslAllowInvalidCertificatesornet.ssl.allowInvalidCertificates: truefor MongoDB 4.0 and later--tlsAllowInvalidCertificatesornet.tls.allowInvalidCertificates: truefor MongoDB 4.2 and later
Warning
Although available, avoid using the
--sslAllowInvalidCertificatesoption if possible. If the use of--sslAllowInvalidCertificatesis necessary, only use the option on systems where intrusion is not possible.If the
mongoshell (and other MongoDB Tools) runs with the--sslAllowInvalidCertificatesoption, themongoshell (and other MongoDB Tools) will not attempt to validate the server certificates. This creates a vulnerability to expiredmongodandmongoscertificates as well as to foreign processes posing as validmongodormongosinstances. If you only need to disable the validation of the hostname in the TLS/SSL certificates, see--sslAllowInvalidHostnames.When using the
allowInvalidCertificatessetting, MongoDB logs as a warning the use of the invalid certificate.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--tlsFIPSModeNew in version 4.2.
Directs the
mongoto use the FIPS mode of the TLS/SSL library. Your system must have a FIPS compliant library to use the--tlsFIPSModeoption.Note
FIPS-compatible TLS/SSL is available only in MongoDB Enterprise. See Configure MongoDB for FIPS for more information.
--tlsCertificateSelector <parameter>=<value>New in version 4.2: Available on Windows and macOS as an alternative to
--tlsCertificateKeyFile.The
--tlsCertificateKeyFileand--tlsCertificateSelectoroptions are mutually exclusive. You can only specify one.Specifies a certificate property in order to select a matching certificate from the operating system's certificate store.
--tlsCertificateSelectoraccepts an argument of the format<property>=<value>where the property can be one of the following:PropertyValue typeDescriptionsubjectASCII string
Subject name or common name on certificate
thumbprinthex string
A sequence of bytes, expressed as hexadecimal, used to identify a public key by its SHA-1 digest.
The
thumbprintis sometimes referred to as afingerprint.When using the system SSL certificate store, OCSP (Online Certificate Status Protocol) is used to validate the revocation status of certificates.
Changed in version 4.4:
mongod/mongoslogs a warning on connection if the presented x.509 certificate expires within30days of themongod/mongoshost system time. See x.509 Certificates Nearing Expiry Trigger Warnings for more information.
--tlsDisabledProtocols <string>New in version 4.2.
Disables the specified TLS protocols. The option recognizes the following protocols:
TLS1_0,TLS1_1,TLS1_2, and starting in version 4.0.4 (and 3.6.9 and 3.4.24),TLS1_3.On macOS, you cannot disable
TLS1_1and leave bothTLS1_0andTLS1_2enabled. You must also disable at least one of the other two; for example,TLS1_0,TLS1_1.To list multiple protocols, specify as a comma separated list of protocols. For example
TLS1_0,TLS1_1.The specified disabled protocols overrides any default disabled protocols.
Starting in version 4.0, MongoDB disables the use of TLS 1.0 if TLS 1.1+ is available on the system. To enable the disabled TLS 1.0, specify
noneto--tlsDisabledProtocols. See Disable TLS 1.0.
SSL Options (Deprecated)
Important
Starting in version 4.2, the SSL options are deprecated. Use the TLS counterparts instead. The SSL protocol is deprecated and MongoDB supports TLS 1.0 and later.
Note
mongo disables support for TLS 1.0
encryption on systems where TLS 1.1+ is available. For
more details, see Disable TLS 1.0.
--sslDeprecated since version 4.2: Use
--tlsinstead.Enables connection to a
mongodormongosthat has TLS/SSL support enabled.Starting in version 3.2.6, if
--tlsCAFileornet.tls.CAFile(or their aliases--sslCAFileorssl.CAFile) is not specified, the system-wide CA certificate store will be used when connecting to an TLS/SSL-enabled server. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.To use x.509 authentication,
--tlsCAFileornet.tls.CAFilemust be specified unless using--tlsCertificateSelectoror--net.tls.certificateSelector. Or if using thesslaliases,--sslCAFileornet.ssl.CAFilemust be specified unless using--sslCertificateSelectorornet.ssl.certificateSelector.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslPEMKeyFile <filename>Deprecated since version 4.2: Use
--tlsCertificateKeyFileinstead.Specifies the
.pemfile that contains both the TLS/SSL certificate and key. Specify the file name of the.pemfile using relative or absolute paths.This option is required when using the
--ssloption to connect to amongodormongosthat hasCAFileenabled withoutallowConnectionsWithoutCertificates.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslPEMKeyPassword <value>Deprecated since version 4.2: Use
--tlsCertificateKeyFilePasswordinstead.Specifies the password to de-crypt the certificate-key file (i.e.
--sslPEMKeyFile). Use the--sslPEMKeyPasswordoption only if the certificate-key file is encrypted. In all cases, themongowill redact the password from all logging and reporting output.If the private key in the PEM file is encrypted and you do not specify the
--sslPEMKeyPasswordoption, themongowill prompt for a passphrase. See TLS/SSL Certificate Passphrase.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslCAFile <filename>Deprecated since version 4.2: Use
--tlsCAFileinstead.Specifies the
.pemfile that contains the root certificate chain from the Certificate Authority. Specify the file name of the.pemfile using relative or absolute paths.Starting in version 3.2.6, if
--tlsCAFileornet.tls.CAFile(or their aliases--sslCAFileorssl.CAFile) is not specified, the system-wide CA certificate store will be used when connecting to an TLS/SSL-enabled server. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.To use x.509 authentication,
--tlsCAFileornet.tls.CAFilemust be specified unless using--tlsCertificateSelectoror--net.tls.certificateSelector. Or if using thesslaliases,--sslCAFileornet.ssl.CAFilemust be specified unless using--sslCertificateSelectorornet.ssl.certificateSelector.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslCertificateSelector <parameter>=<value>Deprecated since version 4.2: Use
--tlsCertificateSelectorinstead.New in version 4.0: Available on Windows and macOS as an alternative to
--tlsCertificateKeyFile.--tlsCertificateKeyFileand--sslCertificateSelectoroptions are mutually exclusive. You can only specify one.Specifies a certificate property in order to select a matching certificate from the operating system's certificate store.
--sslCertificateSelectoraccepts an argument of the format<property>=<value>where the property can be one of the following:PropertyValue typeDescriptionsubjectASCII string
Subject name or common name on certificate
thumbprinthex string
A sequence of bytes, expressed as hexadecimal, used to identify a public key by its SHA-1 digest.
The
thumbprintis sometimes referred to as afingerprint.When using the system SSL certificate store, OCSP (Online Certificate Status Protocol) is used to validate the revocation status of certificates.
--sslCRLFile <filename>Deprecated since version 4.2: Use
--tlsCRLFileinstead.Specifies the
.pemfile that contains the Certificate Revocation List. Specify the file name of the.pemfile using relative or absolute paths.Note
Starting in version 4.4, to check for certificate revocation, MongoDB
enablesthe use of OCSP (Online Certificate Status Protocol) by default as an alternative to specifying a CRL file or using the system SSL certificate store.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslFIPSModeDeprecated since version 4.2: Use
--tlsFIPSModeinstead.Directs the
mongoto use the FIPS mode of the TLS/SSL library. Your system must have a FIPS compliant library to use the--sslFIPSModeoption.Note
FIPS-compatible TLS/SSL is available only in MongoDB Enterprise. See Configure MongoDB for FIPS for more information.
--sslAllowInvalidCertificatesDeprecated since version 4.2: Use
--tlsAllowInvalidCertificatesinstead.Bypasses the validation checks for server certificates and allows the use of invalid certificates to connect.
Note
Starting in MongoDB 4.0, if you specify any of the following x.509 authentication options, an invalid certificate is sufficient only to establish a TLS connection but it is insufficient for authentication:
--sslAllowInvalidCertificatesornet.ssl.allowInvalidCertificates: truefor MongoDB 4.0 and later--tlsAllowInvalidCertificatesornet.tls.allowInvalidCertificates: truefor MongoDB 4.2 and later
Warning
Although available, avoid using the
--sslAllowInvalidCertificatesoption if possible. If the use of--sslAllowInvalidCertificatesis necessary, only use the option on systems where intrusion is not possible.If the
mongoshell (and other MongoDB Tools) runs with the--sslAllowInvalidCertificatesoption, themongoshell (and other MongoDB Tools) will not attempt to validate the server certificates. This creates a vulnerability to expiredmongodandmongoscertificates as well as to foreign processes posing as validmongodormongosinstances. If you only need to disable the validation of the hostname in the TLS/SSL certificates, see--sslAllowInvalidHostnames.When using the
allowInvalidCertificatessetting, MongoDB logs as a warning the use of the invalid certificate.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslAllowInvalidHostnamesDeprecated since version 4.2: Use
--tlsAllowInvalidHostnamesinstead.Disables the validation of the hostnames in TLS/SSL certificates. Allows
mongoto connect to MongoDB instances even if the hostname in their certificates do not match the specified hostname.For more information about TLS/SSL and MongoDB, see Configure
mongodandmongosfor TLS/SSL and TLS/SSL Configuration for Clients .
--sslDisabledProtocols <string>Deprecated since version 4.2: Use
--tlsDisabledProtocolsinstead.Disables the specified TLS protocols. The option recognizes the following protocols:
TLS1_0,TLS1_1,TLS1_2, and starting in version 4.0.4 (and 3.6.9),TLS1_3.On macOS, you cannot disable
TLS1_1and leave bothTLS1_0andTLS1_2enabled. You must also disable at least one of the other two; for example,TLS1_0,TLS1_1.To list multiple protocols, specify as a comma separated list of protocols. For example
TLS1_0,TLS1_1.The specified disabled protocols overrides any default disabled protocols.
Starting in version 4.0, MongoDB disables the use of TLS 1.0 if TLS 1.1+ is available on the system. To enable the disabled TLS 1.0, specify
noneto--sslDisabledProtocols. See Disable TLS 1.0.New in version 3.6.5.
Sessions
--retryWritesNew in version 3.6.
Enables retryable writes as the default for sessions in the
mongoshell.For more information on sessions, see Client Sessions and Causal Consistency Guarantees.
Client-Side Field Level Encryption Options
--awsAccessKeyId <string>An AWS Access Key associated to an IAM user with
ListandReadpermissions for the AWS Key Management Service (KMS). Themongoshell uses the specified--awsAccessKeyIdto access the KMS.--awsAccessKeyIdis required for enabling Client-Side Field Level Encryption for themongoshell session.--awsAccessKeyIdrequires all of the following command line options:If
--awsAccessKeyIdis omitted, use theMongo()constructor within the shell session to enable client-side field level encryption.To mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to
--awsAccessKeyId.
--awsSecretAccessKey <string>An AWS Secret Key associated to the specified
--awsAccessKeyId.--awsSecretAccessKeyis required for enabling Client-Side Field Level Encryption for themongoshell session.--awsSecretAccessKeyrequires all of the following command line options:If
--awsSecretAccessKeyand its supporting options are omitted, useMongo()within the shell session to enable client-side field level encryption.To mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to
--awsSecretAccessKey.
--awsSessionToken <string>An AWS Session Token associated to the specified
--awsAccessKeyId.--awsSessionTokenis required for enabling Client-Side Field Level Encryption for themongoshell session.--awsSessionTokenrequires all of the following command line options:If
--awsSessionTokenand its supporting options are omitted, useMongo()within the shell session to enable client-side field level encryption.To mitigate the risk of leaking access keys into logs, consider specifying an environmental variable to
--awsSessionToken.
--keyVaultNamespace <string>The full namespace (
<database>.<collection>) of the collection used as a key vault for Client-Side Field Level Encryption.--keyVaultNamespaceis required for enabling client-side field level encryption. for themongoshell session.mongocreates the specified namespace if it does not exist.--keyVaultNamespacerequires all of the following command line options:If
--keyVaultNamespaceand its supporting options are omitted, use theMongo()constructor within the shell session to enable client-side field level encryption.
Files
~/.dbshellmongomaintains a history of commands in the.dbshellfile.Note
mongodoes not record interaction related to authentication in the history file, includingauthenticateanddb.createUser().
~/.mongorc.jsmongowill read the.mongorc.jsfile from the home directory of the user invokingmongo. In the file, users can define variables, customize themongoshell prompt, or update information that they would like updated every time they launch a shell. If you use the shell to evaluate a JavaScript file or expression either on the command line withmongo --evalor by specifying a .js file to mongo,mongowill read the.mongorc.jsfile after the JavaScript has finished processing.Specify the
--norcoption to disable reading.mongorc.js.
/etc/mongorc.jsGlobal
mongorc.jsfile which themongoshell evaluates upon start-up. If a user also has a.mongorc.jsfile located in theHOMEdirectory, themongoshell evaluates the global/etc/mongorc.jsfile before evaluating the user's.mongorc.jsfile./etc/mongorc.jsmust have read permission for the user running the shell. The--norcoption formongosuppresses only the user's.mongorc.jsfile.On Windows, the global
mongorc.js </etc/mongorc.js>exists in the%ProgramData%\MongoDBdirectory./tmp/mongo_edit{<time_t>}.js- Created by
mongowhen editing a file. If the file exists,mongowill append an integer from1to10to the time value to attempt to create a unique file. %TEMP%mongo_edit{<time_t>}.js- Created by
mongo.exeon Windows when editing a file. If the file exists,mongowill append an integer from1to10to the time value to attempt to create a unique file.
Environment
EDITORSpecifies the path to an editor to use with the
editshell command. A JavaScript variableEDITORwill override the value ofEDITOR.
HOMESpecifies the path to the home directory where
mongowill read the.mongorc.jsfile and write the.dbshellfile.
HOMEDRIVEOn Windows systems,
HOMEDRIVEspecifies the path the directory wheremongowill read the.mongorc.jsfile and write the.dbshellfile.
HOMEPATHSpecifies the Windows path to the home directory where
mongowill read the.mongorc.jsfile and write the.dbshellfile.
Keyboard Shortcuts
The mongo shell supports the following keyboard shortcuts:
[1]
Keybinding | Function |
|---|---|
Up arrow | Retrieve previous command from history |
Down-arrow | Retrieve next command from history |
Home | Go to beginning of the line |
End | Go to end of the line |
Tab | Autocomplete method/command |
Left-arrow | Go backward one character |
Right-arrow | Go forward one character |
Ctrl-left-arrow | Go backward one word |
Ctrl-right-arrow | Go forward one word |
Meta-left-arrow | Go backward one word |
Meta-right-arrow | Go forward one word |
Ctrl-A | Go to the beginning of the line |
Ctrl-B | Go backward one character |
Ctrl-C | Exit the |
Ctrl-D | Delete a char (or exit the |
Ctrl-E | Go to the end of the line |
Ctrl-F | Go forward one character |
Ctrl-G | Abort |
Ctrl-J | Accept/evaluate the line |
Ctrl-K | Kill/erase the line |
Ctrl-L or type | Clear the screen |
Ctrl-M | Accept/evaluate the line |
Ctrl-N | Retrieve next command from history |
Ctrl-P | Retrieve previous command from history |
Ctrl-R | Reverse-search command history |
Ctrl-S | Forward-search command history |
Ctrl-T | Transpose characters |
Ctrl-U | Perform Unix line-discard |
Ctrl-W | Perform Unix word-rubout |
Ctrl-Y | Yank |
Ctrl-Z | Suspend (job control works in linux) |
Ctrl-H | Backward-delete a character |
Ctrl-I | Complete, same as Tab |
Meta-B | Go backward one word |
Meta-C | Capitalize word |
Meta-D | Kill word |
Meta-F | Go forward one word |
Meta-L | Change word to lowercase |
Meta-U | Change word to uppercase |
Meta-Y | Yank-pop |
Meta-Backspace | Backward-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 emacs
keybindings. |
Use
Typically users invoke the shell with the mongo command at
the system prompt. Consider the following examples for other
scenarios.
Connect to a mongod Instance with Access Control
To connect to a database on a remote host using authentication and a non-standard port, use the following form:
mongo --username <user> --password --host <host> --port 28015
Alternatively, consider the following short form:
mongo -u <user> -p --host <host> --port 28015
Replace <user> and <host> with the appropriate values for your
situation and substitute or omit the --port as
needed.
If you do not specify the password to the --password or -p command-line option, the
mongo shell prompts for the password.
Connect to a Replica Set Using the DNS Seedlist Connection Format
New in version 3.6.
To connect to a replica set described using the
DNS Seed List Connection Format, use the --host option
to specify the connection string to the mongo shell. In
the following example, the DNS configuration resembles:
Record TTL Class Priority Weight Port Target _mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27317 mongodb1.example.com. _mongodb._tcp.server.example.com. 86400 IN SRV 0 5 27017 mongodb2.example.com.
The TXT record for the DNS entry includes the replicaSet and authSource options:
Record TTL Class Text server.example.com. 86400 IN TXT "replicaSet=rs0&authSource=admin"
The following command then connects the mongo shell to
the replica set:
mongo --host "mongodb+srv://server.example.com/?username=allison"
The mongo shell will automatically prompt you to provide
the password for the user specified in the username option.
Connect to a MongoDB Atlas Cluster using AWS IAM Credentials
New in version 4.4.
To connect to a MongoDB Atlas cluster which
has been configured to support authentication via AWS IAM credentials,
provide a connection string to
the mongo shell similar to the following:
mongo 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'
Connecting to Atlas using AWS IAM credentials in this manner uses the
MONGODB-AWS authentication mechanism
and the $external authSource, as shown in this example.
If using an AWS session token
as well, provide it with the AWS_SESSION_TOKEN
authMechanismProperties value in your
connection string, as follows:
mongo 'mongodb+srv://<aws access key id>:<aws secret access key>@cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS&authMechanismProperties=AWS_SESSION_TOKEN:<aws session token>'
Note
If the AWS access key ID, secret access key, or session token include the following characters:
: / ? # [ ] @
those characters must be converted using percent encoding.
Alternatively, the AWS access key ID, and secret access key, and
optionally session token can each be provided outside of the connection
string using the --username, --password, and
--awsIamSessionToken options instead, like so:
mongo 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS' --username <aws access key id> --password <aws secret access key> --awsIamSessionToken <aws session token>
When provided as command line parameters, these three options do not require percent encoding.
You may also set these credentials on your platform using standard
AWS IAM environment variables.
The mongo shell checks for the following environment
variables when you use the MONGODB-AWS
authentication mechanism:
AWS_ACCESS_KEY_IDAWS_SECRET_ACCESS_KEYAWS_SESSION_TOKEN
If set, these credentials do not need to be specified in the connection
string or via the explicit options to the mongo shell
(i.e. --username and --password).
The following example sets these environment variables in the bash
shell:
export AWS_ACCESS_KEY_ID='<aws access key id>' export AWS_SECRET_ACCESS_KEY='<aws secret access key>' export AWS_SESSION_TOKEN='<aws session token>'
Syntax for setting environment variables in other shells will be different. Consult the documentation for your platform for more information.
You can verify that these environment variables have been set with the following command:
env | grep AWS
Once set, the following example connects to a MongoDB Atlas cluster using these environment variables:
mongo 'mongodb+srv://cluster0.example.com/testdb?authSource=$external&authMechanism=MONGODB-AWS'
Execute JavaScript Against the mongo Shell
To execute a JavaScript file without evaluating the ~/.mongorc.js
file before starting a shell session, use the following form:
mongo --shell --norc alternate-environment.js
To execute a JavaScript file with authentication, with password prompted rather than provided on the command-line, use the following form:
mongo script-file.js -u <user> -p
Use --eval to Execute JavaScript Code
You may use the --eval option to execute
JavaScript directly from the command line.
For example, the following operation evaluates a JavaScript string which queries a collection and prints the results as JSON.
On Linux and macOS, you will need to use single quotes (e.g. ')
to enclose the JavaScript, using the following form:
mongo --eval 'db.collection.find().forEach(printjson)'
On Windows, you will need to use double quotes (e.g. ")
to enclose the JavaScript, using the following form:
mongo --eval "db.collection.find().forEach(printjson)"