Install MongoDB on Ubuntu

This example is for MongoDB 4.4 on Ubuntu 18 Bionic. You can find other sources here if you want a different version of MongoDB or are on a different version of Ubuntu.

This example is for MongoDB 4.4 on Ubuntu 18 Bionic. You can find other sources here if you want a different version of MongoDB or are on a different version of Ubuntu.

Install MongoDB Community Edition on Ubuntu

Import Mongo 4.4 GPG key

curl -fsSL https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -

Create source list for apt

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

Update apt and install Mongodb

sudo apt update2​3sudo apt install mongodb-org

Start MongoDB

sudo systemctl start mongod.service

Auto-start MongoDB on reboot

sudo systemctl enable mongod

Create a root user

mongo

use admin

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

Remote Access

This is optional and only fi you need to access the database from somewhere other than localhost. Modify the "bindIP" to 0.0.0.0 for anywhere or a specific ip or ip range for limited remote access in /etc/mongod.conf.

Limited

net:
  port: 27017
  bindIp: 22.35.223.23
/etc/mongod.conf

Anywhere

net:
  port: 27017
  bindIp: 0.0.0.0
/etc/mongod.conf

Create an application user

Create a user with limited roles on a particular database.

mongo

use admin

db.createUser(
      {
          user: "appuser",
          pwd: "USER_PASSWORD_HERE",
          roles: [ { "readWrite", db:"DB_USER_CAN_READ_WRITE_HERE" } ]
      }
)

Enbale Authentication

In /etc/mongod.conf uncomment the following two lines.

security:
  authorization: enabled
/etc/mongod.conf

Common Admin Commands

Get Status:

sudo systemctl status mongod

Stop MongoDB:

sudo systemctl stop mongod

Start MongoDB:

sudo systemctl start mongod

Restart MongoDB:

sudo systemctl restart mongod

Disable auto-start:

sudo systemctl disable mongod

Enable auto-start:

sudo systemctl enable mongod

Subscribe to dadonk

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe