Home

Installing MongoDB on Ubuntu 20.04

What is MongoDB?

MongoDB is the most popular document-oriented NoSQL database around. Like other NoSQL databases it's schema-flexible — documents are stored as BSON (a binary JSON variant), so you don't have to lock down a rigid schema upfront. It also has solid stories for high availability and horizontal scaling. This post walks through standing up a single-node (standalone) MongoDB on Ubuntu 20.04.

MongoDB has consistently topped Stack Overflow's "most wanted database" lists for years.

What you'll need:

If you want to reach MongoDB from outside the host, make sure port 27017 (the default) is open.

Installing MongoDB

Import MongoDB's GPG key:

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

You should see OK.

If apt-key add errors out, install gnupg first:

js
sudo apt-get install gnupg

On newer Ubuntu releases, apt-key is deprecated — prefer dropping the key into /etc/apt/keyrings/ and referencing it with signed-by= in the sources file. The 6.0 install instructions in MongoDB's docs follow this pattern.

Add the apt source list:

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

Refresh apt:

bash
sudo apt-get update

Install the latest 6.0 release:

bash
sudo apt-get install -y mongodb-org

If you need a specific patch version (e.g. 6.0.3):

bash
sudo apt-get install -y mongodb-org=6.0.3 mongodb-org-database=6.0.3 mongodb-org-server=6.0.3 mongodb-org-mongos=6.0.3 mongodb-org-tools=6.0.3

Optional — pin the version so apt upgrade doesn't bump it:

bash
echo "mongodb-org hold" | sudo dpkg --set-selectionsecho "mongodb-org-database hold" | sudo dpkg --set-selectionsecho "mongodb-org-server hold" | sudo dpkg --set-selectionsecho "mongodb-mongosh hold" | sudo dpkg --set-selectionsecho "mongodb-org-mongos hold" | sudo dpkg --set-selectionsecho "mongodb-org-tools hold" | sudo dpkg --set-selections

Default paths: logs go to /var/log/mongodb, data lives under /var/lib/mongodb. The install also creates a mongodb user and assigns it ownership of those directories.

Start the service:

bash
sudo systemctl start mongod

Check it's healthy:

bash
sudo systemctl status mongod

Make it start on boot:

bash
sudo systemctl enable mongod

Connecting

mongosh (the MongoDB shell) is bundled with the install. Drop into it:

bash
mongosh

Localhost exception: until you create at least one user, MongoDB lets local connections in without authentication. Always create a real user and lock down access before exposing the port.

A couple of commands to get a feel for things:

Insert into a (new) database:

bash
db.linuxpedi.insert({"name": "MertYavuz"})

Show databases:

bash
show dbs

For a deeper dive, MongoDB's free training is genuinely good — see learn.mongodb.com.