MongoDB is a NoSQL, open-source, document-oriented database used for managing web applications. It dynamically stores the data in JSON formatted documents that do not require predefined schemas like the conventional table-based databases.

In this article, we will look at how to install and configure MongoDB on a Ubuntu 20.04 LTS system.

Prerequisites

Before we begin, log in as a sudo enabled user and update and upgrade the packages on your server by issuing the command shown below.

sudo apt update && sudo apt upgrade

Installing MongoDB on Ubuntu 20.04

There are two ways to install MongoDB on your Ubuntu machine. First, from the default Ubuntu repository, which contains the older version, MongoDB 3.6. And second, by adding the dedicated package repository of MongoDB (contains the latest version MongoDB 4.4) into the apt resources of your system.

MongoDB Inc does not support the mongoDB package in the Ubuntu repository. It is also different from the mongodb-org packages.  So, it is recommended to install MongoDB by adding the dedicated package repository of MongoDB to the apt resources.

Installing MongoDB by adding the official repository

First, import the public GPG key of the latest version of MongoDB. To find the appropriate key, visit this URL and look for the server-x.x.asc file corresponding with the current latest version of MongoDB. 

At the time of writing this article, the newest version of MongoDB is 4.4. So we’ll select that and use the command below to import the GPG key for the version 4.4.

wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

On successful execution, the command will give the output as OK.

Since we need the mongodb-org package to install the latest version of MongoDB, add the official MongoDB repository to your system using the command below.

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

Now update the local package database and install mongodb-org package by running the commands below one-by-one.

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

Once MongoDB is installed, start and enable the mongod service on your system using the commands below.

systemctl start mongod
systemctl enable mongod

To verify MongoDB is running on your system, use the command below. It should output the status as active.

systemctl status mongod
mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor p>
Active: active (running) since Tue 2020-08-18 09:01:48 UTC; 45s ago
Docs: https://docs.mongodb.org/manual
Main PID: 13739 (mongod)
Memory: 79.1M
CGroup: /system.slice/mongod.service
└─13739 /usr/bin/mongod --config /etc/mongod.conf

You can also check the connection status, current version, server address, and port, with the following command:

mongo --eval 'db.runCommand({ connectionStatus: 1 })'

If the connection status shows ok : 1, then it means the server is working appropriately, as shown in the output below.

MongoDB shell version v4.2.8
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("6ba987a2-30fc-4d84-8665-57f28b1bbfd9") }
MongoDB server version: 4.2.8
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1
}

The default port number of MongoDB is 27017, running on 127.0.0.1, which is the loopback address for the localhost.


Configuring MongoDB 

Configuring MongoDB is optional as the default configuration settings are sufficient to meet your needs, but for production environments, it is recommended to enable authorization.

The configuration file of MongoDB is present in the /etc directory. To edit it, type the following command in your terminal.

nano /etc/mongod.conf

Now go to the bottom of the file and uncomment the security option by removing the # symbol and type authorization: enabled as shown below.

security:
authorization: enabled

Restart MongoDB with the following command to apply the changes.

systemctl restart mongod

To know more about configuring MongoDB, visit this documentation page.


Creating and Verifying MongoDB Administrator

We will now create an admin user who can access the MongoDB database.

Creating MongoDB Admin

To access the MongoDB shell, use the mongo command.

mongo

Then, access the MongoDB admin database with the following command.

use admin

Now use the following command to create a new user and password with the role userAdminAnyDatabase.

db.createUser(
{
user: "UserName",
pwd: "PasswordOfYourChoice",
roles: [{ role:"userAdminAnyDatabase",db:"admin"}]
}
)

Note: Replace the value of user (UserName) and password (passwordOfYourChoice) to your choice.

After successfully creating a MongoDB user, type quit() to exit the shell.

quit()

Verify Admin authentication

To verify the authentication, access admin account with the command below.

mongo -u UserName -p --authenticationDatabase admin

The shell will prompt you to enter the password. Type the password you chose for the user in the instructions above, and hit enter.

Then, access the admin database with following command.

use admin

Now, issue the show users command in the shell to fetch details of all authenticated users.

show users
{
"_id" : "admin.UserName",
"userId" : UUID("d5e186d7-0520-41a5-8f42-da3b7b8e8868"),
"user" : "UserName",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

You should see the UserName you created in the steps above in the output.


Managing MongoDB

To manage mongod processes, we use the built-in init system of Ubuntu. Ubuntu versions from 16.04 Xenial use systemd to manage MongoDB, which uses the systemctl command.

Stop mongod service

To stop the mongod process, use the following command.

sudo systemctl stop mongod

Start mongod service

To start the mongod process, use the following command.

sudo systemctl start mongod

Restart Mongod

To restart the mongod process, use the following command.

sudo systemctl restart mongod

We have successfully installed the latest version of MongoDB on your Ubuntu 20.04 machine. To know more about MongoDB, Refer to this documentation.