Mongo Shell

Mongo shell is an interactive JavaScript interface to MongoDB used to perform administrative operations and also query and update data.

Prior to connecting to MongoDB, ensure that MongoDB is running. If it is not, start MongoDB.

To start MongoDB, run the following command in a terminal.

Once you are sure that MongoDB is running, Open a Terminal and run the following command  to start mongo shell.

  $ mongo
If the server is not running, you may get connect failed message as below :
When no parameters are provided with mongo command, the default functionality is that, the mongo shell tries to make a connection to the MongoDB server running at localhost on port 27017.

But if you like to connect to MongoDB server that is running on a different machine connected to your network, you may make use of the options of mongo shell as shown below

An example is provided below

Now we shall run a simple query db to know the database the shell is pointing to.

test is a default database.

 

Start Mongo Shell for a specified MongoDB instance among multiple instances

If you come across the scenario that there are multiple MongoDB instances running in a same machine, but on the different ports of-course, then to connect to a particular MongoDB instance differentiated by the port it is running on, run the following command :

Following is an example demonstrating to open a Mongo Shell connected to a MongoDB instance running at 27018.

 

Mongo Shell Commands

Following are a useful list of Mongo Shell Commands :

  • help – show help
  • help admin – administrative help
  • help connect – connecting to a db help
  • help keys – key shortcuts
  • help misc – misc things to know
  • help mr – mapreduce
  • show dbs – show database names
  • show collections – show collections in current database
  • show users – show users in current database
  • show profile – show most recent system.profile entries with time >= 1ms
  • show logs – show the accessible logger names
  • show log [name] – prints out the last segment of log in memory, ‘global’ is default
  • use <db_name> – set current database
  • it – result of the last line evaluated; use to further iterate
  • exit – quit the mongo shell

 

Conclusion :

In this MongoDB Tutorial, we have learnt about Mongo Shell, its usage and its connectivity to MongoDB Server when the server is running in another machine in network.