Databases Reference
In-Depth Information
MongoDB Shell
MongoDB comes with a JavaScript shell that allows interaction with a MongoDB in-
stance from the command line. The shell is very useful for performing administrative
functions, inspecting a running instance, or just playing around. The mongo shell is a
crucial tool for using MongoDB and is used extensively throughout the rest of the text.
Running the Shell
To start the shell, run the mongo executable:
$ ./mongo
MongoDB shell version: 1.6.0
url: test
connecting to: test
type "help" for help
>
The shell automatically attempts to connect to a MongoDB server on startup, so make
sure you start mongod before starting the shell.
The shell is a full-featured JavaScript interpreter, capable of running arbitrary JavaScript
programs. To illustrate this, let's perform some basic math:
> x = 200
200
> x / 5;
40
We can also leverage all of the standard JavaScript libraries:
> Math.sin(Math.PI / 2);
1
> new Date("2010/1/1");
"Fri Jan 01 2010 00:00:00 GMT-0500 (EST)"
> "Hello, World!".replace("World", "MongoDB");
Hello, MongoDB!
We can even define and call JavaScript functions:
> function factorial (n) {
... if (n <= 1) return 1;
... return n * factorial(n - 1);
... }
> factorial(5);
120
Note that you can create multiline commands. The shell will detect whether the Java-
Script statement is complete when you press Enter and, if it is not, will allow you to
continue writing it on the next line.
 
Search WWH ::




Custom Search