mongo
Description
mongo
is an interactive JavaScript shell interface toMongoDB, which provides a powerful interface for systemadministrators 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.
The mongo
shell is included as part of the MongoDB Server installation. MongoDB also provides the mongo
shell as a standalone package. To download the standalone mongo
shell package:
Open the Download Center. For the
mongo
Enterprise Shell, select theMongoDB Enterprise Server tab.Select your preferred Version and OS from thedropdowns.
Select
Shell
from the Package dropdown and clickDownload to start downloading the package.
If the Shell
option is unavailable for the selected OS andVersion, contact MongoDB Technical Support for assistance.
Note
- Starting in MongoDB 4.2 (and 4.0.13), the
mongo
shell displays awarning message when connected to non-genuine MongoDB instances asthese instances may behave differently from the official MongoDBinstances; e.g. missing or incomplete features, different featurebehaviors, etc. - Starting in version 4.0,
mongo
disables support for TLS 1.0encryption on systems where TLS 1.1+ is available. Formore details, see Disable TLS 1.0.
Syntax
- You can run
mongo
shell without any command-lineoptions use the default settings:
- mongo
- You can run
mongo
shell with a connection string that specifies the host and port andother connection options. For example, the following includes thetls
:
- mongo "mongodb://mongodb0.example.com:27017/testdb?tls=true"
The tls
option is available starting in MongoDB 4.2. Inearlier version, use the ssl
option.
To connect mongo
shell to a replica set, you canspecify 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, seeConnection String URI Format.
- You can run
mongo
shell with various command-lineoptions. 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
Starting in version 4.2
- MongoDB deprecates the SSL options and insteads adds newcorresponding TLS options.
Core Options
—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.
—port
<port>
- Specifies the port where the
mongod
ormongos
instance 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.- To connect to a replica set,
- Specify the
replica set name
and a seed list of set members. Use the following form:
- <replSetName>/<hostname1><:port>,<hostname2><:port>,<...>
- For TLS/SSL connections (
—ssl
), - The
mongo
shell verifies that the hostname (specifiedin—host
option or the connection string)matches theSAN
(or, ifSAN
is not present, theCN
) inthe certificate presented by themongod
ormongos
. IfSAN
is present,mongo
does not match against theCN
. If the hostname does not matchtheSAN
(orCN
), themongo
shell will fail toconnect.
Starting in MongoDB 4.2, when performing comparison of SAN, MongoDBsupports 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 bythe DNS SRV hostname record and any options. TheauthSource
andreplicaSet
options, if included in the connection string,will override any corresponding DNS-configured options set in theTXT record. Use of themongodb+srv:
connection stringimplicitly enables TLS/SSL (normally set withssl=true
) forthe client connection. The TLS/SSL option can be turned off bysettingssl=false
in 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.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
<username>
- 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
<password>
- Specifies a password with which to authenticate to a MongoDB databasethat uses authentication. Use in conjunction with the
—username
and—authenticationDatabase
options. To force mongo toprompt for a password, enter the—password
option as thelast option and leave out the argument.
New in version 3.4.
Enables network compression for communication between thismongo shell and:
- a
mongod
instance a
mongos
instance.You can specify the following compressors:- zlib (Available starting in MongoDB 3.6)
- zstd (Available starting in MongoDB 4.2)
Important
Messages are compressed when both parties enable networkcompression. Otherwise, messages between the parties areuncompressed.
If you specify multiple compressors, then the order in which you listthe compressors matter as well as the communication initiator. Forexample, if a mongo
shell specifies the following networkcompressors zlib,snappy
and the mongod
specifiessnappy,zlib
, messages between mongo
shell andmongod
uses zlib
.
If the parties do not share at least one common compressor, messagesbetween the parties are uncompressed. For example, if amongo
shell specifies the network compressorzlib
and mongod
specifies snappy
, messagesbetween mongo
shell and mongod
are not compressed.
To connect to a MongoDB cluster via IPv6, you must specifyboth —ipv6
and—host <mongod/mongos IPv6 address>
when starting the mongo shell.
mongod
and mongos
disable IPv6 supportby default. Specifying —ipv6
when connecting to amongod/mongos
does not enable IPv6 support on themongod/mongos
. For documentation on enabling IPv6 supporton the mongod/mongos
, see net.ipv6
.
- mongo admin
The above command will connect the mongo shell to theadmin database of the MongoDB deployment running 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/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 cannotuse —host
or —port
.
New in version 4.0.
Enable the JavaScript engine’s JIT compiler.
Changed in version 4.0: The JavaScript engine’s JIT compiler is now disabled by default.
Disables the JavaScript engine’s JIT compiler.
New in version 3.4.
Allows fields of type javascript andjavascriptWithScope to be automaticallymarshalled to JavaScript functions in the mongo
shell.
With the —disableJavaScriptProtection
flag set, it is possibleto 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 mongo
starts without the—disableJavaScriptProtection
flag) is to convert embeddedJavaScript functions to the non-executable MongoDB shell typeCode
. The following example demonstrates the default behaviorwithin 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-0800 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 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>
- Specifies the authentication database where the specified
—username
has been created.See Authentication Database.
If you do not specify a value for —authenticationDatabase
, mongo uses the databasespecified in the connection string.
Specifies the authentication mechanism the mongo instance uses toauthenticate to the mongod
or mongos
.
Changed in version 4.0: MongoDB removes support for the deprecated MongoDBChallenge-Response (MONGODB-CR
) authentication mechanism.
MongoDB adds support for SCRAM mechanism using the SHA-256 hashfunction (SCRAM-SHA-256
).
ValueDescriptionSCRAM-SHA-1RFC 5802 standardSalted Challenge Response Authentication Mechanism using the SHA-1hash function.SCRAM-SHA-256RFC 7677 standardSalted Challenge Response Authentication Mechanism using the SHA-256hash function.
Requires featureCompatibilityVersion set to 4.0
.
New in version 4.0.
MONGODB-X509MongoDB TLS/SSL certificate authentication.GSSAPI (Kerberos)External authentication using Kerberos. This mechanism isavailable only in MongoDB Enterprise.PLAIN (LDAP SASL)External authentication using LDAP. You can also use PLAIN
for authenticating in-database users. PLAIN
transmitspasswords in plain text. This mechanism is available only inMongoDB Enterprise.
New in version 2.6.
Specify the hostname of a service using GSSAPI/Kerberos. Only required if the hostname of a machine doesnot match the hostname resolved by DNS.
This option is available only in MongoDB Enterprise.
New in version 2.6.
Specify the name of the service using GSSAPI/Kerberos. Only required if the service does not use thedefault name of mongodb
.
This option is available only in MongoDB Enterprise.
TLS Options
Note
Starting in version 4.0, mongo
disables support for TLS 1.0encryption on systems where TLS 1.1+ is available. Formore details, see Disable TLS 1.0.
See
Configure mongod and mongos for TLS/SSL for fulldocumentation of MongoDB’s support.
New in version 4.2.
Enables connection to a mongod
or mongos
that hasTLS/SSL support enabled.
Starting in version 3.2.6, if —tlsCAFile
or net.tls.CAFile
(or their aliases —sslCAFile
or ssl.CAFile
) is notspecified, the system-wide CA certificate store will be used whenconnecting to an TLS/SSL-enabled server. In previous versions ofMongoDB, the mongo
shell exited with an error that itcould not validate the certificate.
To use x.509 authentication, —tlsCAFile
or net.tls.CAFile
must be specified unless using —tlsCertificateSelector
or—net.tls.certificateSelector
. Or if using the ssl
aliases,—sslCAFile
or net.ssl.CAFile
must be specified unless using—sslCertificateSelector
or net.ssl.certificateSelector
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Specifies the .pem
file that contains both the TLS/SSLcertificate and key for the mongo
shell. Specify thefile name of the .pem
file using relative or absolute paths.
This option is required when using the —tls
option to connect to a mongod
or mongos
instance that requires client certificates. That is, themongo
shell present this certificate to the server.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Specifies the password to de-crypt the certificate-key file (i.e.—tlsCertificateKeyFile
).
Use the —tlsCertificateKeyFilePassword
option only if thecertificate-key file is encrypted. In all cases, the mongo willredact the password from all logging and reporting output.
If the private key in the PEM file is encrypted and you do notspecify the —tlsCertificateKeyFilePassword
option, the mongo will prompt for apassphrase. See TLS/SSL Certificate Passphrase.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Specifies the .pem
file that contains the root certificatechain from the Certificate Authority. This file is used to validatethe certificate presented by themongod
/mongos
instance.
Specify the file name of the .pem
file using relative orabsolute paths.
Starting in version 3.2.6, if —tlsCAFile
or net.tls.CAFile
(or their aliases —sslCAFile
or ssl.CAFile
) is notspecified, the system-wide CA certificate store will be used whenconnecting to an TLS/SSL-enabled server. In previous versions ofMongoDB, the mongo
shell exited with an error that itcould not validate the certificate.
To use x.509 authentication, —tlsCAFile
or net.tls.CAFile
must be specified unless using —tlsCertificateSelector
or—net.tls.certificateSelector
. Or if using the ssl
aliases,—sslCAFile
or net.ssl.CAFile
must be specified unless using—sslCertificateSelector
or net.ssl.certificateSelector
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Specifies the .pem
file that contains the Certificate RevocationList. Specify the file name of the .pem
file using relative orabsolute paths.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Disables the validation of the hostnames in the certificate presentedby the mongod
/mongos
instance. Allowsmongo to connect to MongoDB instances even if the hostname inthe server certificates do not match the server’s host.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Bypasses the validation checks for the certificates presented by themongod
/mongos
instance and allowsconnections to servers that present invalid certificates.
Note
Starting in MongoDB 4.0, if you specify—sslAllowInvalidCertificates
ornet.ssl.allowInvalidCertificates: true
(or in MongoDB 4.2, thealias —tlsAllowInvalidateCertificates
ornet.tls.allowInvalidCertificates: true
) when using x.509authentication, an invalid certificate is only sufficient toestablish a TLS/SSL connection but is insufficient forauthentication.
Warning
Although available, avoid using the—sslAllowInvalidCertificates
option if possible. If the use of—sslAllowInvalidCertificates
is necessary, only use the optionon systems where intrusion is not possible.
If the mongo
shell (and otherMongoDB Tools) runs with the—sslAllowInvalidCertificates
option, themongo
shell (and otherMongoDB Tools) will not attempt to validatethe server certificates. This creates a vulnerability to expiredmongod
and mongos
certificates aswell as to foreign processes posing as validmongod
or mongos
instances. If youonly need to disable the validation of the hostname in theTLS/SSL certificates, see —sslAllowInvalidHostnames
.
When using the allowInvalidCertificates
setting,MongoDB logs as a warning the use of the invalid certificate.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
New in version 4.2.
Directs the mongo to use the FIPS mode of the TLS/SSLlibrary. Your system must have a FIPS compliant library to usethe —tlsFIPSMode
option.
Note
FIPS-compatible TLS/SSL isavailable only in MongoDB Enterprise. SeeConfigure MongoDB for FIPS for more information.
New in version 4.2: Available on Windows and macOS as an alternative to —tlsCertificateKeyFile
.
The —tlsCertificateKeyFile
and —tlsCertificateSelector
options are mutually exclusive. You can onlyspecify one.
Specifies a certificate property in order to select a matchingcertificate from the operating system’s certificate store.
—tlsCertificateSelector
accepts an argument of the format <property>=<value>
where the property can be one of the following:
PropertyValue typeDescriptionsubject
ASCII stringSubject name or common name on certificatethumbprint
hex stringA sequence of bytes, expressed as hexadecimal, used toidentify a public key by its SHA-1 digest.
The thumbprint
is sometimes referred to as afingerprint
.
When using the system SSL certificate store, OCSP (OnlineCertificate Status Protocol) is used to validate the revocationstatus of certificates.
New in version 4.2.
Disables the specified TLS protocols. The option recognizes thefollowing protocols: TLS1_0
, TLS1_1
, TLS1_2
, andstarting in version 4.0.4 (and 3.6.9), TLS1_3
.
- On macOS, you cannot disable
TLS1_1
and leave bothTLS1_0
andTLS1_2
enabled. You must also disable at least one of the othertwo; for example,TLS1_0,TLS1_1
. - To list multiple protocols, specify as a comma separated list ofprotocols. For example
TLS1_0,TLS1_1
. - The specified disabled protocols overrides any default disabledprotocols.Starting in version 4.0, MongoDB disables the use of TLS 1.0 if TLS1.1+ is available on the system. To enable thedisabled TLS 1.0, specify
none
to—tlsDisabledProtocols
. See Disable TLS 1.0.
SSL Options (Deprecated)
Important
Starting in version 4.2, the SSL options are deprecated. Use the TLScounterparts instead. The SSL protocol is deprecated and MongoDBsupports TLS 1.0 and later.
Note
Starting in version 4.0, mongo
disables support for TLS 1.0encryption on systems where TLS 1.1+ is available. Formore details, see Disable TLS 1.0.
Deprecated since version 4.2: Use —tls
instead.
Enables connection to a mongod
or mongos
that hasTLS/SSL support enabled.
Starting in version 3.2.6, if —tlsCAFile
or net.tls.CAFile
(or their aliases —sslCAFile
or ssl.CAFile
) is notspecified, the system-wide CA certificate store will be used whenconnecting to an TLS/SSL-enabled server. In previous versions ofMongoDB, the mongo
shell exited with an error that itcould not validate the certificate.
To use x.509 authentication, —tlsCAFile
or net.tls.CAFile
must be specified unless using —tlsCertificateSelector
or—net.tls.certificateSelector
. Or if using the ssl
aliases,—sslCAFile
or net.ssl.CAFile
must be specified unless using—sslCertificateSelector
or net.ssl.certificateSelector
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsCertificateKeyFile
instead.
Specifies the .pem
file that contains both the TLS/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 a mongod
or mongos
that hasCAFile
enabled withoutallowConnectionsWithoutCertificates
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsCertificateKeyFilePassword
instead.
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, the mongo willredact the password from all logging and reporting output.
If the private key in the PEM file is encrypted and you do notspecify the —sslPEMKeyPassword
option, the mongo will prompt for apassphrase. See TLS/SSL Certificate Passphrase.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsCAFile
instead.
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.
Starting in version 3.2.6, if —tlsCAFile
or net.tls.CAFile
(or their aliases —sslCAFile
or ssl.CAFile
) is notspecified, the system-wide CA certificate store will be used whenconnecting to an TLS/SSL-enabled server. In previous versions ofMongoDB, the mongo
shell exited with an error that itcould not validate the certificate.
To use x.509 authentication, —tlsCAFile
or net.tls.CAFile
must be specified unless using —tlsCertificateSelector
or—net.tls.certificateSelector
. Or if using the ssl
aliases,—sslCAFile
or net.ssl.CAFile
must be specified unless using—sslCertificateSelector
or net.ssl.certificateSelector
.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsCertificateSelector
instead.
New in version 4.0: Available on Windows and macOS as an alternative to —tlsCertificateKeyFile
.
—tlsCertificateKeyFile
and —sslCertificateSelector
options are mutually exclusive. You can onlyspecify one.
Specifies a certificate property in order to select a matchingcertificate from the operating system’s certificate store.
—sslCertificateSelector
accepts an argument of the format <property>=<value>
where the property can be one of the following:
PropertyValue typeDescriptionsubject
ASCII stringSubject name or common name on certificatethumbprint
hex stringA sequence of bytes, expressed as hexadecimal, used toidentify a public key by its SHA-1 digest.
The thumbprint
is sometimes referred to as afingerprint
.
When using the system SSL certificate store, OCSP (OnlineCertificate Status Protocol) is used to validate the revocationstatus of certificates.
Deprecated since version 4.2: Use —tlsCRLFile
instead.
Specifies the .pem
file that contains the Certificate RevocationList. Specify the file name of the .pem
file using relative orabsolute paths.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsFIPSMode
instead.
Directs the mongo to use the FIPS mode of the TLS/SSLlibrary. Your system must have a FIPS compliant library to usethe —sslFIPSMode
option.
Note
FIPS-compatible TLS/SSL isavailable only in MongoDB Enterprise. SeeConfigure MongoDB for FIPS for more information.
Deprecated since version 4.2: Use —tlsAllowInvalidCertificates
instead.
Bypasses the validation checks for server certificates and allowsthe use of invalid certificates to connect.
Note
Starting in MongoDB 4.0, if you specify—sslAllowInvalidCertificates
ornet.ssl.allowInvalidCertificates: true
(or in MongoDB 4.2, thealias —tlsAllowInvalidateCertificates
ornet.tls.allowInvalidCertificates: true
) when using x.509authentication, an invalid certificate is only sufficient toestablish a TLS/SSL connection but is insufficient forauthentication.
Warning
Although available, avoid using the—sslAllowInvalidCertificates
option if possible. If the use of—sslAllowInvalidCertificates
is necessary, only use the optionon systems where intrusion is not possible.
If the mongo
shell (and otherMongoDB Tools) runs with the—sslAllowInvalidCertificates
option, themongo
shell (and otherMongoDB Tools) will not attempt to validatethe server certificates. This creates a vulnerability to expiredmongod
and mongos
certificates aswell as to foreign processes posing as validmongod
or mongos
instances. If youonly need to disable the validation of the hostname in theTLS/SSL certificates, see —sslAllowInvalidHostnames
.
When using the allowInvalidCertificates
setting,MongoDB logs as a warning the use of the invalid certificate.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsAllowInvalidHostnames
instead.
Disables the validation of the hostnames in TLS/SSL certificates. Allowsmongo to connect to MongoDB instances even if the hostname in theircertificates do not match the specified hostname.
For more information about TLS/SSL and MongoDB, seeConfigure mongod and mongos for TLS/SSL andTLS/SSL Configuration for Clients .
Deprecated since version 4.2: Use —tlsDisabledProtocols
instead.
Disables the specified TLS protocols. The option recognizes thefollowing protocols: TLS1_0
, TLS1_1
, TLS1_2
, andstarting in version 4.0.4 (and 3.6.9), TLS1_3
.
- On macOS, you cannot disable
TLS1_1
and leave bothTLS1_0
andTLS1_2
enabled. You must also disable at least one of the othertwo; for example,TLS1_0,TLS1_1
. - To list multiple protocols, specify as a comma separated list ofprotocols. For example
TLS1_0,TLS1_1
. - The specified disabled protocols overrides any default disabledprotocols.Starting in version 4.0, MongoDB disables the use of TLS 1.0 if TLS1.1+ is available on the system. To enable thedisabled TLS 1.0, specify
none
to—sslDisabledProtocols
. See Disable TLS 1.0.
New in version 3.6.5.
Sessions
New in version 3.6.
Enables retryable writes as the default for sessions in themongo
shell.
For more information on sessions, see Client Sessions and Causal Consistency Guarantees.
Client-Side Field Level Encryption Options
—awsAccessKeyId
<string>
- An AWS Access Keyassociated to an IAM user with
List
andRead
permissions for theAWS Key Management Service (KMS). The mongo shell uses the specified—awsAccessKeyId
to access the KMS.
—awsAccessKeyId
is required for enabling Client-Side Field Level Encryptionfor the mongo shell session. —awsAccessKeyId
requires all of the followingcommand line options:
—awsSecretAccessKey
—keyVaultNamespace
If—awsAccessKeyId
is omitted, use theMongo()
constructor within the shellsession to enable client-side field level encryption.
To mitigate the risk of leaking access keys into logs, consider specifyingan environmental variable to —awsAccessKeyId
.
—awsSecretAccessKey
<string>
- An AWS Secret Keyassociated to the specified
—awsAccessKeyId
.
—awsSecretAccessKey
is required for enabling Client-Side Field Level Encryptionfor the mongo shell session. —awsSecretAccessKey
requires all of the followingcommand line options:
—awsAccessKeyId
—keyVaultNamespace
If—awsSecretAccessKey
and 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 specifyingan environmental variable to —awsSecretAccessKey
.
—awsSessionToken
<string>
- An AWS Session Tokenassociated to the specified
—awsAccessKeyId
.
—awsSessionToken
is required for enabling Client-Side Field Level Encryptionfor the mongo shell session. —awsSessionToken
requires all of the followingcommand line options:
—awsAccessKeyId
—awsSecretAccessKey
—keyVaultNamespace
If—awsSessionToken
and 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 specifyingan environmental variable to —awsSessionToken
.
—keyVaultNamespace
<string>
- The full namespace (
<database>.<collection>
) of the collection used as akey vault for Client-Side Field Level Encryption.—keyVaultNamespace
isrequired for enabling client-side field level encryption. for the mongoshell session. mongo creates the specified namespace if it does notexist.
—keyVaultNamespace
requires all of the following command line options:
—awsAccessKeyId
—awsSecretAccessKey
If—keyVaultNamespace
and its supporting options are omitted, use theMongo()
constructor within the shell session to enable client-side field levelencryption.
Files
~/.dbshell
mongo
maintains a history of commands in the.dbshell
file.
Note
mongo
does not record interaction related toauthentication in the history file, includingauthenticate
and db.createUser()
.
~/.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 withmongo —eval
orby specifying a .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.js
file located in theHOME
directory, themongo
shell evaluates the global/etc/mongorc.js
file _before_evaluating the user’s.mongorc.js
file.
/etc/mongorc.js
must have read permission for the userrunning the shell. The —norc
option for mongo
suppresses 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 from1
to10
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 from1
to10
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.dbshell
file.
HOMEDRIVE
- On Windows systems,
HOMEDRIVE
specifies the path thedirectory wheremongo
will read the.mongorc.js
file and write the.dbshell
file.
HOMEPATH
- Specifies the Windows path to the home directory where
mongo
will read the.mongorc.js
file and writethe.dbshell
file.
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 mongo shell |
Ctrl-D | Delete a char (or exit the mongo shell) |
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 cls | 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 emacskeybindings. |
Use
Typically users invoke the shell with the mongo
command atthe system prompt. Consider the following examples for otherscenarios.
Connect to a mongod Instance with Access Control
To connect to a database on a remote host using authentication and anon-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 yoursituation and substitute or omit the —port
asneeded.
If you do not specify the password to the —password
or -p
command-line option, themongo
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 theDNS Seedlist Connection Format, use the —host
optionto specify the connection string to the mongo
shell. Inthe 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 tothe replica set:
- mongo --host "mongodb+srv://server.example.com/?username=allison"
The mongo
shell will automatically prompt you to providethe password for the user specified in the username
option.
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 promptedrather than provided on the command-line, use the following form:
- mongo script-file.js -u <user> -p
See also
Use —eval to Execute JavaScript Code
You may use the —eval
option to executeJavaScript directly from the command line.
For example, the following operation evaluates a JavaScript stringwhich 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)"
See also