Installing MongoDB and using the shell

MongoDB can be easily installed on any platform. On Ubuntu 18.04, we need to perform some steps before running the apt-get command:

sudo apt-get update
sudo apt-get install -y mongodb

Once you've installed it, check whether the mongo process is running. If not, you can start the MongoDB daemon using the following command:

systemctl start mongod

If the user is root, you can drop the sudo keyword before each command.

We can also download MongoDB manually from the website and copy it to /usr/local/bin. To do this, we have to create an init script for the server since the server stops when the system is shut down. We can use the nohup tool to run the server in the background. Usually, it is better to install it using apt-get.

To install MongoDB on Mac OS X, you'll need to use the Homebrew software. Follow these steps to do so:

  1. We can easily install it using the following command:
brew tap mongodb/brew
brew install mongodb-community
  1. After that, we need to create the db directory where MongoDB stores its database: 
mkdir -p /data/db
  1. Then, change the permissions of that file using chown:
chown -R `id -un` /data/db
  1. Now, MongoDB is ready. To see its logs interactively, we need to stop MongoDB as a process and run it in a shell. To stop the service, use the following command:
systemctl stop mongod
  1. Now, in a Terminal window, run the following command, which starts MongoDB interactively (not in the background):
mongod

The preceding command results in the following output:

The preceding command shows the status of the database in a few columns. From these logs, we can figure out that the server started on port 27017. It displays the build environment, the storage engine that was used, and so on.

On Windows, we can manually download the installer binary and launch it by adding the installation bin directory to the PATH variable. Then, we can run it using the mongod command. Alongside the MongoDB installation comes a client shell called Mongo. We will look at it in brief in the next section.