In this tutorial, you will learn how to install MongoDB on Ubuntu 20.04 and Ubuntu 22.04.
MongoDB has its own repository that allows you to install MongoDB on two different Ubuntu versions, on Ubuntu 20.04 and Ubuntu 22.04.
By adding this repository on your system, you are able to install MongoDB directly from the terminal.
In this tutorial, we'll be installing MongoDB on Ubuntu by using the official repository.
Install MongoDB on Ubuntu
Step 1 - Import MongoDB GPG Key
Before installing MongoDB on your machine, you need to import MongoDB's GPG key.
To import MongoDB's GPG Key, you can do so by running the command below.
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
--dearmor

Step 2 - Setup MongoDB Repository
Depending the version of Ubuntu, proceed to setup MongoDB repository on your machine.
Even though MongoDB supports both versions, make sure to setup the right repository for your version.
So if you are running Ubuntu 22.04, then you will need to use only the repository for Ubuntu 22.04, which is the "Jammy" version.
To setup MongoDB repository for Ubuntu 22.04, run
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

To setup MongoDB repository for Ubuntu 20.04, run
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

Step 3 - Update your system
Next, update your system, in order to be able to use MongoDB repository.
sudo apt update

Step 4 - Install MongoDB
Finally, install MongoDB, by running the command below.
sudo apt install mongodb-org -y

Uninstall MongoDB on Ubuntu
Uninstall MongoDB on any Ubuntu version, by running the command below.
sudo apt purge mongodb-org -y

Conclusion
In this tutorial, you learned how to install MongoDB official package mongodb-org
by using the official repository offered by MongoDB.