w3resource

Introduction to mongo Shell

Usage of multi-line operations in the mongo shell

If a line in mongo shell ends with an open parenthesis ('(') or an open brace ('{'), or an open bracket ('['), then the subsequent lines start with ellipsis ("...") until you enter the corresponding closing parenthesis (')') or the closing brace ('}') or the closing bracket (']'). The mongo shell waits for the proper ending parenthesis before evaluating the code. Here is the example below.

> if ( x > 0 ) {
... count++;
... print (x);
... }

You can exit the line continuation mode if you enter two blank lines. Here is the example below.

> if (x > 0
...
...
>

Access different databases temporarily

The  db.getSiblingDB() method can be used to access another database without switching databases, as in the following example which first switches to the mytest database and then accesses the sampleDBdatabase from the test database:

use mytest
db.getSiblingDB('sampleDB').getCollectionNames();

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.
  • Use <Tab> to autocomplete or to list the completion possibilities. Here in the example below uses <Tab> to complete the method name starting with the letter 'd':
db.myCollection.c<Tab>
> db.myCollection.d
db.myCollection.dataSize(          db.myCollection.drop(
db.myCollection.diskStorageStats(  db.myCollection.dropIndex(
db.myCollection.distinct(          db.myCollection.dropIndexes(

There are many collection methods starting with the letter 'd', the above example shows that the  <Tab>  lists the various methods that start with 'd'.

Customize the mongo shell prompt

You can change the mongo shell prompt by setting the prompt variable. This makes it possible to display additional information in the prompt.

Set prompt to any string or arbitrary JavaScript code that returns a string, consider the following examples:

  • Set the shell prompt to display the hostname and the database issued:

  • > var host = db.serverStatus().host;
    
    or you can use the constant for your host.
    
    test@bidhan-PC> var host = "myhost";
    test@myhost> var prompt = function() { return db+"@"+host+"> "; }
    
    Here is the new mongo shell prompt.
    
    test@myhost>
    
    if you want to return the prompt again
    
    test@myhost> var prompt = function() { return "> "; }
    
    

    Set the shell prompt to display the database statistics:

    
    > var prompt = function() {
    ...                 return "Uptime:"+db.serverStatus().uptime+" Documents:"+db.stats().objects+" > "
    ;
    ...              }
    Here is the new prompt. 
    
    
    Uptime:9862 Documents:0 >
    
    

    Previous: Install MongoDB on Linux
    Next: Data Types

    

    Follow us on Facebook and Twitter for latest update.