OPTIONS

Getting Started with the mongo Shell

This document provides a basic introduction to using the mongo shell. See Install MongoDB for instructions on installing MongoDB for your system.

Start the mongo Shell

To start the mongo shell and connect to your MongoDB instance running on localhost with default port:

  1. Go to your <mongodb installation dir>:

    cd <mongodb installation dir>
    
  2. Type ./bin/mongo to start mongo:

    ./bin/mongo
    

    If you have added the <mongodb installation dir>/bin to the PATH environment variable, you can just type mongo instead of ./bin/mongo.

  3. To display the database you are using, type db:

    db
    

    The operation should return test, which is the default database. To switch databases, issue the use <db> helper, as in the following example:

    use <database>
    

    To list the available databases, use the helper show dbs. See also How can I access different databases temporarily? to access a different database from the current database without switching your current database context (i.e. db..)

To start the mongo shell with other options, see examples of starting up mongo and mongo reference which provides details on the available options.

Note

When starting, mongo checks the user’s HOME directory for a JavaScript file named .mongorc.js. If found, mongo interprets the content of .mongorc.js before displaying the prompt for the first time. If you use the shell to evaluate a JavaScript file or expression, either by using the --eval option on the command line or by specifying a .js file to mongo, 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.

Executing Queries

From the mongo shell, you can use the shell methods to run queries, as in the following example:

db.<collection>.find()
  • The db refers to the current database.

  • The <collection> is the name of the collection to query. See Collection Help to list the available collections.

    If the mongo shell does not accept the name of the collection, for instance if the name contains a space, hyphen, or starts with a number, you can use an alternate syntax to refer to the collection, as in the following:

    db["3test"].find()
    
    db.getCollection("3test").find()
    
  • The find() method is the JavaScript method to retrieve documents from <collection>. The find() method returns a cursor to the results; however, in the mongo shell, if the returned cursor is not assigned to a variable using the var keyword, then the cursor is automatically iterated up to 20 times to print up to the first 20 documents that match the query. The mongo shell will prompt Type it to iterate another 20 times.

    You can set the DBQuery.shellBatchSize attribute to change the number of iteration from the default value 20, as in the following example which sets it to 10:

    DBQuery.shellBatchSize = 10;
    

    For more information and examples on cursor handling in the mongo shell, see Cursors.

    See also Cursor Help for list of cursor help in the mongo shell.

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

Print

The mongo shell automatically prints the results of the find() method if the returned cursor is not assigned to a variable using the var keyword. To format the result, you can add the .pretty() to the operation, as in the following:

db.<collection>.find().pretty()

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

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

Evaluate a JavaScript File

You can execute a .js file from within the mongo shell, using the load() function, as in the following:

load("myjstest.js")

This function loads and executes the myjstest.js file.

The load() method accepts relative and absolute paths. If the current working directory of the mongo shell is /data/db, and the myjstest.js resides in the /data/db/scripts directory, then the following calls within the mongo shell would be equivalent:

load("scripts/myjstest.js")
load("/data/db/scripts/myjstest.js")

Note

There is no search path for the load() function. If the desired script is not in the current working directory or the full specified path, mongo will not be able to access the file.

Use a Custom Prompt

You may modify the content of the prompt by creating the variable prompt in the shell. The prompt variable can hold strings as well as any arbitrary JavaScript. If prompt holds a function that returns a string, mongo can display dynamic information in each prompt. Consider the following examples:

Example

Create a prompt with the number of operations issued in the current session, define the following variables:

cmdCount = 1;
prompt = function() {
             return (cmdCount++) + "> ";
         }

The prompt would then resemble the following:

1> db.collection.find()
2> show collections
3>

Example

To create a mongo shell prompt in the form of <database>@<hostname>$ define the following variables:

host = db.serverStatus().host;

prompt = function() {
             return db+"@"+host+"$ ";
         }

The prompt would then resemble the following:

<database>@<hostname>$ use records
switched to db records
records@<hostname>$

Example

To create a mongo shell prompt that contains the system up time and the number of documents in the current database, define the following prompt variable:

prompt = function() {
             return "Uptime:"+db.serverStatus().uptime+" Documents:"+db.stats().objects+" > ";
         }

The prompt would then resemble the following:

Uptime:5897 Documents:6 > db.people.save({name : "James"});
Uptime:5948 Documents:7 >

Use an External Editor in the mongo Shell

New in version 2.2.

In the mongo shell you can use the edit operation to edit a function or variable in an external editor. The edit operation uses the value of your environments EDITOR variable.

At your system prompt you can define the EDITOR variable and start mongo with the following two operations:

export EDITOR=vim
mongo

Then, consider the following example shell session:

MongoDB shell version: 2.2.0
> function f() {}
> edit f
> f
function f() {
    print("this really works");
}
> f()
this really works
> o = {}
{ }
> edit o
> o
{ "soDoes" : "this" }
>

Note

As mongo shell interprets code edited in an external editor, it may modify code in functions, depending on the JavaScript compiler. For mongo may convert 1+1 to 2 or remove comments. The actual changes affect only the appearance of the code and will vary based on the version of JavaScript used but will not affect the semantics of the code.

Exit the Shell

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