Share AT

Reading Time: 5 mins.

Overview:

MongoDB, an open-source document database software and falls under the category of NoSQL database as it uses JSON-like documents with dynamic schemas instead of the traditional table-based relational database structure like MySQL and PostgreSQL. Used by several modern applications, MongoDB supports cross-platform and helps to store high-volume of data. With MongoDB, you need not set up a new database with an updated schema every time you alter the schema. Due to its high-performance, scalability and easy integration with numerous programming languages, MongoDB is the best go-to-option for websites/applications that require powerful, mission-critical and high-availability databases. For more details, visit, https://www.mongodb.com/

Prerequisites:

  1. To be logged in as a non-root user with sudo privileges.
  2. Installation of all the required Postgre packages.

Table of contents:

  1. Adding MongoDB repository
  2. Installing MongoDB
  3. Verifying MongoDB Installation
  4. Enabling Authentication for MongoDB
  5. Creating a MongoDB user with admin privileges
  6. Managing MongoDB commands

Step 1: Adding MongoDB repository

To update your server’s local package, use the below command.

sudo apt update

Post updating the package, install the required dependencies to add a new repository over HTTPS:

sudo apt install dirmngr gnupg apt-transport-https ca-certificates software-properties-common

Next, import the repository’s GPG key and add the MongoDB repository as shown below.

sudo wget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -
sudo add-apt-repository 'deb [arch=amd64] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 multiverse'

Here, we’ve added the necessary dependencies and MongoDB repositories required for the MongoDB installation.

Step 2: Installing MongoDB

To make it easy for the APT to find the whereabouts of mongodb-org package, update your server’s local package index.

sudo apt update

As soon as the repository was enabled, install the mongodb-org meta-package by typing the following command.

sudo apt install mongodb-org

To start the MongoDB daemon on system startups, type:

sudo systemctl enable --now mongod

Step 3: Verifying MongoDB Installation

Now that you’ve installed MongoDB, it will start automatically. In case, if it hasn’t started yet, enter the below command.

sudo systemctl start mongod.service

To verify the status of MongoDB, type:

sudo systemctl status mongod

Output

● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: active (running) since Thu 2020-10-01 11:33:23 IST; 3s ago
Docs: https://docs.mongodb.org/manual
Main PID: 15694 (mongod)
Memory: 60.4M
CGroup: /system.slice/mongod.service
└─15694 /usr/bin/mongod --config /etc/mongod.conf

Oct 01 11:33:23 user systemd[1]: Started MongoDB Database Server.

To verify whether the installation has completed successfully, connect to the MongoDB database server using the mongo tool for printing the connection status and version number:

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

Output

MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("be8f76c7-70d8-4b8c-ad9d-c4709c6caf52") }
MongoDB server version: 4.4.1
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1
}

Step 4: Enabling authentication for MongoDB (recommended)

By default, you’ve everything configured for the MongoDB settings. Just in case, for the fine-working in the production environment, it’s always recommended to uncomment the security section and enable the authorization, as shown below. We have to enable the security directive in the mongodb conf file.

Open the configuration file using the below command:

sudo nano /etc/mongod.conf
security:
authorization: enabled

Enabling the authorization option is crucial as it will regulate and control the users’ access to database resources and operations via Role-Based Access Control (RBAC). If disabled, each and every user will have access to all the databases and can perform any action as they preferred.

Now that we have made some configurations, it is necessary to restart the MongoDB service to update the changes.

sudo systemctl restart mongod

In order to know more about MongoDB 4.4 in-detail, visit the Configuration File Options documentation page.

Note: If you are using a development environment, you need not enable the authentication. Now that we have enabled the authentication (as shown above), we need to create a privileged user to specifically access the MongoDB databases, let’s see how to do it in the next section.

Step 5: Creating a MongoDB user with admin privileges

For the purpose of role-based access control, if you’ve enabled MongoDB authentication, it’s necessary for you to create an administrative user so as to access and manage the MongoDB instance.

Now, to access the mongo shell, type:

sudo mongo

Output

MongoDB shell version v4.4.1
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4d002568-bd95-41e9-82a4-e6fb60a73e8e") }
MongoDB server version: 4.4.1

Here, we need to switch as an admin user as we need to create a user with admin privileges.

To switch as an admin user, type:

> use admin

Output

switched to db admin

Now, let us create a MongoDB user by entering the following code.

> db.createUser(
... {
... user: "demoAdmin",
... pwd: "demo123",
... roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
... }
... )

Output

Successfully added user: {
"user" : "demoAdmin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}

To verify the created privileged user, first, login to the mongodb shell using the below command.

$ sudo mongo -u demoAdmin -p --authenticationDatabase admin

Note: You can’t access the mongodb shell directly since we’ve enabled the authentication option to control the user access.

> use admin

Next run show users which then allows you to view the information regarding the newly created user.

> show users

Output

{
"_id" : "admin.demoAdmin",
"userId" : UUID("99003037-a63c-4515-90b9-c3f391ae4d1c"),
"user" : "demoAdmin",
"db" : "admin",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
],
"mechanisms" : [
"SCRAM-SHA-1",
"SCRAM-SHA-256"
]
}

Note: Make sure that you have set a stronger password to prevent security breaches.

Step 6: Managing MongoDB commands

The following are some of the basic MongoDB commands.

To check the status of the MongoDB service, type:

sudo systemctl status mongod

To stop the service anytime, type:

sudo systemctl stop mongod

To start the service when it’s stopped, type:

sudo systemctl start mongod

To restart the server when it’s already running, type:

sudo systemctl restart mongod

To disable the automatic startup on system boot-ups, type:

sudo systemctl disable mongod

To re-enable it to start up at boot, run the enable command again.

sudo systemctl enable mongod

If you want to more details with regard to MongoDB commands, check out the link, https://docs.mongodb.com/manual/reference/mongo-shell/

Conclusion:

This article walked you through the how-to of installing and configuring MongoDB on Ubuntu 20.04. We did this by first adding the official MongoDB repository to the APT instance, and installing the latest version of MongoDB. Followed by that, we’ve enabled the system level startup commands and tested the active status of mongodb instances. In order to use MongoDB in remote connections, we’ve enabled the authentication option and created a privileged user so as to access the mongodb shell without compromising the security of the server.