Installing MongoDB on Ubuntu 22.04 – A Complete Guide

Installing and configuring MongoDB on your Ubuntu 22.04 is a simple task that should not take much of your time. However, some steps may be intricate for newbies, so we compiled this guide. This tutorial will help you learn how to install and configure MongoDB 5.0.9 on your Ubuntu 22.04.

Prerequisites:

  • Before we embark on our endeavor, confirm that you have the following:
  • The tutorial requires Ubuntu 22.04 server
  • Root privileges
  • A fully-configured firewall

What is MongoDB?

MongoDB is a document-centric NoSQL database program distinguished for its exceptional performance. It is a free, open-source solution published under the GNU Affero General Public License (GPL) and is commonly used in modern-day web applications. The application manifests the top qualities of a distributed database at its core. Therefore horizontal scaling, geographical distribution, and high availability are built-in.

MongoDB is written in C++ language and stores data in a format called Binary JSON (BSON). The flexible JSON-like documents mean the data fields can vary from one document to the other, and the structure can be modified over time. In addition, the database only offers unique packages for 64bit Long-term Support (LTS) Ubuntu releases. For example, the latest Ubuntu 22.04 (Jammy Jellyfish), Ubuntu 20.04 (Focal Fossa), Ubuntu 18.04 (Bionic Beaver), Ubuntu 16.04 (Xenial XERUS), and Ubuntu 14.04 (Trusty Tahr).

 

MongoDB Pros and Cons

ProsCons
It stores almost all data in the RAM, which allows for faster performanceJoining documents is tedious because MongoDB doesn’t support joins as a relational database
It is simple and easy to understandIt performs at low speeds when indexing is done incorrectly
The setup process is straightforward and quickIt limits document size to 16 MB per document
It operates on a dynamic schematic architecture that is compatible with non-structured data and storagePerformance nesting for documents is limited to 100 levels
It uses sharding with large datasetsIt demands a large amount of storage because of the lack of joins functionality, which results in data duplication
It uses horizontal scalability
It offers an advanced ad-hoc queries feature
It offers accurate documentation and doesn’t tether with the data when it processes it
It offers expert customer support

 

Installing MongoDB: Overview

Part One: Installing MongoDBStep 1: Install Dependencies

Step 2: Create a MongoDB repository

Step 3: Import the GPG public key

Step 4: Update the repository

Step 5: Install MongoDB

Part Two: Configuring MongoDB username/passwordStep 1: Open the mongo shell

Step 2: Change the database administrator

Step 3: Create a root user

Step 4: Enable MongoDB authentication

Step 5: Restart MongoDB

Part Three – Managing The Newly Installed MongoDB ServiceStatus Check

To Stop MongoDB

To Start MongoDB

To Restart MongoDB

Part Four: Adjusting the Firewall SettingsAllow UFW to port 27017


Part One: Installing MongoDB

Step 1: Install dependencies

First, install mongodb dependencies by using this command:

$ sudo apt update

$ sudo apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common

Step 2: Create a MongoDB repository

Once you import the key, the next step is creating a list file for MongoDB in ‘/etc/apt/sources.list.d/’. Run the command below:

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

By now MongoDB is yet to release the packages for Ubuntu 20.04 (Focal fossa), but the focal should be working fine on your Ubuntu 22.04 LTS. In some case you might visit this URL before executing the above command.  In case a directory “focal” appears on the web page, you should replace the term ‘jemmy’ in the command above with the term ‘focal’.

Step 3: Import the GPG Public key

The Ubuntu advanced package tool (package manager apt) requires the GNU Privacy Guard (GPG) of the software distributor to authenticate and ensure consistency of the package. For this reason, the first step when installing MongoDB is importing the GPG key to your Ubuntu server. Run the following command to import the key:

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

Step 4: Update the repository

By now, you have the repository for your MongoDB 5.0. Next, you should issue an update command to allow Ubuntu to read packages from the newly created repository. To update the repository, run the following apt command:

$ sudo apt-get update

That’s it, the stage is set for MongoDB installation.

Step 5: Install MongoDB

Now, type the following command to initiate the installation of MongoDB from the repository:

sudo apt-get install -y mongodb-org

In a while, mongodb will be installed completely on your system.

If you receive an error of missing packages then, you will run these commands to resolve this error:

$ echo "deb http://security.ubuntu.com/ubuntu impish-security main" | sudo tee /etc/apt/sources.list.d/impish-security.list

$ sudo apt-get update

$ sudo apt-get install libssl1.1

Now, install mongodb using this command:

$ sudo apt-get install -y mongodb-org

After completing the installation display the installed version:

$ mongo --version

The MongoDB apt installer will automatically create the mongod.service file for the systemd. However, you can craft this manually if this is not created automatically. The system unit file retains the information about sockets, services, devices, and other resources managed by the system. Create the file in /etc/systemd/system/ directory, use the following nano:

# sudo nano /etc/systemd/system/mongodb.service

Then copy and paste the text below:

[Unit]

Description=High-performance, schema-free document-oriented database

After=network.target

Documentation=https://docs.mongodb.org/manual

[Service]

User=mongodb

Group=mongodb

ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

[Install]

WantedBy=multi-user.target

Press Ctrl + O to save the file and Ctrl + X to close it. Next, update the systemd to incorporate the newly created service, then enable and induct the service.

The MongoDB apt installer will automatically starts the mongodb service on your system. Alternatively, you can also enable and restart MongoDB service by using the following commands:

# sudo systemctl daemon-reload

 # sudo systemctl enable mongod

 # sudo systemctl start mongod

Confirm the service is running using the following command:

# systemctl status mongod

 

Part Two: Configuring MongoDB username/password

By now, you have installed all the packages of MongoDB. Then next is configuring the username and password for your database server.

Step 1: Open the mongo shell

Before setting up the username and password, you must open the MongoDB shell for your database server. Type in:

# mongo

If you get the error:

Failed global initialization: badvalue invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are correctly set.

Then use the command below;

export LC_ALL=C

mongo

Step 2: Change the database administrator

Once you are logged in the shell, type the command below to switch to the administrator database:

>use admin

Step 3: Create a root user

Now you can create an admin username, then create its password. Use the following command to achieve this:

db.createUser({user:"admin", pwd:"admin123", roles:[{role:"root", db:"admin"}]})

From the command above, it is clear you have created a user called admin with a password set as admin123. The user has the role/permission as the root user, whereas the database is the admin.

Note
The password value can be substituted for your unique value, e.g., you can set the password as MyPassword.

The command above will give the following output:

Output for creating an admin username and password

Exit the MongoDB shell by typing exit.

Step 4: Enable MongoDB authentication

Locate and open the ‘/lib/systemd/system/mongod.service’ using your nano editor:

# sudo nano /lib/systemd/system/mongod.service

On the ExecStart line, include an optional argument line:

ExecStart=/usr/bin/mongod --quiet --auth --config /etc/mongod.conf

Press Ctrl+O to save and Ctrl+X to exit nano.

Next, update the system to incorporate a new version of the adjusted service file.

systemctl daemon-reload

Step 5: Restart MongoDB

Now restart MongoDB to enable all the changes made to take effect. Use the following command:

# sudo systemctl restart mongod

Then run the command below to connect to the shell:

# mongo -u admin -p --authenticationDatabase admin

You will be requested to enter the password as set above. Once you are logged into the MongoDB shell, verify that you are the authenticated user you created above. Run the following command:

> db.runCommand({connectionStatus : 1})

You will get the following output:

That is it!

Part Three – Managing The Newly Installed MongoDB Service

Once MongoDB has been fully installed, it manifests as a systemd service which means it can be managed using the systemd command. The following are the systemd commands to use to manage MongoDB:

Status Check

To check the status of the MongoDB service, run the command below:

$ sudo systemctl status MongoDB

To Stop MongoDB

MongoDB database server can be stopped anytime by running the following command:

$ sudo systemctl stop MongoDB

To Start MongoDB

On the other hand, the service can be started by running the command below:

$ sudo systemctl start MongoDB

To Restart MongoDB

Additionally, the MongoDB database server can be restarted with a single command:

$ sudo systemctl disable mongodb

And to enable MongoDB, you can run the command below:

$ sudo systemctl enable MongoDB

 

Part Four: Adjusting the Firewall Settings on MongoDB

In some cases, when the firewall is enabled on Ubuntu Server, the access to the MongoDB server may be limited. This setting is ideal and secure if you plan to use the MongoDB server locally with apps operating on the same server.

However, if you intend to connect to the MongoDB database server from the internet, you should enable inbound connections in the Uncomplicated Firewall (UFW). By default, the MongoDB server runs on port 27017, and to permit access to MongoDB via this port; you could run the command sudo ufw allow 27017. However, permitting access to the MongoDB database server via its default port provides unrestricted access to data and the server itself.

For this reason, it’s always wise to allow access only to specific locations. To achieve this, you enable access on the default port but specify the IP address of the other server with explicit rights to connect to the database server. Run the command below:

$ sudo ufw allow from your_other_server_ip/32 to any port 27017

Next, run the command below to check the status of the firewall:

$ sudo ufw allow 27017

$ sudo ufw status

This will give you an output like the one below:

The output clearly shows that port 27017 is allowed anywhere. If you have permitted a specific IP address to access the database server, you should see the allowed IP address listed and not Anywhere in the above output.

Now, even though the default port is open, the database server is currently listening on 127.0.0.1. To permit remote connections, you must include a publicly-routed IP address for your server to Mongo.conf file.

Run the command below to open the Mongo.conf file:

$ sudo nano /etc/mongodb.conf

Locate the bind_ip value and add the desired IP address:

...

logappend=true

bind_ip = 127.0.0.1,your_server_ip

#port = 27017

...

A comma should be placed before adding the IP address you want to allow. Once that is done, Save the changes and exit the editor.

Next, restart MongoDB:

$ sudo systemctl restart mongodb

That’s it! You have successfully modified the firewall settings.

 

Conclusion

You have successfully installed and configured MongoDB on Ubuntu 22.04. Enjoy the high availability, high performance, and the automatic scaling of MongoDB. Start up MongoDB quickly and enjoy the convenience and fun of creating your applications.

How to Install OpenCart on an Ubuntu 18.04 Server or VPS with Apache, MariaDB and PHP 7

In this how-to, you'll learn how to install OpenCart, an open source shopping ca
3 min read
Angela Olaru
Angela Olaru
Senior Writer & Hosting Expert

How to Backup Your MySQL Database on an Ubuntu 18.04 VPS or Dedicated Server

This article shows you how to back up a MySQL database on a Linux Ubuntu 18.04 s
3 min read
Eliran Ouzan
Eliran Ouzan
Web Designer & Hosting Expert

How to Install MongoDB on Your CentOS 7 VPS or Dedicated Server

MongoDB is designed for extensive databases and is mainly used for data analytic
2 min read
Eliran Ouzan
Eliran Ouzan
Web Designer & Hosting Expert

How to Disable MySQL 5 "Strict Mode" on an Ubuntu 18.04 VPS or Dedicated Server

How to Disable MySQL Strict Mode on MySQL 5.6 Running on an Ubuntu 18.04 VPS.
2 min read
Idan Cohen
Idan Cohen
Marketing Expert
HostAdvice.com provides professional web hosting reviews fully independent of any other entity. Our reviews are unbiased, honest, and apply the same evaluation standards to all those reviewed. While monetary compensation is received from a few of the companies listed on this site, compensation of services and products have no influence on the direction or conclusions of our reviews. Nor does the compensation influence our rankings for certain host companies. This compensation covers account purchasing costs, testing costs and royalties paid to reviewers.
Click to go to the top of the page
Go To Top