Thursday, 15 December 2016

MongoDB Shell

The MongoDB shell (mongo) is a fully-functioning JavaScript interpreter that is included with all MongoDB distributions.

Running the shell
To start the MongoDB shell we run the mongo executable from the command line:
mongo

We can run mongo with various options. To see what these are, first run it with the help option:
C:\Users>mongo --help
MongoDB shell version v3.4.0
usage: mongo [options] [db address] [file names (ending in .js)]
db address can be:
  foo                   foo database on local machine
  192.168.0.5/foo       foo database on 192.168.0.5 machine
  192.168.0.5:9999/foo  foo database on 192.168.0.5 machine on port 9999
Options:
  --shell                             run the shell after executing files
  --nodb                              don't connect to mongod on startup - no
                                      'db address' arg expected
  --norc                              will not run the ".mongorc.js" file on
                                      start up
  --quiet                             be less chatty
  --port arg                          port to connect to
  --host arg                          server to connect to
  --eval arg                          evaluate javascript
  -h [ --help ]                       show this usage information
  --version                           show version information
  --verbose                           increase verbosity
  --ipv6                              enable IPv6 support (disabled by default)
  --disableJavaScriptJIT              disable the Javascript Just In Time
                                      compiler
  --disableJavaScriptProtection       allow automatic JavaScript function
                                      marshalling
  --ssl                               use SSL for all connections
  --sslCAFile arg                     Certificate Authority file for SSL
  --sslPEMKeyFile arg                 PEM certificate/key file for SSL
  --sslPEMKeyPassword arg             password for key in PEM file for SSL
  --sslCRLFile arg                    Certificate Revocation List file for SSL
  --sslAllowInvalidHostnames          allow connections to servers with
                                      non-matching hostnames
  --sslAllowInvalidCertificates       allow connections to servers with invalid
                                      certificates
  --sslFIPSMode                       activate FIPS 140-2 mode at startup
  --networkMessageCompressors arg     Comma-separated list of compressors to
                                      use for network messages
  --jsHeapLimitMB arg                 set the js scope's heap size limit

Authentication Options:
  -u [ --username ] arg               username for authentication
  -p [ --password ] arg               password for authentication
  --authenticationDatabase arg        user source (defaults to dbname)
  --authenticationMechanism arg       authentication mechanism
  --gssapiServiceName arg (=mongodb)  Service name to use when authenticating
                                      using GSSAPI/Kerberos
  --gssapiHostName arg                Remote host name to use for purpose of
                                      GSSAPI/Kerberos authentication

file names: a list of files to run. files have to end in .js and will exit after unless --shell is specified

By default, mongo will try to connect to the test Database on localhost port 27107 or 127.0.0.1:27017/test
We can override these individually with the --host and --port options shown above, but these cannot be applied together and there is no Database option. Alternatively we can supply a [db address] string:
mongo 192.169.0.5:27108/admin

When we start the shell, it will give us some version and connection info and maybe some warnings. We can disable this with the --quiet option

We can also start the shell without any Database connection using the --nodb option:
mongo --nodb
We can't do much with MongoDB in this mode, but we could run JavaScripts, eg:
C:\Users>mongo --nodb --quiet
> var result = "";
> var i = 0;
> do {i += 1;result += i + " ";} while (i < 5)
1 2 3 4 5
> print ("result: " + result)
result: 1 2 3 4 5


Here we start it with the defaults, as our mongod process is using them also:
As well as the --help option, there is an internal help command as shown above, that gives some info about specific MongoDB functions or helpers. This shows further help helpers, for instance Database-level help is provided by db.help() and Collection-level help by db.collection.help(). There are also some show helpers to help us navigate through our MongoDB.

Here we check the Databases in our MongoDB (show dbs), switch from test Database to admin Database (use admin), show the available Collections in the admin Database (show collections)and query the system.version Collection to show us our current version of MongoDB (db.system.find()).

Note that to run a function, such as db.collection.find , we need to supply parentheses to it:
db.system.version.find()

If we don't supply the parentheses the shell returns the implementation of the function itself:
This gives us some nice information about the inputs and outputs of the function.

Some functions will also have there own help helper, for instance
db.collection.find().help()
You will come to use a lot of these variations of find as you spend more time with the MongoDB shell.

Configuring the shell
We can format the shell prompt from the default ">" to something more informative, for instance to show the current Database and time:
prompt = function() { return db+"@" + new Date().toLocaleTimeString()+"> " ; };

We could run this directly in the shell to configure that particular session. However, there is a file called .mongorc.js in the users home directory (Unix: ~, Windows: %HOMEPATH%) that is sourced when mongo is started. This file is the place to store such customizations in order to make them permanent.

Here is an example that sets the default editor, the prompt and disables some functions that could damage our Database:
C:\Users>cat %HOMEPATH%\.mongorc.js
EDITOR = "notepad.exe";
prompt = function() { return db+"@" + new Date().toLocaleTimeString()+"> "; };

// Disable dangerous actions (not recommended)
var disabled = function() {
    print("That command is disabled");
    };
db.dropDatabase = DB.prototype.dropDatabase = disabled;
DBCollection.prototype.drop = disabled;
DBCollection.prototype.dropIndex = disabled;



Now if we start our shell and attempt to drop the admin Database, we should get this:
C:\Users>mongo --quiet
test@18:55:15> show dbs
admin   0.000GB
local   0.000GB
test    0.000GB
test@18:55:19> use admin
switched to db admin
admin@18:55:27> db.dropDatabase()
That command is disabled
admin@18:55:30> show dbs
admin   0.000GB
local   0.000GB
test    0.000GB


I don't recommend messing with functions in this way, and the behavior of this script seems to change between different versions and systems. For instance, on some versions the shell would not start --nodb as the db in db.dropDatabase is not defined. On others it was ok.

Starting mongo with the --norc option will disable mongorc.js for that session.


The official MongoDB shell documentation can be found here





1 comment: