We are committed to provide service 24 X 7

Deals, Shopping, Training, Tools

Learn how to – How To Install MongoDB 6 on Debian 11 / Debian 10

Learn how to – How To Install MongoDB 6 on Debian 11 / Debian 10.

NoSQL database is a database type where information is stored in JSON documents as opposed to rows and columns used in Relational databases. This technology was implemented in the 1970s when data storage was extremely expensive. In SQL databases, data is organized in rows and columns which make them extremely inflexible and difficult to modify. In NoSQL databases, developers are not tied to the rigid tabular approach and therefore are able to enjoy flexible schemas and scale easily with large amounts of data and high user loads.

The most popular NoSQL databases are Apache Cassandra, ElasticSearch, Amazon DynamoDB, HBase, Couchbase, Redis, MongoDB e.t.c

MongoDB is a cross-platform, object-oriented NoSQL database developed by MongoDB Inc. licensed under the Server Side Public License. It is implemented in C++ language and supports both 32 and 64-bit systems. MongoDB is highly used in applications that require enormous scalability and flexibility.

MongoDB provides high availability through a replica set. This is typically a group of mongod services that have the same data set. They provide high availability which is basic for all production deployments. In MongoDB replication, there are data-bearing nodes and optionally one arbiter node. In the data-bearing nodes group, only one is considered the Primary node and the others the secondary nodes. The primary node mainly receives all the write operations from the application. The secondary nodes replicate the primary node’s operation logs. The secondary nodes replicate data sets from the primary node.

The image below can be used to understand the architecture:

MongoDB is highly used in the following areas:

  • Inventory and catalog management – NoSQL databases provide high availability and predictable, cost-effective, horizontal scalability. This makes MongoDB effective in e-commerce companies that have massive and rowing online catalogs.
  • E-commerce product catalog – organizations are able to build applications with improved customer satisfaction by providing a single view of the customer by aggregating customer and product information
  • Mobile and social networking sites – MongoDB is able to handle;e large volumes of data extremely fast.
  • Real-time analytics and high-speed logging – It is used in customer analytics, real-time data integration that requires large volumes of high-speed data logging and aggregation
  • Fraud detection and identity authentication – MongoDB is used to provide real-time analysis of a large volume to identify any abnormality
  • Financial services and payments
  • Content management systems

Features of MongoDB 6.0

The latest release MongoDB 6.0 offers a lot of features that include:

  • Improved support for event-driven architectures – MongoDB 6.0 enriches change streams, adding abilities that take change streams to the next level.
  • More operators, less work – The operators allow enable you to push more work to the database while spending less time writing code.
  • Deeper insights from enriched queries – users are able to process multiple documents and return computed results. This can help build complex data processing pipelines to extract the insights you need.
  • Data security and operational efficiency – It allows users to compress and encrypt audit events before being written to the disk, leveraging their own KMIP-compliant key management system. The log encryption protects event integrity and confidentiality.
  • Seamless data sync – The Cluster-to-Cluster Sync provides an easy way to migrate data to the cloud, with continuous, unidirectional data synchronization between two MongoDB clusters
  • More resilient operations – MongoDB’s replica set design allows users to withstand and overcome outages. MongoDB 6.0 introduces improvements to sharding, the mechanism that enables horizontal scalability.

This guide provides the required steps on how to install MongoDB 6 on Debian 11 / Debian 10

System Requirements

To enable to install and run MongoDB, you need the following CPU architectures:

  • For x86_64 microarchitecture:
    • Intel x86_64 of a Sandy Bridge or later Core processor or a Tiger Lake or later Celeron or Pentium processor
    • AMD x86_64 of a Bulldozer or later processor.
  • ARM64 microarchitecture
    • ARMv8.2-A or later microarchitecture

Check the architecture using the command:

$ cat /proc/cpuinfo
processor	: 0
vendor_id	: GenuineIntel
cpu family	: 6
model		: 94
model name	: Intel(R) Xeon(R) CPU E3-1275 v5 @ 3.60GHz
stepping	: 3
microcode	: 0xf0
cpu MHz		: 3600.056
cache size	: 16384 KB
.....

#1. Add MongoDB 6.0 Repository

MongoDB offers two major editions:

  • Community edition: a free edition
  • Enterprise edition: provided as part of the Mongo Enterprise Advanced subscription. It offers advanced features such as on-disk encryption, Kerberos and LDAP support, auditing e.t.c.

In this guide, we will install the Community Edition, but since it is not provided in the default repositories, we need to add the repositories to the system.

Install the required tools:

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

First, import the 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

Now add the MongoDB 6.0 repository to the system.

##On Debian 11
echo "deb http://repo.mongodb.org/apt/debian bullseye/mongodb-org/6.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

##On Debian 10
echo "deb http://repo.mongodb.org/apt/debian buster/mongodb-org/6.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

Once added, update the APT package index:

sudo apt update

#2. Install MongoDB 6.0 on Debian 11 / Debian 10

Once the repository has been added, MongoDB 6.0 can be installed with the command:

sudo apt install mongodb-org

Dependency Tree:

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 39 not upgraded.
Need to get 134 MB of archives.
After this operation, 458 MB of additional disk space will be used.
Do you want to continue? [Y/n] y

You can also install a specific version for each component:

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

Once the installation is complete, start and enable the service:

sudo systemctl enable --now mongod

Verify that the service is running:

$ systemctl status mongod
 mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2022-07-28 16:04:35 EDT; 50s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 537 (mongod)
     Memory: 140.8M
        CPU: 822ms
     CGroup: /system.slice/mongod.service
             └─537 /usr/bin/mongod --config /etc/mongod.conf

Check the available version of MongoDB:

$ mongod --version
db version v6.0.0
Build Info: {
    "version": "6.0.0",
    "gitVersion": "e61bf27c2f6a83fed36e5a13c008a32d563babe2",
    "openSSLVersion": "OpenSSL 1.1.1n  15 Mar 2022",
    "modules": [],
    "allocator": "tcmalloc",
    "environment": {
        "distmod": "debian11",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

#3. Configure MongoDB 6.0 on Debian 11 / Debian 10

MongoDB stores its config file at /etc/mongod.conf. There are many configurations you can make in the file such as database path, logs path, listening port, address e.t.c. In this guide, we will make the below configs:

Enable Password Authentication

When installed, MongoDB does not offer password protection to the database. This can pose a security threat since anyone can access and use the database. To secure the instance, you need to create a user and set a password:

Access the shell:

mongosh

Create the admin user:

use admin
db.createUser(
{
user: "mongouser",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)

You will be required to provide a password for the user. Once set, exit the shell and enable authentication in the config file:

sudo vim /etc/mongod.conf

Find and uncomment the security part and add the line as shown.

security:
    authorization: "enabled"

Enable Remote Access

MongoDB listens on localhost by default, to change this and enable it to listen on the IP address, edit the config as shown:

# network interfaces
net:
  port: 27017
  bindIp: 0.0.0.0

Once the desired changes have been made, save the file and restart the service:

sudo systemctl restart mongod

If you have a firewall enabled, allow the port through it:

sudo ufw allow 27017

#4. Using MongoDB 6.0 on Debian 11 / Debian 10

Now access the MongoDB shell using the admin user and password created earlier.

$ mongosh -u mongouser
Enter password: *********
Connecting to:		mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.5.3
Using MongoDB:		6.0.0
Using Mongosh:		1.5.3

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

test>

Create a Database MongoDB

First, list the available databases:

> show dbs
admin   132.00 KiB
config   12.00 KiB
local    72.00 KiB

To create a database in MongoDB, just switch to a non-existing database. For example:

> use sampledb
switched to db sampledb

Create a collection in MongoDB

Collections are equivalent to tables in SQL databases. To create a table in MongoDB, use a command with the below syntax:

db.userdetails.insertOne(
   {F_Name: "Computing",
    L_NAME: "ForGeeks",
    ID_NO: "124345",
     AGE: "49",
     TEL: "25465467187"
   }
)

Once created, list the available collections:

> show collections
userdetails

Create an overall admin

An overall admin has the ability to access and use any database. For example, the user created earlier was an overall admin. To create another admin user, use the command:

use admin
db.createUser(
  {
    user: 'admin',
    pwd: 'AdminPassW0rd',
    roles: [ { role: 'userAdminAnyDatabase', db: 'admin' } ]
  }
);

Create an admin for a specific database

You can create an admin user for a specific database. For example:

use testdatabase
db.createUser(
  {
    user: 'testadmin',
    pwd: 'TestPassW0rd',
    roles: [ { role: 'userAdmin', db: 'testdatabase' } ]
  }
);

Create a User with Read and Write privileges

It is also possible to create a user with read and write permissions to a specific database. For example:

use testdatabase
db.createUser(
   {
     user: 'testuser',
     pwd: 'TestPassW0rd',
     roles: [ { role: 'readWrite', db: 'testdatabase' } ]
   }
 );

List Users on MongoDB

To list the available users, query the system.users collection.

use admin
db.system.users.find()

Sample Output:

Exit the shell using the command:

> exit

#5. Using a Custom Data Path in MongoDB

Normally, MongoDB stores its data in /var/lib/mongodb. However, this can be changed to another preferred data path. To achieve this, begin by stopping the service:

sudo systemctl stop mongod.service

Create the custom data path with the correct permissions:

sudo mkdir -p /data/mongo
sudo chown -R mongodb:mongodb /data/mongo

Proceed and copy the contents of the old directory to this new path:

sudo cp -r /var/lib/mongodb/* /data/mongo

You can move the old directory to a backup file:

sudo mv /var/lib/mongodb /var/lib/mongodb.bak

Now edit the config file to accommodate the new path:

sudo vim /etc/mongod.conf

Make the below changes:

# Where and how to store data.
storage:
  dbPath: /data/mongo
.......

Save the file, reload the daemon and start the service:

sudo systemctl daemon-reload
sudo systemctl start mongod

Verify if the service is running:

$ systemctl status mongod
● mongod.service - MongoDB Database Server
     Loaded: loaded (/lib/systemd/system/mongod.service; enabled; vendor preset: enabled)
     Active: active (running) since Thu 2022-07-28 16:36:02 EDT; 3s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 2020 (mongod)
     Memory: 164.3M
        CPU: 737ms
     CGroup: /system.slice/mongod.service
             └─2020 /usr/bin/mongod --config /etc/mongod.conf

Voila!

Conclusion

In this guide, we have installed MongoDB 6 on Debian 11 / Debian 10. In addition to that, we have learned how to configure MongoDB, and create users, databases, and collections.

Interested in more?

Cart

Your Cart is Empty

Back To Shop