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:
- 1 Ubuntu 20.04 server
- Minimum 4 GB RAM, 2 CPU cores
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:
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -You should see OK.
If
apt-key adderrors out, install gnupg first:jssudo apt-get install gnupgOn newer Ubuntu releases,
apt-keyis deprecated — prefer dropping the key into/etc/apt/keyrings/and referencing it withsigned-by=in the sources file. The 6.0 install instructions in MongoDB's docs follow this pattern.
Add the apt source list:
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.listRefresh apt:
sudo apt-get updateInstall the latest 6.0 release:
sudo apt-get install -y mongodb-orgIf you need a specific patch version (e.g. 6.0.3):
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.3Optional — pin the version so apt upgrade doesn't bump it:
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-selectionsDefault paths: logs go to
/var/log/mongodb, data lives under/var/lib/mongodb. The install also creates amongodbuser and assigns it ownership of those directories.
Start the service:
sudo systemctl start mongodCheck it's healthy:
sudo systemctl status mongodMake it start on boot:
sudo systemctl enable mongodConnecting
mongosh (the MongoDB shell) is bundled with the install. Drop into it:
mongoshLocalhost 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:
db.linuxpedi.insert({"name": "MertYavuz"})Show databases:
show dbsFor a deeper dive, MongoDB's free training is genuinely good — see learn.mongodb.com.