Read in 4 minutes

last updated 

How to Install MongoDB on Ubuntu 18.04

MongoDB is a free and open-source document database. It belongs to a family of databases called NoSQL which are different from the traditional table-based SQL databases like MySQL and PostgreSQL.

In MongoDB, data is stored in flexible, JSON-like documents where fields can vary from document to document. It does not require a predefined schema and data structure can be changed over time.

In this tutorial, we will cover the process of installing and configuring the latest version of MongoDB Community Edition on a Ubuntu 18.04 machine from the official MongoDB repositories.

Prerequisites

Before continuing with this tutorial, make sure you are logged in as a user with sudo privileges.

Installing MongoDB

At the time of writing this article, the latest version of MongoDB is version 4.0.

Before continuing with the installation process, head over to the Install on Ubuntu section of MongoDB’s documentation and check if there is a new release available .

The following steps describe how to install MongoDB on your Ubuntu server:

  1. Enabling MongoDB repository

    First add the MongoDB GPG key to your system using the following command:

    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4

    Once the key is imported, add the MongoDB repository with:

    sudo add-apt-repository 'deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse'

    If you get an error message saying add-apt-repository command not found then you will need to install the software-properties-common package.

    To install an older version of MongoDB, just replace 4.0 with your preferred version.

  2. Installing MongoDB

    To be able to install packages from the MongoDB repository you’ll need to update the packages list first:

    sudo apt update

    Now that the repository is enabled and packages list is updated you can install the mongodb-org meta-package using the apt package manager:

    sudo apt install mongodb-org

    The following packages will be installed on your system as a part of the mongodb-org package:

    • mongodb-org-server - The mongod daemon and corresponding init scripts and configurations.
    • mongodb-org-mongos - The the mongos daemon.
    • mongodb-org-shell - The mongo shell is an interactive JavaScript interface to MongoDB. It is used to perform administrative tasks through the command line.
    • mongodb-org-tools - Contains several MongoDB tools for to importing and exporting data, statistics, as well as other utilities.
  3. Starting MongoDB

    Once the installation is completed, start the MongoDB daemon and enable it to start on boot by typing:

    sudo systemctl start mongod
    sudo systemctl enable mongod
  4. Verifying MongoDB Installation

    To verify whether the installation has completed successfully we will connect to the MongoDB database server using the mongo tool and print the connection status:

    mongo --eval 'db.runCommand({ connectionStatus: 1 })'

    The output will look like this:

    MongoDB shell version v4.0.2
    connecting to: mongodb://127.0.0.1:27017
    MongoDB server version: 4.0.2
    {
      "authInfo" : {
        "authenticatedUsers" : [ ],
        "authenticatedUserRoles" : [ ]
      },
      "ok" : 1
    }

    A value of 1 for the ok field indicates success.

Configuring MongoDB

MongoDB uses a YAML formatted configuration file, /etc/mongod.conf . You can configure your MongoDB instance by editing this file.

The default configuration settings are sufficient for most users. However for production environments it is recommend to uncomment the security section and enable authorization as shown bellow:

/etc/mongod.conf
security:
  authorization: enabled

The authorization option enables Role-Based Access Control (RBAC) that regulates users access to database resources and operations. If this option is disabled each user will have access to all databases and perform any action.

After making changes to the MongoDB configuration file, restart the mongod service with:

sudo systemctl restart mongod

To find more information about the configuration options available in MongoDB 4.0 visit the Configuration File Options documentation page.

Creating Administrative MongoDB User

If you enabled the MongoDB authentication, create an administrative MongoDB user that will be used to access and manage the MongoDB instance.

First access the mongo shell with:

mongo

Once you are inside the MongoDB shell type the following command to connect to the admin database:

use admin
switched to db admin

Issue the following command to create a new user named mongoAdmin with the userAdminAnyDatabase role:

db.createUser(
  {
    user: "mongoAdmin", 
    pwd: "changeMe", 
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
Successfully added user: {
	"user" : "mongoAdmin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	]
}
You can name the administrative MongoDB user as you want.

Exit the mongo shell with:

quit()

To test the changes, access the mongo shell using the adminstrative user you have previously created:

mongo -u mongoAdmin -p --authenticationDatabase admin
use admin
switched to db admin

Now, print the users with:

show users
{
	"_id" : "admin.mongoAdmin",
	"user" : "mongoAdmin",
	"db" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

You can also try to access the mongo shell without any arguments ( just type mongo) and see if you can list the users using the same commands as above.

Conclusion

You have learned how to install and configure MongoDB 4.0 on your Ubuntu 18.04 server.

You can consult The MongoDB 4.0 Manual for more information on this topic.