Navigation

mongo

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 part of the MongoDB distributions.

Note

Starting in version 4.0, mongo disables 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 mongo shell without any command-line options use the default settings:

    mongo
    
  • You can run mongo shell with a connection string that specifies the host and port and other connection options. For example:

    mongo mongodb://mongodb0.example.com:28015/testdb?ssl=true
    

    For more information on the connection string options, see Connection String URI Format.

  • You can run mongo shell with various command-line options. For example:

    mongo --host mongodb0.example.com:28015 [additional options]
    
    mongo --host mongodb0.example.com --port 28015 [additional options]
    

    For more information on the options available, see Options.

Options

Core Options

--shell

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

--nodb

Prevents the shell from connecting to any database instances. Later, to connect to a database within the shell, see Opening New Connections.

--norc

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

--quiet

Silences output from the shell during the connection process.

--port <port>

Specifies the port where the mongod or mongos instance is listening. If --port is not specified, mongo attempts to connect to port 27017.

--host <hostname>

Specifies the name of the host machine where the mongod or mongos is running. If this is not specified, mongo attempts to connect to a MongoDB process running on the 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 (specified in --host option or the connection string) matches the SAN (or, if SAN is not present, the CN) in the certificate presented by the mongod or mongos. If SAN is present, mongo does not match against the CN. If the hostname does not match the SAN (or CN), the mongo shell will fail to connect.
For DNS seedlist connections,

Specify the connection protocol as mongodb+srv, followed by the DNS SRV hostname record and any options. The authSource and replicaSet options, if included in the connection string, will override any corresponding DNS-configured options set in the TXT record. Use of the mongodb+srv: connection string implicitly enables TLS/SSL (normally set with ssl=true) for the client connection. The TLS/SSL option can be turned off by setting ssl=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 database that 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 database that uses authentication. Use in conjunction with the --username and --authenticationDatabase options. To force mongo to prompt for a password, enter the --password option as the last option and leave out the argument.

--help, -h

Returns information on the options and use of mongo.

--version

Returns the mongo release number.

--verbose

Increases the verbosity of the output of the shell during the connection process.

--networkMessageCompressors <string>

New in version 3.4.

Enables network compression for communication between this mongo shell and:

You can specify the following compressors:

  • snappy
  • zlib (Available in MongoDB 3.6 or greater)

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 mongo shell specifies the following network compressors zlib,snappy and the mongod specifies snappy,zlib, messages between mongo shell and mongod uses zlib.

If the parties do not share at least one common compressor, messages between the parties are uncompressed. For example, if a mongo shell specifies the network compressor zlib and mongod specifies snappy, messages between mongo shell and mongod are not compressed.

--ipv6

Removed in version 3.0.

Enables IPv6 support and allows mongo to connect to the MongoDB instance using an IPv6 network. Prior to MongoDB 3.0, you had to specify --ipv6 to use IPv6. In MongoDB 3.0 and later, IPv6 is always enabled.

<db name>

Specifies the name of the database to connect to. For example:

mongo admin

The above command will connect the mongo shell 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 --host or --port.

--enableJavaScriptJIT

New in version 4.0.

Enable the JavaScript engine’s JIT compiler.

--disableJavaScriptJIT

Changed in version 4.0: The JavaScript engine’s JIT compiler is now disabled by default.

Disables the JavaScript engine’s JIT compiler.

--disableJavaScriptProtection

New in version 3.4.

Allows fields of type javascript and javascriptWithScope to be automatically marshalled to JavaScript functions in the mongo shell.

With the --disableJavaScriptProtection flag 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 mongo starts without the --disableJavaScriptProtection flag) is to convert embedded JavaScript functions to the non-executable MongoDB shell type Code. 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-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 should be the last option specified.

Optional

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

mongo file.js --username username --password

Use the --shell option to return to a shell after the file finishes running.

Authentication Options

--authenticationDatabase <dbname>

Specifies the database in which the user is created. See Authentication Database.

If you do not specify a value for --authenticationDatabase, mongo uses the database specified in the connection string.

--authenticationMechanism <name>

Default: SCRAM-SHA-1

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

Changed in version 4.0: MongoDB removes support for the deprecated MongoDB Challenge-Response (MONGODB-CR) authentication mechanism.

MongoDB adds support for SCRAM mechanism using the SHA-256 hash function (SCRAM-SHA-256).

Value Description
SCRAM-SHA-1 RFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA-1 hash function.
SCRAM-SHA-256

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-X509 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 PLAIN for authenticating in-database users. PLAIN transmits passwords in plain text. This mechanism is available only in MongoDB Enterprise.
--gssapiHostName

New in version 2.6.

Specify 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.

--gssapiServiceName

New in version 2.6.

Specify 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/SSL Options

--ssl

Changed in version 3.2.6.

Enables connection to a mongod or mongos that has TLS/SSL support enabled.

Starting in version 3.2.6, if --sslCAFile or ssl.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, the mongo shell exited with an error that it could not validate the certificate.

If using x.509 authentication, --sslCAFile or ssl.CAFile must be specified unless using --sslCertificateSelector.

For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslPEMKeyFile <filename>

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

This option is required when using the --ssl option to connect to a mongod or mongos that has CAFile enabled without allowConnectionsWithoutCertificates.

For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslPEMKeyPassword <value>

Specifies the password to de-crypt the certificate-key file (i.e. --sslPEMKeyFile). Use the --sslPEMKeyPassword option only if the certificate-key file is encrypted. In all cases, the mongo will 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 --sslPEMKeyPassword option, the mongo will prompt for a passphrase. See TLS/SSL Certificate Passphrase.

For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslCAFile <filename>

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

Starting in version 3.2.6, if --sslCAFile or ssl.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, the mongo shell exited with an error that it could not validate the certificate.

If using x.509 authentication, --sslCAFile or ssl.CAFile must be specified unless using --sslCertificateSelector.

For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslCertificateSelector <parameter>=<value>

Deprecated since version 4.2: Use --tlsCertificateSelector instead.

New in version 4.0: Available on Windows and macOS as an alternative to --sslPEMKeyFile.

--sslPEMKeyFile and --sslCertificateSelector options 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.

--sslCertificateSelector accepts an argument of the format <property>=<value> where the property can be one of the following:

Property Value type Description
subject ASCII string Subject name or common name on certificate
thumbprint hex string

A sequence of bytes, expressed as hexadecimal, used to identify a public key by its SHA-1 digest.

The thumbprint is sometimes referred to as a fingerprint.

--sslCRLFile <filename>

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

For more information about TLS/SSL and MongoDB, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslFIPSMode

New in version 2.6.

Directs the mongo to use the FIPS mode of the TLS/SSL library. Your system must have a FIPS compliant library to use the --sslFIPSMode option.

Note

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

--sslAllowInvalidCertificates

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 --sslAllowInvalidCertificates or ssl.allowInvalidCertificates: true when 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 --sslAllowInvalidCertificates option if possible. If the use of --sslAllowInvalidCertificates is necessary, only use the option on systems where intrusion is not possible.

If the mongo shell (and other MongoDB Tools) runs with the --sslAllowInvalidCertificates option, the mongo shell (and other MongoDB Tools) will not attempt to validate the server certificates. This creates a vulnerability to expired mongod and mongos certificates as well as to foreign processes posing as valid mongod or mongos instances. If you only need to disable the validation of the hostname in the TLS/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, see Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslAllowInvalidHostnames

New in version 3.0.

Disables the validation of the hostnames in TLS/SSL certificates. Allows mongo to 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 mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients .

--sslDisabledProtocols <string>

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_1 and leave both TLS1_0 and TLS1_2 enabled. 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 none to --sslDisabledProtocols. See Disable TLS 1.0.

New in version 3.6.5.

Sessions

--retryWrites

New in version 3.6.

Enables retryable writes as the default for sessions in the mongo shell.

For more information on sessions, see Client Sessions and Causal Consistency Guarantees.

Files

~/.dbshell

mongo maintains a history of commands in the .dbshell file.

Note

mongo does not record interaction related to authentication in the history file, including authenticate and db.createUser().

~/.mongorc.js

mongo will read the .mongorc.js file from the home directory of the user invoking mongo. In the file, users can define variables, customize the mongo shell 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 with mongo --eval or by specifying a .js file to mongo, mongo will read the .mongorc.js file after the JavaScript has finished processing.

Specify the --norc option to disable reading .mongorc.js.

/etc/mongorc.js

Global mongorc.js file which the mongo shell evaluates upon start-up. If a user also has a .mongorc.js file located in the HOME directory, the mongo 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 user running the shell. The --norc option for mongo suppresses only the user’s .mongorc.js file.

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

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

Environment

EDITOR

Specifies the path to an editor to use with the edit shell command. A JavaScript variable EDITOR will override the value of EDITOR.

HOME

Specifies the path to the home directory where mongo will read the .mongorc.js file and write the .dbshell file.

HOMEDRIVE

On Windows systems, HOMEDRIVE specifies the path the directory where mongo 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 write the .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 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 Seedlist 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.

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 Print Query Results as JSON

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

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

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

←   mongos mongod.exe  →