With the installation of MongoDB, you have installed mongod which is mongo daemon responsible for running MongoDB as a service in the host environment. To connect and interact with MongoDB it also installs one shell called Mongo. To run mongo shell, you need to add its path in PATH environment variable. Once you have all environment variables set to run the shell from the command prompt, open Terminal from your operating system and run command mongo on terminal prompt.
If the mongo server is up and running with default settings, it will connect to it and give you Mongo shell prompt. If you need to connect with remote server or with local server where MongoDB is running on a different port, then run the following command
mongo --host <host IP address/domainName> --port <port number>
Where host IP address could be localhost or loopback address or any accessible network IP address. There might be situations when you find that your MongoDB service is not running. To start MongoDB service, there are multiple ways depending upon your operating system. Let’s see a few examples:
#for windows: #Start MongoDB service net start MongoDB #Verify the Service net start | findstr Mongo #for Linux #Start MongoDB service service mongod start #Verify the Service service mongod status
There are more options to connect to MongoDB via shell. Let’s assume that we are having a MongoDB server running on 10.10.25.123 at port 8888 and has a database codingfreaks, and we need to connect to it. For this run either of the following command:
mongo codingfreaks --host 10.10.25.123 --port 8888
Now you have verified that the server is up and running and you have connected to it via the mongo shell. MongoDB comes with a local help which enables you to search the syntax for the command you require to execute. To get help for getting into mongo shell, run
This command will show you all options and their argument which lets you access MongoDB in different ways. E.g. how to connect with a specific user of MongoDB, how to increase verbosity and much more.
Mongo shell has one more interesting feature which is common for Linux users but not common for Windows users i.e. it lets you use Tab key to complete the command phrase to some extent. In next article, we will see some keyboard shortcuts to fasten up the interaction with Mongo Shell.