How to Install MongoDB in Ubuntu Server

MongoDB is a high performance and feature rich NoSQL database and the most popular NoSQL database on the market. In this tutorial we will learn how to install MongoDB on Ubuntu Server.

MongoDB 3.4 is the latest version which available from the mongo apt repository. Do the following steps to enable apt repository and install mongodb in Ubuntu.

First, import the apt key:

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6

Next, create the apt source list file:

echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

Then, update the apt source list and install the mongodb-org package.

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

The mongodb package includes following packages mongodb-org-server and mongodb-org-shell.

Finally, we can start and enable mongod service:

sudo systemctl start mongod.service
sudo systemctl enable mongod.service

MongoDB for Ubuntu also available from the default Ubuntu software repository, but it is not the most up-to-date version of the MongoDB Server.

View MongoDB Server Status

To check the server version running on your Ubuntu server, Type:

mongod -version

To view the Server status Type:

sudo systemctl status mongod.service
● mongod.service - High-performance, schema-free document-oriented database
   Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2017-10-13 19:21:31 IST; 1h 31min ago
     Docs: https://docs.mongodb.org/manual
 Main PID: 1933 (mongod)
    Tasks: 20
   Memory: 68.2M
      CPU: 32.816s
   CGroup: /system.slice/mongod.service
           └─1933 /usr/bin/mongod --config /etc/mongod.conf

The MongoDB by default running on TCP port 27017, so make sure that MongoDB Server is listening on TCP port 27017.

sudo ss -tlp | grep 27017
LISTEN     0      128    127.0.0.1:27017    *:*    users:(("mongod",pid=1933,fd=7))

Start MongoDB Service on Ubuntu

We can start, stop and restart mongodb service on Ubuntu 16.04 with systemctl command.

sudo systemctl start mongod.service

Set MongoDB to start at system reboot:

sudo systemctl enable mongod.service

In Ubuntu 14.04, you have to use the service command to manage mongodb service:

sudo service mongod start

Using the MongoDB Shell

To connect to the local instance of the MongoDB Server, Type:

mongo

Once you entered the mongo command, you will directed to the MongoDB Shell.

To show databases, Type:

show dbs

To select a Database, Type:

use database_name

To exit from the Ubuntu MongoDB Shell, Type:

exit