How To Install MongoDB 5 on Ubuntu 22.04|20.04|18.04

Posted on 203 views

MongoDB is one of the popular NoSQL database server used in developing modern dynamic apps. It makes use of JSON-like documents and optional schemas; data objects stored as separate documents within a collection, as opposed to rows and columns used in traditional relational databases. MongoDB is highly scalable and flexible and offers easy querying and indexing for developers. Due to its horizontal scaling and load-balancing capabilities, MongoDB has offered developers highest levels of flexibility and scalability. MongoDB Atlas is a cloud database service and is the leading for developing modern applications and can deploy fully managed cloud databases across Azure, AWS or Google Cloud.

MongoDB offers both a community Edition which is free to download and use and an Enterprise Edition which is part of the MongoDB Enterprise Advanced subscription. This Enterprise version includes comprehensive support for your MongoDB deployment and offers enterprise-focused features such as LDAP and Kerberos support, on-disk encryption, and auditing.

Features and Advantages of MongoDB Database

  • Offers high scalability and flexibility; automatic failover and data redundancy
  • Offers an expressive query language which is simple to learn and use
  • Ad-hoc queries for real-time analytics
  • It supports arrays and nested objects as values, and allow for flexible and dynamic schemas.
  • It is easy to compose queries which allow sorting and filtering, no mater how nested, and supports aggregation, geo-location, time-series, graph search and more.
  • Supports sharding which enables splitting of large datasets across miltiple distributed collections which then ease querying.
  • Supports multiple storage engines

MongoDB 50 new features

MongoDB 5.0 is the latest version released in July 13, 2021. There are a number of fixes made from the previous versions and also some additional features which you can find them all in MongoDB 5.0 official release notes. Some of the additional features include:

  • Introduction of time series collections which efficiently store sequences of measurements over a period of time.
  • Deprecation of map-reduce operation.
  • Introduction of new aggregation operators such as $dateAdd, $dateDiff, $dateSubtract, $getField, $rand and many more. Check the documentation document.
  • Introduction of $setWindowFields pipeline stage which enables performing of operations on a specified span of documents in a collection, known as a window.
  • Add the capability of configuring auditing filters at runtime.

Install MongoDB 5 on Ubuntu 22.04|20.04|18.04

The below steps will guide us on how we can get MongoDB 5.0 installed in Ubuntu 22.04|20.04|18.04.

Step 1: Import MongoDB GPG Key

Update APT package index and install basic utility packages required:

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

We first need to import MongoDB public GPG key as below:

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

Step 2: Add MongoDB Repository on Ubuntu 22.04|20.04|18.04

To be able to install MongoDB with apt, we need to add MongoDB repository.

Ubuntu 22.04 / 20.04:

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

Ubuntu 18.04:

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

Step 3: Install MongoDB 5.0 on Ubuntu 22.04|20.04|18.04

We have already added MongoDB GPG and repository, we proceed to install MongoDB. Update packages first

sudo apt update
sudo apt install mongodb-org

Accept installation prompt:

....
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following additional packages will be installed:
  mongodb-database-tools mongodb-mongosh mongodb-org-database 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-mongosh mongodb-org mongodb-org-database mongodb-org-database-tools-extra mongodb-org-mongos mongodb-org-server mongodb-org-shell mongodb-org-tools
0 upgraded, 9 newly installed, 0 to remove and 72 not upgraded.
Need to get 143 MB of archives.
After this operation, 461 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

If you wish to install a specific version of MongoDB, you can pass the version as shown below.

sudo apt-get install -y mongodb-org= mongodb-org-database= mongodb-org-server= mongodb-org-shell= mongodb-org-mongos= mongodb-org-tools=

Step 4: Start MongoDB 5.0 on Ubuntu 22.04|20.04|18.04

Once the installation process is complete, proceed to start and enable MongoDB

sudo systemctl restart mongod

Confirm that MongoDB is actually running

$ systemctl status mongod
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; disabled; vendor prese>
     Active: active (running) since Tue 2021-08-24 15:42:58 UTC; 11s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 14497 (mongod)
     Memory: 61.6M
     CGroup: /system.slice/mongod.service
             └─14497 /usr/bin/mongod --config /etc/mongod.conf

Aug 24 15:42:58 lorna-ubuntu20 systemd[1]: Started MongoDB Database Server.

Confirm MongoDB version

$ mongod --version
db version v5.0.9
Build Info: 
    "version": "5.0.9",
    "gitVersion": "6f7dae919422dcd7f4892c10ff20cdc721ad00e6",
    "openSSLVersion": "OpenSSL 1.1.1f  31 Mar 2020",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": 
        "distmod": "ubuntu2004",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    

You can then enable MongoDB to automatically start on system reboot.

$ sudo systemctl enable mongod
Created symlink /etc/systemd/system/multi-user.target.wants/mongod.service → /lib/systemd/system/mongod.service.

Step 5: Configure MongoDB 5.0 on Ubuntu

The configuration file for MongoDB is found in /etc/mongod.conf. Here, you will find the configurations for db path, logs path. You cak always make you changes to this file depending on your installation needs. Restart mongod service every time you make a change to the file.

Mongodb Enable Password Authentication

Let’s enable mongodb password authentication so that users can login with a password to read or edit database. Uncomment #Security and the add the content to be as below

security:
  authorization: enabled

After that restart mongod service

sudo systemctl restart mongod

MongoDB Enable Remote Access

By default, MongoDB can only be accesses locally. If you wish to be able to access the database remotely, we will make a small change on the configuration file to include MongoDB server IP address or hostname as shown below.

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,mongodb-server-ip

Save the changes and restart mongod service. You also need to allow on the firewall the trusted remote IP addresses if you have enabled your firewall

sudo ufw allow from trusted-server-ip to any port 27017

Step 6: Creating a Users and Database in MongoDB

To access MongoDB shell, run the command mongosh on the terminal as shown

$ mongosh
Current Mongosh Log ID:	6298e0a77a8138c811c6c8a0
Connecting to:		mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.0
Using MongoDB:		5.0.9
Using Mongosh:		1.5.0

For mongosh info see: https://docs.mongodb.com/mongodb-shell/
..........
> 

To list existing databases

> show dbs
admin       135 kB
config      111 kB
local      73.7 kB

How to Create a User and Add Role in MongoDB

Let’s see how we can create a user in MongoDB and give them admin roles and permission to all databases

> db.createUser(
        user: "testuser",
        pwd:  "TestUserPassword",
        roles: [role: "userAdminAnyDatabase" , db: "admin"]
);
 ok: 1 

To allow a user to have permission to a specific database

db.createUser(
        user: "testuser2",
        pwd:  "TestUser2Password",
        roles: [role: "userAdmin" , db: "employees"]
);

To create a new database in MongoDB, we use the command use. MongoDB does not have create command. As an example, create a new database called ‘test

> use employees
switched to db employees

You need to add some information to the DB for it to be listed when you list databases.

db.Employees.insertOne(name: "hale" , age: 20 , department: "IT")

  acknowledged: true,
  insertedId: ObjectId("61252c7492f10ccae358d787")

MongoDB insertOne and insertMany

Note that Collection.insert() is deprecated and you should use insertOneinsertMany, or bulkWrite.

Now when you show databases, you new db should also be listed

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

Step 7: MongoDB Tuning

Once you have MongoDB installed, it is important to ensure its performance is at optimal configurations. As information increases, our MongoDB installation should be able to handle and process as expected. Scaling can occur both horizontally or vertically. Horizontal scaling means addition of server resources such as RAM and CPU while vertical scaling is the introduction of more servers in our installation.

A vertical scaling, which is very crucial in the overall performance of mongodb is influenced by certain factors including: Memory use, Number of concurrent connections and WiredTiger Cache among others. Memory is one important factor that highly influence MongoDB performance. MongoDB uses WiredTiger as its default storage engine and it therefore preservers 50% of (available memory -1) for WiredTiger.

For example, a server with 8GB RAM will have 0.5*(8-1) memory preserver for WiredTiger. To check cache usage statistics and determine whether you need to make changes, run the command below:

> db.serverStatus().wiredTiger.cache
{
  'application threads page read from disk to cache count': 6,
  'application threads page read from disk to cache time (usecs)': 46,
  'application threads page write from cache to disk count': 184,
  'application threads page write from cache to disk time (usecs)': 10501,
  'bytes allocated for updates': 65768,
  'bytes belonging to page images in the cache': 30285,
  'bytes belonging to the history store table in the cache': 571,
  'bytes currently in the cache': 104652,
  'bytes dirty in the cache cumulative': 2813442,
  'bytes not belonging to page images in the cache': 74366,
  'bytes read into cache': 28042,
  'bytes written from cache': 1283385,
  'cache overflow score': 0,
  'checkpoint blocked page eviction': 0,
  'checkpoint of history store file blocked non-history store page eviction': 0,
  'eviction calls to get a page': 2,
  'eviction calls to get a page found queue empty': 2,
  'eviction calls to get a page found queue empty after locking': 0,
  'eviction currently operating in aggressive mode': 0,
  'eviction empty score': 0,
  'eviction passes of a file': 0,
  'eviction server candidate queue empty when topping up': 0,
  'eviction server candidate queue not empty when topping up': 0,
  'eviction server evicting pages': 0,
  'eviction server slept, because we did not make progress with eviction': 0,
  'eviction server unable to reach eviction goal': 0,
  'eviction server waiting for a leaf page': 0,
  'eviction state': 64,
  'eviction walk target pages histogram - 0-9': 0,
  'eviction walk target pages histogram - 10-31': 0,
  'eviction walk target pages histogram - 128 and higher': 0,
  'eviction walk target pages histogram - 32-63': 0,
  'eviction walk target pages histogram - 64-128': 0,
  'eviction walk target pages reduced due to history store cache pressure': 0,
  'eviction walk target strategy both clean and dirty pages': 0,
  'eviction walk target strategy only clean pages': 0,
  'eviction walk target strategy only dirty pages': 0,
  'eviction walks abandoned': 0,
..............

From the above output, of major importance are:

  • wiredTiger.cache.maximum bytes configure
  • wiredTiger.cache.bytes currently in the cache
  • wiredTiger.cache.tracked dirty bytes in the cache
  • wiredTiger.cache.pages read into cache
  • wiredTiger.cache.pages written from cache

The current sizes of the above should enable us to make a decision of whether to increase the size of the WiredTiger in our servers. Another thing that is equally important is WiredTiger Concurrency Read and Write Ticket usage which can be checked as below:

> db.serverStatus().wiredTiger.concurrentTransactions

  write:  out: 0, available: 128, totalTickets: 128 ,
  read:  out: 1, available: 127, totalTickets: 128 

If you notice the numbers increasing and tending towards that available number of cores, your servers might be approaching CPU saturation.

In this guide, we have learned how to install the latest MongoDB version, which is MongoDB 5, and we have also seen how to create users with specific roles as well as how to create and use databases in MongoDB. We finishes by looking at tuning MongoDB 5 to ensure desired performance at any given time. I hope the guide has been useful.

coffee

Gravatar Image
A systems engineer with excellent skills in systems administration, cloud computing, systems deployment, virtualization, containers, and a certified ethical hacker.