Installing MongoDB on Ubuntu with authentication

1. Remove the previous MongoDB

Because Ubuntu has a default mongo install, we have to remove it.

sudo service mongod stop
sudo apt-get purge mongodb-org* mongod -y
sudo apt autoremove
sudo rm -rf /var/log/mongodb
sudo rm -rf /var/lib/mongodb
sudo rm -rf /data/db

2. Reinstall MongoDB

sudo apt-get update
sudo apt-get install gnupg -y
wget -qO - https://www.mongodb.org/static/pgp/server-4.2.asc | sudo apt-key add -
echo "deb [ arch=amd64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.2.list
sudo apt-get update
sudo apt-get install -y mongodb-org

3. Create folders

Because we do not use the root user, we have to give appropriate access

sudo mkdir -p /data/db
sudo chown mongodb /data/db -R
sudo chown mongodb /var/log/mongodb -R
sudo chown mongodb /var/lib/mongodb -R
sudo chmod 777 /tmp/
service mongod restart

4. Add mongo users

Open mongo console

mongo

You have to create an admin user and app user

use admin;
db.createUser(
  {
    user: "root",
    pwd: "veryStrongAndSecurePassword",
    roles: [ { role: "root", db: "admin" } ]
  }
);
db.createUser(
  {
    user: "app",
    pwd: "veryGoodAppPassword",
    roles: [ { role: "readWrite", db: "sessions" } ]
  }
);

Edit mongodb.conf (/etc/mongod.conf):
Uncomment security and add authorization:

security:
	authorization: enabled

Then restart mongo

sudo service mongod restart