Use the following options to view and control various aspects of your MongoDB Shell.
General Options
--build-infoReturns a JSON-formatted document with information about your
mongoshbuild and driver dependencies.Example: View Build Information
You can check the build information and driver dependencies of your
mongoshbinary by running the following command from your terminal:mongosh --build-info This command returns the following JSON-formatted document:
{ version: '1.10.1', distributionKind: 'packaged', buildArch: 'x64', buildPlatform: 'linux', buildTarget: 'unknown', buildTime: '2023-06-21T09:49:37.225Z', gitVersion: '05ad91b4dd40382a13f27abe1ae8c3f9f52a38f7', nodeVersion: 'v16.20.1', opensslVersion: '3.1.1', sharedOpenssl: true, runtimeArch: 'x64', runtimePlatform: 'darwin', deps: { nodeDriverVersion: '5.6.0' } }
--eval <javascript>Evaluates a JavaScript expression. You can use a single
--evalargument or multiple--evalarguments together.After
mongoshevaluates the--evalargument, it prints the results to your command line. If you use multiple--evalstatements,mongoshonly prints the results of the last--eval.You can use the
--jsonflag with--evalto returnmongoshresults in Extended JSON format.mongoshsupports both--json=canonicaland--json=relaxedmodes. If you omit the mode,mongoshdefaults to thecanonicalmode. The--jsonflag is mutually exclusive with--shell.Example: Format Output
To get output suitable for automated parsing, use
EJSON.stringify().mongosh --quiet --host rs0/centos1104 --port 27500 \ --eval "EJSON.stringify(rs.status().members.map( \ m => ({'id':m._id, 'name':m.name, 'stateStr':m.stateStr})));" \ | jq After parsing with
jq, the output resembles this:[ { "id": 0, "name": "centos1104:27500", "stateStr": "PRIMARY" }, { "id": 1, "name": "centos1104:27502", "stateStr": "SECONDARY" }, { "id": 2, "name": "centos1104:27503", "stateStr": "SECONDARY" } ] Note
EJSONhas built in formatting options which may eliminate the need for a parser likejq. For example, the following code produces output that is formatted the same as above.mongosh --quiet --host rs0/centos1104 --port 27500 \ --eval "EJSON.stringify( rs.status().members.map( \ ({ _id, name, stateStr }) => ({ _id, name, stateStr })), null, 2);" Example: Multiple --eval Arguments
To get a list of collections in the
moviesDatabase, use multiple--evalstatements:mongosh --quiet \ --eval 'use moviesDatabase' \ --eval 'show collections' \ mongodb://localhost/ Example: --json Option
To return statistics about a collection in Extended JSON format using multiple
--evalstatements:mongosh --quiet --json=relaxed \ --eval 'use <database-name>' \ --eval 'db.<collection>.stats()' \ mongodb://localhost/
--file, -f <javascript>Runs a script from the command line without entering the MongoDB Shell console.
For additional details and an example, see Execute a Script From the Command Line.
--quietSkips all messages during startup (such as welcome messages and startup warnings) and goes directly to the prompt.
--skipStartupWarningsPrevents
mongoshfrom displaying server startup warnings when creating a session. To suppress all startup messages, use the--quietoption.
--shellEnables the shell interface. If you invoke the
mongoshcommand 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. The--shellflag is mutually exclusive with--json.
Stable API Options
--apiVersion <version number>Specifies the apiVersion.
"1"is currently the only supported value.
--apiStrictSpecifies that the server will respond with APIStrictError if your application uses a command or behavior outside of the Stable API.
If you specify
--apiStrict, you must also specify--apiVersion.
--apiDeprecationErrorsSpecifies that the server will respond with APIDeprecationError if your application uses a command or behavior that is deprecated in the specified
apiVersion.If you specify
--apiDeprecationErrors, you must also specify--apiVersion.
Connection Options
--host <hostname>Specifies the name of the host machine where the
mongodormongosis running. If this is not specified, the MongoDB Shell attempts 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 (
--tls), - The MongoDB Shell verifies that the hostname
(specified in the
--hostoption or the connection string) matches theSAN(or, ifSANis not present, theCN) in the certificate presented by themongodormongos. IfSANis present, the MongoDB Shell does not match against theCN. If the hostname does not match theSAN(orCN), the MongoDB Shell shell fails to connect.
- 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, overrides any corresponding DNS-configured options set in the TXT record. Use of themongodb+srv:connection string implicitly enables TLS / SSL (normally set withtls=true) for the client connection. The TLS option can be turned off by settingtls=falsein the query string.Example
mongodb+srv://server.example.com/?connectionTimeoutMS=3000
--port <port>Specifies the port where the
mongodormongosinstance is listening. If--portis not specified, the MongoDB Shell attempts to connect to port27017.
TLS Options
--tlsEnables connection to a
mongodormongosthat has TLS / SSL support enabled.To learn more about TLS/SSL and MongoDB, see:
--tlsCertificateKeyFile <filename>Specifies the
.pemfile that contains both the TLS / SSL certificate and key formongosh. 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, the MongoDB Shell presents this certificate to the server.Note
To learn more about TLS/SSL and MongoDB, see:
--tlsCertificateKeyFilePassword <value>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, the MongoDB Shell redacts 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; the MongoDB Shell prompts for a passphrase.See TLS/SSL Certificate Passphrase.
To learn more about TLS/SSL and MongoDB, see:
--tlsCAFile <filename>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.To learn more about TLS/SSL and MongoDB, see:
--tlsCRLFile <filename>Specifies the
.pemfile that contains the Certificate Revocation List. Specify the file name of the.pemfile using relative or absolute paths.To learn more about TLS/SSL and MongoDB, see:
--tlsAllowInvalidHostnamesDisables the validation of the hostnames in the certificate presented by the
mongod/mongosinstance. Allows the MongoDB Shell to connect to MongoDB instances even if the hostname in the server certificates do not match the server's host.To learn more about TLS/SSL and MongoDB, see:
--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
--tlsAllowInvalidCertificateswhen using x.509 authentication, an invalid certificate is only sufficient to establish a TLS / SSL connection but is insufficient for authentication.Warning
Although available, avoid using the
--tlsAllowInvalidCertificatesoption if possible. If the use of--tlsAllowInvalidCertificatesis necessary, only use the option on systems where intrusion is not possible.If the MongoDB Shell shell (and other MongoDB Tools) runs with the
--tlsAllowInvalidCertificatesoption, the shell (and other MongoDB Tools) do 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--tlsAllowInvalidHostnames.To learn more about TLS/SSL and MongoDB, see:
--tlsCertificateSelector <parameter>=<value>Available on Windows and macOS as an alternative to
--tlsCertificateKeyFile.Important
Windows and Importing Private Keys
When you import your private key, you must mark it as exportable. The Windows Certificate Import Wizard doesn't check this option by default.
![Microsoft Certificate Import Wizard where the key marked as exportable]()
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.
--tlsDisabledProtocols <string>Disables the specified TLS protocols. The option recognizes the following protocols:
TLS1_0TLS1_1TLS1_2(Starting in version 4.0.4, 3.6.9, 3.4.24)
TLS1_3On 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.
--tlsUseSystemCAAllows
mongoshto load TLS certificates already available to the operating system's certificate authority without explicitly specifying the certificates to the shell. This behavior is always enabled and cannot be turned off.--tlsUseSystemCAcan still be set for backward compatibility, but it has no effect.
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, the MongoDB Shell uses the database specified in the connection string.
--authenticationMechanism <name>Specifies the authentication mechanism the MongoDB Shell uses to authenticate to the
mongodormongos. If you don't specify anauthenticationMechanismbut provide user credentials, the MongoDB Shell and drivers attempt to use SCRAM-SHA-256. If this fails, they fall back to SCRAM-SHA-1.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.MongoDB TLS / SSL certificate authentication.
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 in MongoDB Enterprise and MongoDB Atlas.MONGODB-OIDC (OpenID Connect)
External authentication using OpenID Connect. This mechanism is available in MongoDB Enterprise and MongoDB Atlas.
MONGODB-AWS(AWS IAM)External authentication using Amazon Web Services Identity and Access Management (AWS IAM) credentials. This mechanism is available in MongoDB Enterprise and MongoDB Atlas.
--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.
--sspiHostnameCanonicalization <string>Specifies whether or not to use Hostname Canonicalization.
--sspiHostnameCanonicalizationhas the same effect as setting theCANONICALIZE_HOST_NAME:true|falsekey-pair in theauthMechanismPropertiesportion of the connection string.If
--sspiHostnameCanonicalizationis set to:forwardAndReverse, performs a forward DNS lookup and then a reverse lookup. New inmongosh1.3.0.forward, the effect is the same as settingauthMechanismProperties=CANONICALIZE_HOST_NAME:true.none, the effect is the same as settingauthMechanismProperties=CANONICALIZE_HOST_NAME:false.
--oidcFlowsSpecifies OpenID Connect flows in a comma-separated list. The OpenID Connect flows specify how
mongoshinteracts with the identity provider for the authentication process.mongoshsupports the following OpenID Connect flows:OpenID Connect FlowDescriptionauth-codeDefault.
mongoshopens a browser and redirects you to the identity provider log-in screen.device-authmongoshprovides you with a URL and code to finish authentication. This is considered a less secure OpenID Connect flow but can be used whenmongoshis run in an environment in which it cannot open a browser.To set
device-authas a fallback option toauth-code, see the following example:mongosh 'mongodb://localhost/' --authenticationMechanism MONGODB-OIDC --oidcFlows=auth-code,device-auth
--oidcIdTokenAsAccessTokenSpecifies whether
mongoshuses the ID token received from the identity provider instead of the access token. Use this option with identity providers that you can't configure to provide JWT access tokens.
--oidcNoNonceBy default,
mongoshsends a nonce parameter during the OIDC Authorization Code Flow.If you set the
--oidcNoNonceoption,mongoshdoes not send a nonce parameter. Use this option if your identity provider does not support nonce values as part of authorization.
--oidcRedirectUriSpecifies a URI where the identity provider redirects you after authentication. The URI must match the configuration of the identity provider. The default is
http://localhost:27097/redirect.
--oidcTrustedEndpointSpecifies a connection to a trusted endpoint that is not Atlas or localhost to ensure that access tokens are sent to trusted servers. Only use this option when connecting to servers that you trust.
--browserSpecifies the browser
mongoshredirects you to whenMONGODB-OIDCis enabled.This option is run with the system shell.
--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 force the MongoDB Shell to prompt for a password, enter the
--passwordoption as the last option and leave out the argument.
--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.
Session Options
--retryWritesEnables Retryable Writes.
By default, retryable writes are:
enabled in
mongoshdisabled in the legacy
mongoshell
To disable retryable writes, use
--retryWrites=false.For more information on sessions, see Client Sessions and Causal Consistency Guarantees.
Field Level Encryption Options
--cryptSharedLibPath <string>New in version 8.2.
The path to the Automatic Encryption Shared Library. The library must be version 8.2.0 or higher. Required to use automatic encryption for the
mongoshshell session.
--awsAccessKeyId <string>An AWS Access Key associated with an IAM user who has
ListandReadpermissions for the AWS Key Management Service (KMS).mongoshuses the specified--awsAccessKeyIdto access the KMS.--awsAccessKeyIdis required to enable Client-Side Field Level Encryption for themongoshshell session.--awsAccessKeyIdrequires both 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 to enable Client-Side Field Level Encryption for themongoshsession.--awsSecretAccessKeyrequires both 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 to enable Client-Side Field Level Encryption for themongoshshell 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 themongoshshell session.mongoshcreates the specified namespace if it does not exist.--keyVaultNamespacerequires both 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.
