How to install MongoDB on Ubuntu 22.04 – vetechno

MongoDB is an open-source, cross-platform, overall, object-oriented, straightforward, and flexible NoSQL database. It is a document database management system designed for high performance data persistence, high availability, as well as automatic scaling, based on the NoSQL. In MongoDB, a record is a document, which is a data structure that comprises of field and value pairs (MongoDB documents are comparable to JSON objects). MongoDB is developed in C++, it has tremendous scalability and flexibility, making it simple for developers to query and index data.

Features of MongoDB Database

  • Document Oriented
  • No complex joins needed
  • Indexed Database
  • Scalability
  • Automatic Partitioning of Big Data
  • Schema-less Database
  • Replication
  • Aggregation Pipeline
  • GridFS
  • Sharding
  • High Performance

In this tutorial, we will explain step by step how to install and configure MongoDB on Ubuntu 20.04 server.

Also Read

Prerequisites

  1. You must have sudo / root privileges to install packages
  2. Internet connection
  3. Operating System :- Ubuntu 22.04, 20.04, 18.04 LTS.

Install MongoDB on Ubuntu 22.04 LTS

Step 1. First Update System Packages:

To install any package on Ubuntu operating system need to update the repository’s package list by using the following command:

sudo apt update
sudo apt install wget curl gnupg2 software-properties-common apt-transport-https ca-certificates lsb-release

Step 2. Import the Public Key

Run the following command to import the MongoDB public GPG Key:

curl -fsSL https://www.mongodb.org/static/pgp/server-6.0.asc|sudo gpg --dearmor -o /etc/apt/trusted.gpg.d/mongodb-6.gpg

Step 3. Next, add the MongoDB repository with the following command:

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

Step 4. Add dependence

sudo apt install libssl1.1

Step 5. Next, update the repository and install the MongoDB with the following command:

sudo apt update -y 
sudo apt install mongodb-org -y

OUTPUT:

root@vetechno:/home/user# apt install mongodb-org
Reading package lists… Done
Building dependency tree… Done
Reading state information… Done
The following additional packages will be installed:
mongodb-database-tools mongodb-org-database-tools-extra mongodb-org-mongos mongodb-org-server mongodb-org-shell mongodb-org-tools
The following NEW packages will be installed:
mongodb-database-tools mongodb-org mongodb-org-database-tools-extra mongodb-org-mongos mongodb-org-server mongodb-org-shell mongodb-org-tools
0 upgraded, 7 newly installed, 0 to remove and 101 not upgraded.
Need to get 98.0 MB of archives.
After this operation, 203 MB of additional disk space will be used.
Do you want to continue? [Y/n] Y
Get:1 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4/multiverse amd64 mongodb-database-tools amd64 100.6.0 [47.8 MB]
Get:2 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4/multiverse amd64 mongodb-org-shell amd64 4.4.17 [13.4 MB]
Get:3 https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4/multiverse amd64 mongodb-org-server amd64 4.4.17 [20.8 MB]
.
.
.
.
.
.
.

Once the installation of MongoDB has been completed, start the MongoDB service and enable it to start at reboot with the following command:

Managing the MongoDB Service

systemctl start mongod        # To start a MongoDB service
systemctl stop mongod         # To stop running MongoDB service
systemctl enable mongod       # To enable a MongoDB service at Server Startup
systemctl status mongod       # To check status of MongoDB service

OUTPUT:

root@vetechno:/home/user# systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor preset: enabled)
Active: active (running) since Thu 2022-10-27 14:32:06 UTC; 4s ago
Docs: https://docs.mongodb.org/manual
Main PID: 3883 (mongod)
Memory: 60.0M
CPU: 758ms
CGroup: /system.slice/mongod.service
└─3883 /usr/bin/mongod --config /etc/mongod.conf

Oct 27 14:32:06 vetechno systemd[1]: Started MongoDB Database Server.

Step 6. Check MongoDB Port

sudo ss -pnltu | grep 27017

OUTPUT:

root@vetechno:/home/user# sudo ss -pnltu | grep 27017
tcp LISTEN 0 4096 127.0.0.1:27017 0.0.0.0:* users:(("mongod",pid=1195,fd=10))

Step 7. Check MongoDB installed version:

mongod --version

OUTPUT:

db version v6.0.0
Build Info: {
    "version": "6.0.0",
    "gitVersion": "e61bf27c2f6a83fed36e5a13c008a32d563babe2",
    "openSSLVersion": "OpenSSL 1.1.1f  31 Mar 2020",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "ubuntu2004",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

Step 8. Verify MongoDB connection

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

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

OUTPUT:

root@vetechno:/home/user# mongo --eval 'db.runCommand({ connectionStatus: 1 })'
MongoDB shell version v4.4.17
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("c62d039c-8c1c-4354-8340-2c523b52a856") }
MongoDB server version: 4.4.17
{
"authInfo" : {
"authenticatedUsers" : [ ],
"authenticatedUserRoles" : [ ]
},
"ok" : 1
}

A value of 1 for the ok field indicates success.

Step 9. Starting MongoDB shell:

To login into the MongoDB, you can open the “mongo shell” with the following terminal command.

root@vetechno:/home/user# mongo

MongoDB shell version v4.4.17
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("831ab8d8-758b-46ae-818f-72bdcb8cd58f") }
MongoDB server version: 4.4.17
---

The server generated these startup warnings when booting: 
        2022-10-28T18:01:09.394+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
        2022-10-28T18:01:11.140+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
        Enable MongoDB's free cloud-based monitoring service, which will then receive and display
        metrics about your deployment (disk utilization, CPU, operation statistics, etc).

        The monitoring data will be available on a MongoDB website with a unique URL accessible to you
        and anyone you share the URL with. MongoDB may use this information to make product
        improvements and to suggest MongoDB products and deployment options to you.

        To enable free monitoring, run the following command: db.enableFreeMonitoring()
        To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
> 
> 
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> 

How to Configuring MongoDB on Ubuntu 22.04 LTS

In MongoDB, Authentication is not enabled by default, so each user will have access to all databases and perform any action (can view, add and delete data without any permissions). For production environments, it is recommended to enable the MongoDB authentication.

To enable the MongoDB authentication, MongoDB default configuration file is located at /etc/mongod.conf

vim /etc/mongod.conf

Add the below line in security section.

security:
  authorization: enabled

Save the mongod.conf file by using :wq , restart the mongod service and check the status.

systemctl restart mongod        # To restart a MongoDB service
systemctl status mongod       # To check status of MongoDB service

How to Configure MongoDB for remote access on Ubuntu 22.04 LTS

By default, mongodb is configured to only allow local access, that means it is set to be accessed locally on the same server where it is installed.

To enable remote access, you need to edit the /etc/mongod.conf file which is the main configuration file for MongoDB.

vim /etc/mongod.conf

Move to network interfaces section and instead of 127.0.0.1 put 0.0.0.0 to bind to all IPv4 and IPv6 address. It will allow any server to access MongoDB.

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

OUTOUT:

# network interfaces 
net:   
   port: 27017
   bindIp: 0.0.0.0

Save the mongod.conf file by using :wq , restart the mongod service and check the status.

systemctl restart mongod        # To restart a MongoDB service
systemctl status mongod # To check status of MongoDB service

How to create Administrative MongoDB User on Ubuntu 22.04 LTS

If you enabled MongoDB authentication, you must create an administrative user that can access and manage the MongoDB instance.

First, we need access the MongoDB shell.

root@vetechno:/home/user# mongo

MongoDB shell version v4.4.17
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("831ab8d8-758b-46ae-818f-72bdcb8cd58f") }
MongoDB server version: 4.4.17
---

The server generated these startup warnings when booting:
2022-10-28T18:01:09.394+00:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem
2022-10-28T18:01:11.140+00:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted
---
---
Enable MongoDB's free cloud-based monitoring service, which will then receive and display
metrics about your deployment (disk utilization, CPU, operation statistics, etc).

The monitoring data will be available on a MongoDB website with a unique URL accessible to you
and anyone you share the URL with. MongoDB may use this information to make product
improvements and to suggest MongoDB products and deployment options to you.

To enable free monitoring, run the following command: db.enableFreeMonitoring()
To permanently disable this reminder, run the following command: db.disableFreeMonitoring()
---
>

By default, there are three databases that are created upon installation. These are adminconfig, and local. `To list the existing databases, run the command:

show dbs

OUTPUT:

> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB

To create the administrator User, connect or switch to the admin database.

use admin

OUTPUT:

> use admin
switched to db admin

Run the following command to create a new user named mongoAdmin, with password change_password_here and userAdminAnyDatabase role:

db.createUser(
   {
     user: "mongoAdmin",
     pwd: "change_password_here",
     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
   }
 )

OUTPUT:

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

To check the user in current database, follow the below command.

> show users
{
	"_id" : "admin.mongoAdmin",
	"userId" : UUID("b8a42149-0294-496f-8b3b-bc85e0ee51b1"),
	"user" : "mongoAdmin",
	"db" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

Login MongoDB with administrator user

Till now we have enabled the mongodb authentication, configured remote access and created new mongodb administrator user.

Now we will login MongoDB with administrator user, to do so follow the below command

mongo -u mongoAdmin -p --authenticationDatabase admin

To remote access MongoDB, follow the below command

mongo remote_IP:27017 -u "mongoAdmin" -p --authenticationDatabase "admin"

How to Uninstall MongoDB from Ubuntu 22.04 LTS

Before removing MongoDB, make sure you have taken the backup of all databases. With the help of below command, it will completely remove the MongoDB.
First, stop the server using below command.

systemctl stop mongod         # To stop running MongoDB service

Now remove the MongoDB services.

apt purge mongodb
apt remove mongodb
apt autoremove

Conclusion

In the above tutorial, you learned how to install and configure MongoDB on Ubuntu 22.04 server.
Please let me know in the comment box if you are facing any issue.
Happy Learning !!!

Leave a Reply

Your email address will not be published. Required fields are marked *