The mongo Shell

The mongo shell is an interactive JavaScript interface toMongoDB. You can use the mongo shell to query and updatedata as well as perform administrative operations.

The mongo shell is included as part of the MongoDB Server installation. MongoDB also provides the mongoshell as a standalone package. To download the standalone mongoshell package:

  • Open the Download Center. For themongo 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.

Once you have installed and have started MongoDB, connectthe mongo shell to your running MongoDB instance.

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.

Start the mongo Shell and Connect to MongoDB

Prerequisites

Ensure that MongoDB is running before attempting to start themongo shell.

Open a terminal window (or a command prompt for Windows) and go to your<mongodb installation dir>/bin directory:

  1. cd <mongodb installation dir>/bin

Tip

Adding your <mongodb installation dir>/bin to the PATHenvironment variable allows you to type mongo instead of havingto go to the <mongodb installation dir>/bin directory or specifythe full path to the binary.

Local MongoDB Instance on Default Port

You can run mongo shell without any command-line optionsto connect to a MongoDB instancerunning on your localhost with default port 27017:

  1. mongo

Local MongoDB Instance on a Non-default Port

To explicitly specify the port, include the —port command-line option. For example, to connect to a MongoDBinstance running on localhost with a non-default port 28015:

  1. mongo --port 28015

MongoDB Instance on a Remote Host

To explicitly specify the hostname and/or port,

  • You can specify a connection string. For example, to connect to a MongoDBinstance running on a remote host machine:
  1. mongo "mongodb://mongodb0.example.com:28015"
  • You can use the command-line option —host <host>:<port>. For example, to connect to a MongoDB instancerunning on a remote host machine:
  1. mongo --host mongodb0.example.com:28015
  • You can use the —host <host> and—port <port> command-line options. Forexample, to connect to a MongoDB instance running on a remote hostmachine:
  1. mongo --host mongodb0.example.com --port 28015

MongoDB Instance with Authentication

To connect to a MongoDB instance requires authentication:

  • You can specify the username, authentication database, and optionallythe password in the connection string. For example, to connect andauthenticate to a remote MongoDB instance as user alice:

Note

If you do not specify the password in the connection string, theshell will prompt for the password.

  1. mongo "mongodb://alice@mongodb0.examples.com:28015/?authSource=admin"

Note

If you specify —password without the user’s password, theshell will prompt for the password.

  1. mongo --username alice --password --authenticationDatabase admin --host mongodb0.examples.com --port 28015

Connect to a MongoDB Replica Set

To connect to a replica set:

  1. mongo "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA"
  1. mongo "mongodb+srv://server.example.com/"

Note

Use of the +srv connection string modifier automatically setsthe ssl option to true for the connection.

  1. mongo --host replA/mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017

TLS/SSL Connection

For TLS/SSL connections,

  1. mongo "mongodb://mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017/?replicaSet=replA&ssl=true"
  1. mongo "mongodb+srv://server.example.com/"

Note

Use of the +srv connection string modifier automatically setsthe ssl option to true for the connection.

  • You can specify —ssl command-line option.For example, to connect to replica set named replA:
  1. mongo --ssl --host replA/mongodb0.example.com.local:27017,mongodb1.example.com.local:27017,mongodb2.example.com.local:27017

See also

For more information on the options used in the connection examplesas well as other options, see mongo reference and examples of starting up mongo.

Working with the mongo Shell

To display the database you are using, type db:

  1. db

The operation should return test, which is the default database.

To switch databases, issue the use <db> helper, as in thefollowing example:

  1. use <database>

See also db.getSiblingDB() method to access adifferent database from the current database without switching yourcurrent database context (i.e. db).

To list the databases available to the user, use the helper showdbs. [1]

You can switch to non-existing databases. When you first store data inthe database, such as by creating a collection, MongoDB creates thedatabase. For example, the following creates both the databasemyNewDatabase and the collection myCollection duringthe insertOne() operation:

  1. use myNewDatabase
  2. db.myCollection.insertOne( { x: 1 } );

The db.myCollection.insertOne() is oneof the methods available in the mongo shell.

  • db refers to the current database.
  • myCollection is the name of the collection.

If the mongo shell does not accept the name of a collection,you can use the alternative db.getCollection() syntax.For instance, if a collection name contains a space or hyphen, startswith a number, or conflicts with a built-in function:

  1. db.getCollection("3 test").find()
  2. db.getCollection("3-test").find()
  3. db.getCollection("stats").find()

The mongo shell prompt has a limit of 4095 codepoints foreach line. If you enter a line with more than 4095 codepoints, theshell will truncate it.

For more documentation of basic MongoDB operations in themongo shell, see:

[1]If the deployment runs with access control, the operationreturns different values based on user privileges. SeelistDatabases Behavior for details.

Format Printed Results

The db.collection.find() method returns a cursor tothe results; however, in the mongo shell, if the returnedcursor is not assigned to a variable using the var keyword, thenthe cursor is automatically iterated up to 20 times to print up to thefirst 20 documents that match the query. The mongo shellwill prompt Type it to iterate another 20 times.

To format the printed result, you can add the .pretty() to theoperation, as in the following:

  1. db.myCollection.find().pretty()

In addition, you can use the following explicit print methods in themongo shell:

  • print() to print without formatting
  • print(tojson(<obj>)) to print with JSON formatting andequivalent to printjson()
  • printjson() to print with JSON formatting and equivalentto print(tojson(<obj>))

For more information and examples on cursor handling in themongo shell, see Iterate a Cursor in the mongo Shell. See alsoCursor Help for list of cursor help in themongo shell.

Multi-line Operations in the mongo Shell

If you end a line with an open parenthesis ('('), an open brace('{'), or an open bracket ('['), then the subsequent lines startwith ellipsis ("…") until you enter the corresponding closingparenthesis (')'), the closing brace ('}') or the closingbracket (']'). The mongo shell waits for the closingparenthesis, closing brace, or the closing bracket before evaluatingthe code, as in the following example:

  1. > if ( x > 0 ) {
  2. ... count++;
  3. ... print (x);
  4. ... }

You can exit the line continuation mode if you enter two blanklines, as in the following example:

  1. > if (x > 0
  2. ...
  3. ...
  4. >

Tab Completion and Other Keyboard Shortcuts

The mongo shell supports keyboard shortcuts. For example,

  • Use the up/down arrow keys to scroll through command history. See.dbshell documentation for moreinformation on the .dbshell file.

  • Use <Tab> to autocomplete or to list the completionpossibilities, as in the following example which uses <Tab> tocomplete the method name starting with the letter 'c':

  1. db.myCollection.c<Tab>

Because there are many collection methods starting with the letter'c', the <Tab> will list the various methods that start with'c'.

For a full list of the shortcuts, see Shell Keyboard Shortcuts

.mongorc.js File

When starting, mongo checks the user’s HOMEdirectory for a JavaScript file named .mongorc.js. If found, mongo interprets thecontent of .mongorc.js before displaying the prompt for thefirst time. If you use the shell to evaluate a JavaScript file orexpression, either by using the —evaloption on the command line or by specifying a .js file tomongo, mongo will read the.mongorc.js file after the JavaScript has finished processing.You can prevent .mongorc.js from being loaded by using the—norc option.

Exit the Shell

To exit the shell, type quit() or use the <Ctrl-C> shortcut.

See also