MongoDB: Install on Ubuntu

MongoDB is a document database with the scalability and flexibility in mind. It is a distributed database at its core – so scaling and high availability are built in and easy to use.


Use the following command to import the MongoDB public GPG Key

sudo apt-key adv --keyserver hkp:// --recv 9DA31620334BD75D9DCB49F368818C72E52529D4

Then use the following command:

echo "deb [ arch=amd64 ] bionic/mongodb-org/4.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list

Run following command for getting the updates:

sudo apt-get update

Then install the MongoDB using command:

sudo apt-get install -y mongodb-org

You can restart the service by using:

sudo service mongod restart

To start use:

sudo service mongod start

And to stop:

sudo service mongod stop

To enable the service after reboot:

sudo systemctl enable mongodb

Now open /etc/systemd/system/mongodb.service file in any editor. Like, to edit it with vim use following command.

sudo vim /etc/systemd/system/mongodb.service

Add following lines to the file /etc/systemd/system/mongodb.service:

#Unit contains the dependencies to be satisfied before the service is started.


Description=MongoDB Database


# Service tells systemd, how the service should be started.

# Key `User` specifies that the server will run under the mongodb user and

# `ExecStart` defines the startup command for MongoDB server.




ExecStart=/usr/bin/mongod --quiet --config /etc/mongod.conf

# Install tells systemd when the service should be automatically started.

# `` means the server will be automatically started during boot.


Enable authentication

Use following commands to access mongo db:


Switch to ‘admin’ database:

use admin

Use following command to create your user: (set your password in place of ’test pass’)

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

Update file /etc/systemd/system/mongodb.service with following line:

ExecStart=/usr/bin/mongod --quiet --auth --config /etc/mongod.conf

Update /etc/mongodb.conf with following line

    authorization: enabled

Restart mongoldb service, and you are done.

If you want to enable remote access– then open file /etc/mongod.conf and make changes in following lines:

  port: 27017
  bindIp: #This will make the server available from any ip. To restrict access from specific IP, set that IP here

Leave a Comment

The reCAPTCHA verification period has expired. Please reload the page.