Introduction to mongo Shell

Last update on April 14 2018 06:14:57 (UTC/GMT +8 hours)

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':