- Reference >
- MongoDB Package Components >
mongo
mongo¶
On this page
Description¶
-
mongo¶
mongo is an interactive JavaScript shell interface to
MongoDB, which provides a powerful interface for systems
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. This
document addresses the basic invocation of the mongo shell
and an overview of its usage.
Options¶
Core Options¶
-
mongo¶
-
--shell¶ Enables 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.
-
--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.json start up.
-
--quiet¶ Silences output from the shell during the connection process.
-
--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),mongoverifies that the hostname of themongodormongosto which you are connecting matches the CN or SAN of themongodormongos’s--sslPEMKeyFilecertificate. If the hostname does not match the CN/SAN,mongowill fail to connect.
-
--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.
-
--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.
-
--help,-h¶ Returns information on the options and use of
mongo.
-
--version¶ Returns the
mongorelease 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
mongoshell and:Important
Messages are compressed when both parties enable network compression. Otherwise, messages between the parties are uncompressed.
You can specify the following compressor:
-
--ipv6¶ Removed in version 3.0.
Enables IPv6 support and allows
mongoto connect to the MongoDB instance using an IPv6 network. Prior to MongoDB 3.0, you had to specify--ipv6to use IPv6. In MongoDB 3.0 and later, IPv6 is always enabled.
-
<dbname>¶ 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.
-
--disableJavaScriptJIT¶ New in version 3.2.
Disables use of 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
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-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
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 database in which the user is created. See Authentication Database.
If you do not specify a value for
--authenticationDatabase,mongouses the database specified in the connection string.
-
--authenticationMechanism<name>¶ Default: SCRAM-SHA-1
Changed in version 2.6: Added support for the
PLAINandMONGODB-X509authentication mechanisms.Changed in version 3.0: Added support for the
SCRAM-SHA-1authentication mechanism. Changed default mechanism toSCRAM-SHA-1.Specifies the authentication mechanism the
mongoinstance uses to authenticate to themongodormongos.Value Description SCRAM-SHA-1 RFC 5802 standard Salted Challenge Response Authentication Mechanism using the SHA1 hash function. MONGODB-CR MongoDB challenge/response authentication. 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 PLAINfor authenticating in-database users.PLAINtransmits 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¶ Enables connection to a
mongodormongosthat has TLS/SSL support enabled.Changed in version 3.2.6: MongoDB 3.2.6 adds support for checking a certificate against the system CA store, allowing you to run the
mongoshell with the--ssloption without including--sslCAFileorsslAllowInvalidCertificates.If the
mongodormongosto which themongoshell is connecting presents a certificate signed with a CA trusted by the operating system, themongoshell will connect without error. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
-
--sslPEMKeyFile<filename>¶ New in version 2.4.
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.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
-
--sslPEMKeyPassword<value>¶ New in version 2.4.
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.Changed in version 2.6: If the private key in the PEM file is encrypted and you do not specify the
--sslPEMKeyPasswordoption, themongowill prompt for a passphrase. See SSL Certificate Passphrase.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
-
--sslCAFile<filename>¶ New in version 2.4.
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.Changed in version 3.2.6: MongoDB 3.2.6 adds support for checking a certificate against the system CA store, allowing you to run the
mongoshell with the--ssloption without including--sslCAFileorsslAllowInvalidCertificates.If the
mongodormongosto which themongoshell is connecting presents a certificate signed with a CA trusted by the operating system, themongoshell will connect without error. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.Warning
For SSL connections (
--ssl) tomongodandmongos, if themongoshell runs with the--sslAllowInvalidCertificatesoption , themongoshell will not attempt to validate the server certificates. This creates a vulnerability to expiredmongodandmongoscertificates as well as to foreign processes posing as validmongodormongosinstances. Only use--sslAllowInvalidCertificateson systems where intrusion is not possible.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
-
--sslCRLFile<filename>¶ New in version 2.4.
Specifies the
.pemfile that contains the Certificate Revocation List. Specify the file name of the.pemfile using relative or absolute paths.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
-
--sslFIPSMode¶ New in version 2.6.
Directs the
mongoto use the FIPS mode of the installed OpenSSL library. Your system must have a FIPS compliant OpenSSL library to use the--sslFIPSModeoption.Note
FIPS-compatible SSL is available only in MongoDB Enterprise. See Configure MongoDB for FIPS for more information.
-
--sslAllowInvalidCertificates¶ New in version 2.6.
Bypasses the validation checks for server certificates and allows the use of invalid certificates. When using the
allowInvalidCertificatessetting, MongoDB logs as a warning the use of the invalid certificate.Changed in version 3.2.6: MongoDB 3.2.6 adds support for checking a certificate against the system CA store, allowing you to run the
mongoshell with the--ssloption without including--sslCAFileorsslAllowInvalidCertificates.If the
mongodormongosto which themongoshell is connecting presents a certificate signed with a CA trusted by the operating system, themongoshell will connect without error. In previous versions of MongoDB, themongoshell exited with an error that it could not validate the certificate.Warning
For SSL connections (
--ssl) tomongodandmongos, if themongoshell runs with the--sslAllowInvalidCertificatesoption , themongoshell will not attempt to validate the server certificates. This creates a vulnerability to expiredmongodandmongoscertificates as well as to foreign processes posing as validmongodormongosinstances. Only use--sslAllowInvalidCertificateson systems where intrusion is not possible.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
-
--sslAllowInvalidHostnames¶ New in version 3.0.
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.Changed in version 3.0: Most MongoDB distributions include support for TLS/SSL. See Configure mongod and mongos for TLS/SSL and TLS/SSL Configuration for Clients for more information about TLS/SSL and MongoDB.
Changed in version 3.4: If
--sslCAFileis not specified when connecting to an TLS/SSL-enabled server, the system-wide CA certificate store will be used.
Files¶
~/.dbshellmongomaintains a history of commands in the.dbshellfile.Note
mongodoes not record interaction related to authentication in the history file, includingauthenticateanddb.createUser().Warning
Versions of Windows
mongo.exeearlier than 2.2.0 will save the .dbshell file in themongo.exeworking directory.
~/.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 with--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¶
-
EDITOR¶ Specifies the path to an editor to use with the
editshell command. A JavaScript variableEDITORwill override the value ofEDITOR.
-
HOME¶ Specifies the path to the home directory where
mongowill read the.mongorc.jsfile and write the.dbshellfile.
-
HOMEDRIVE¶ On Windows systems,
HOMEDRIVEspecifies the path the directory wheremongowill read the.mongorc.jsfile and write the.dbshellfile.
-
HOMEPATH¶ Specifies 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 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.
To connect to a database on a remote host using authentication and a non-standard port, use the following form:
mongo --username <user> --password <pass> --host <host> --port 28015
Alternatively, consider the following short form:
mongo -u <user> -p <pass> --host <host> --port 28015
Replace <user>, <pass>, and <host> with the appropriate
values for your situation and substitute or omit the --port
as needed.
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
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.