Share on Social Media

MongoDB is an open-source document-oriented NoSQL database management system. In this article, you will learn how to install MongoDB on CentOS 8 server. #centlinux #linux #nosql

What is MongoDB?

MongoDB is a popular, open-source NoSQL database designed for handling large volumes of unstructured or semi-structured data. Unlike traditional relational databases, MongoDB uses a flexible, JSON-like format to store data, making it well-suited for applications that require rapid iteration, scalability, and real-time data processing. Here are some key features and concepts of MongoDB:

Document-Oriented Storage

  • Documents: Data in MongoDB is stored in documents, which are JSON-like objects called BSON (Binary JSON). Each document contains key-value pairs, allowing for a flexible schema design.
  • Collections: Documents are grouped into collections, which are analogous to tables in relational databases. Collections do not enforce a schema, allowing each document to have a different structure.

Schema Flexibility

  • MongoDB’s schema-less design allows developers to store data without defining the structure in advance. This flexibility makes it easy to evolve the database schema as application requirements change.

Scalability

  • MongoDB is designed to scale horizontally by distributing data across multiple servers, a process known as sharding. This allows the database to handle large amounts of data and high traffic loads.

High Availability

  • MongoDB ensures high availability through replication. A replica set in MongoDB consists of multiple copies of data, with one primary node and multiple secondary nodes. If the primary node fails, a secondary node is automatically promoted to primary.

Indexing

  • MongoDB supports various types of indexes to improve query performance, including single-field, compound, geospatial, and text indexes. Indexing helps speed up data retrieval operations.

Aggregation Framework

  • The aggregation framework in MongoDB allows for complex data processing and transformation operations. It includes features like filtering, grouping, sorting, and performing calculations on data.

Ad Hoc Queries

  • MongoDB supports ad hoc queries, allowing users to search and filter data using a rich query language. Queries can include conditions, ranges, and even regular expressions.

Built-In Sharding

  • MongoDB’s sharding mechanism distributes data across multiple servers automatically, making it easy to scale out as data volume grows.

Geospatial Support

  • MongoDB includes powerful geospatial features for storing and querying location-based data, making it suitable for applications involving maps, GPS, and spatial analysis.

Community and Ecosystem:

  • MongoDB has a large and active community, extensive documentation, and a rich ecosystem of tools and libraries. The MongoDB ecosystem includes tools for data visualization, management, backup, and integration with various programming languages and frameworks.

MongoDB is widely used in various industries, including e-commerce, social media, gaming, and IoT, due to its ability to handle diverse data types and its ease of integration with modern application development practices.

Although, we are installing MongoDB 4.2 on CentOS 8, but the same procedure will work for CentOS 7, RHEL 7, RHEL 8 and similar distros.

Recommended Online Training: Learn MongoDB From Scratch For Beginners to Advance

5822578 eb2f 2show?id=oLRJ54lcVEg&offerid=1074530.5822578&bids=1074530

DynamoDB vs MongoDB

DynamoDB and MongoDB are both NoSQL databases, but they have distinct differences in terms of design, features, and use cases. Here’s a comparison of the two:

DynamoDB

  1. Provider: Developed and managed by Amazon Web Services (AWS).
  2. Data Model: Key-Value and Document store. Each item is identified by a primary key (partition key or partition key + sort key).
  3. Scalability: DynamoDB automatically scales to handle large amounts of data and high traffic loads. It provides seamless horizontal scaling.
  4. Performance: Designed for high performance with consistent low latency. You can provision read and write capacity units to manage performance.
  5. Management: Fully managed by AWS, which means it handles tasks like backups, patching, and automatic scaling for you.
  6. Integration: Integrates well with other AWS services such as Lambda, S3, and CloudWatch.
  7. Cost: Pricing is based on the provisioned throughput, storage, and data transfer. There is also an on-demand pricing model that charges based on the number of read and write requests.
  8. Query Language: DynamoDB uses a proprietary API for querying and operations.
  9. Replication and Availability: Built-in support for global tables, which replicate data across multiple AWS regions for high availability and disaster recovery.
  10. Data Types: Supports simple data types (String, Number, Binary) and complex data types (Document, List, Map, Set).

MongoDB

  1. Provider: Developed by MongoDB, Inc. Available as a self-managed database or as a managed service called MongoDB Atlas.
  2. Data Model: Document store. Data is stored in BSON format (binary JSON), which allows for a flexible schema.
  3. Scalability: Supports horizontal scaling through sharding, which allows data to be distributed across multiple servers.
  4. Performance: Performance depends on the configuration and workload. It provides various indexing options to improve query performance.
  5. Management: Can be self-managed or used as a managed service (MongoDB Atlas). With Atlas, MongoDB handles backups, updates, and scaling.
  6. Integration: Integrates with a wide range of platforms and tools, including cloud services, DevOps tools, and programming languages.
  7. Cost: If self-managed, costs depend on the infrastructure used. MongoDB Atlas pricing is based on the cluster size, storage, and data transfer.
  8. Query Language: Uses a rich, JSON-based query language that is flexible and expressive.
  9. Replication and Availability: Supports replica sets, which provide redundancy and high availability. MongoDB Atlas offers multi-region deployment for global distribution.
  10. Data Types: Supports a wide variety of data types, including arrays, nested documents, and rich JSON-like structures.

Summary

  • DynamoDB: Best for applications requiring seamless scaling, low-latency performance, and deep integration with AWS services. Ideal for serverless architectures and high-throughput use cases.
  • MongoDB: Best for applications needing a flexible schema, rich querying capabilities, and the ability to handle complex, nested data structures. Suitable for diverse environments, including on-premises and multi-cloud setups.

Choosing between DynamoDB and MongoDB depends on your specific requirements, including scalability, performance, management preferences, and integration needs.

Read Also: How to install MongoDB on Rocky Linux 9

Linux Server Specification

We are using a minimal installed CentOS 8 virtual machine with following specifications.

  • CPU – 3.4 Ghz (2 cores)
  • Memory – 2 GB
  • Storage – 20 GB
  • Operating System – CentOS Linux 8.0
  • Hostname – mongodb-01.centlinux.com
  • IP Address – 192.168.116.206 /24

Install MongoDB Yum Repository

We can download our required installation package from MongoDB download page.

MongoDB Community Server Downloads
MongoDB Community Server Downloads

Here, you can choose your desired MongoDB release and the target operating system and the website will provide you a download link to the respective installation package. You can then download that RPM package and install it on CentOS 8 server by using dnf command.

But, there is a better way to install MongoDB on CentOS 8 server i.e. by installing MongoDB official yum repository in CentOS 8 and then install the MongoDB by using the dnf command, and we are using the same approach in this installation guide.

Connect with mongodb-01.centlinux.com as root user by using a ssh client.

Create a repo file in /etc/yum.repo.d directory to install MongoDB yum repository in CentOS 8 server.

# vi /etc/yum.repos.d/mongodb-org-4.2.repo

And add following configurations in this file.

[mongodb-org-4.2]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc

Build cache for MongoDB yum repository.

# yum makecache
CentOS-8 - AppStream                            6.0 kB/s | 4.3 kB     00:00
CentOS-8 - Base                                 5.7 kB/s | 3.8 kB     00:00
CentOS-8 - Extras                               2.9 kB/s | 1.5 kB     00:00
MongoDB Repository                              4.7 kB/s | 6.6 kB     00:01
Metadata cache created.

We have installed the MongoDB yum repository in CentOS 8 server.

Set Resource Limits for MongoDB Database

We need to set the resource limits in our CentOS 8 server as required by the MongoDB software.

For this purpotse, create a resource limit configuration file for MongoDB as follows.

# vi /etc/security/limits.d/mongod.conf

And add the following resource limits therein.

mongod soft nproc 64000
mongod hard nproc 64000
mongod soft nofile 64000
mongod hard nofile 64000

Install MongoDB on CentOS 8

Now, we can install MongoDB on CentOS 8 server from the newly added yum repository.

We are installing latest stable release of MongoDB server by using following dnf command.

# dnf install -y mongodb-org

Enable and start MongoDB database service.

# systemctl enable --now mongod.service

After successful start, check the status for MongoDB for any possible errors.

# systemctl status mongod.service
â mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor pres>
   Active: active (running) since Mon 2020-04-13 12:38:08 PKT; 13s ago
     Docs: https://docs.mongodb.org/manual
  Process: 2034 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCE>
  Process: 2031 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited,>
  Process: 2029 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (cod>
  Process: 2028 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, s>
 Main PID: 2036 (mongod)
   Memory: 76.8M
   CGroup: /system.slice/mongod.service
           ââ2036 /usr/bin/mongod -f /etc/mongod.conf

Apr 13 12:38:05 mongodb-01.centlinux.com systemd[1]: Starting MongoDB Database >
Apr 13 12:38:06 mongodb-01.centlinux.com mongod[2034]: about to fork child proc>
Apr 13 12:38:06 mongodb-01.centlinux.com mongod[2034]: forked process: 2036
Apr 13 12:38:08 mongodb-01.centlinux.com mongod[2034]: child process started su>
Apr 13 12:38:08 mongodb-01.centlinux.com systemd[1]: Started MongoDB Database S>

Create SELinux Policy for NoSQL Database

According to MongoDB documentation, if you have configured SELinux in enforcing mode then you have to create a SELinux policy for MongoDB.

Check current SELinux mode.

# getenforce
Enforcing

We need checkpolicy command to verfiy the custom SELinux policies, therefore we are installing checkpolicy package by using dnf command.

# dnf install -y checkpolicy

Create a custom SELinux policy file.

# vi mongodb_cgroup_memory.te

And add followingdirectives therein.

module mongodb_cgroup_memory 1.0;

require {
    type cgroup_t;
    type mongod_t;
    class dir search;
    class file { getattr open read };
}

#============= mongod_t ==============
allow mongod_t cgroup_t:dir search;
allow mongod_t cgroup_t:file { getattr open read };

Compiled and apply this SELinux policy.

# checkmodule -M -m -o mongodb_cgroup_memory.mod mongodb_cgroup_memory.te
# semodule_package -o mongodb_cgroup_memory.pp -m mongodb_cgroup_memory.mod
# semodule -i mongodb_cgroup_memory.pp

Create an Admin User in MongoDB Database

By default, Access Control is not enabled in MongoDB server, therefore, anyone can access MongoDB server and perform administrative actions.

Therefore, it is very important that, we create an Admin user and enable Access Control in our MongoDB server.

Connect with MongoDB shell as follows.

# mongo
MongoDB shell version v4.2.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("195cc9ab-b18a-4edc-9fb0-1266e4d961af") }
MongoDB server version: 4.2.5
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
        http://docs.mongodb.org/
Questions? Try the support group
        http://groups.google.com/group/mongodb-user
Server has startup warnings:
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten]
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten] ** WARNING: Access control is not enabled for the database.
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten] **          Read and write access to data and configuration is unrestricted.
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten]
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten]
2020-04-13T12:38:08.219+0500 I  CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2020-04-13T12:38:08.220+0500 I  CONTROL  [initandlisten] **        We suggest setting it to 'never'
2020-04-13T12:38:08.220+0500 I  CONTROL  [initandlisten]
---
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()
---

>

Connect with admin database.

> use admin;
switched to db admin

Create an admin user as follows.

> db.createUser(
...   {
...     user: "admin",
...     pwd: "123",
...     roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
...   }
... )
Successfully added user: {
        "user" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ]
}

List down all the users in MongoDB database.

> show users
{
        "_id" : "admin.admin",
        "userId" : UUID("cefd30bd-2e83-4959-a47a-087a423806a0"),
        "user" : "admin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

MongoDB admin user has been created successfully.

Exit from MongoDB shell.

> exit
bye

Enable Access Control in MongoDB Server

Initially, Access Control is disabled in MongoDB server. Therefore, any user that has operating system level access to CentOS 8 server can connect to MongoDB instance and perform administrative actions on the databases. That is why we were able to create an admin user without any authentication in the previous step.

To enable Access Control for MongoDB server, we need to edit the systemd unit file for mongod.service.

# vi /usr/lib/systemd/system/mongod.service

Find following line in this file.

Environment="OPTIONS=-f /etc/mongod.conf"

And replace it with following line.

Environment="OPTIONS=--auth -f /etc/mongod.conf"

We have edited a systemd unit file explicitly by using a text editor. Therefore, we need to execute the following command to inform systemd about this change.

# systemctl daemon-reload

Restart MongoDB service to apply the changes.

# systemctl restart mongod.service

For checking Access Control, connect with MongoDB shell and execute some administrative commands.

# mongo
MongoDB shell version v4.2.5
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("3526a97b-a0a1-47d2-91b1-0c15ef9f21e9") }
MongoDB server version: 4.2.5
> use admin
switched to db admin
> show users
2020-04-13T15:11:54.161+0500 E  QUERY    [js] uncaught exception: Error: command usersInfo requires authentication :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype.getUsers@src/mongo/shell/db.js:1638:15
shellHelper.show@src/mongo/shell/utils.js:883:9
shellHelper@src/mongo/shell/utils.js:790:15
@(shellhelp2):1:1

This time the “show user” command raises the authentication error, it confirms that the Access Control has been enabled in our MongoDB server.

Now, connect as admin user.

> db.auth("admin",passwordPrompt())
Enter password:
1

Now, execute the same command, to check if it is working or not.

> show users
{
        "_id" : "admin.admin",
        "userId" : UUID("cefd30bd-2e83-4959-a47a-087a423806a0"),
        "user" : "admin",
        "db" : "admin",
        "roles" : [
                {
                        "role" : "userAdminAnyDatabase",
                        "db" : "admin"
                }
        ],
        "mechanisms" : [
                "SCRAM-SHA-1",
                "SCRAM-SHA-256"
        ]
}

The command “show users” has been successfully executed with a privileged user.

Access Control for MongoDB database has been enabled.

Configure MongoDB Service

This step is optional. If you are planning to access your MongoDB database across the network, then you have to perform following configurations.

By default the MongoDB service runs on the localhost interface. Therefore, to make it accessible from the network, we need to run MongoDB service on all interfaces.

Edit MongoDB configuration file by using vim editor

# vi /etc/mongod.conf

Locate bindIp directive in this file and set it as.

bindIp: 0.0.0.0

Restart MongoDB service to apply changes.

# systemctl restart mongod.service

We are also required to allow incoming traffic to MongoDB service in Linux firewall.

# firewall-cmd --permanent --add-service=mongodb
success
# firewall-cmd --reload
success

You can now access MongoDB database service from network.

MongoDB Data and Log Directories

Following are the two directories, that are very important for MongoDB database administrators.

  • /var/lib/mongo – Data directory (default)
  • /var/log/mongodb – Log directory (default)

We can customize above directories by setting following parameters in /etc/mongodb.conf file.

  • storage.dbPath – to specify a new data directory path
  • systemLog.path – to specify a new log file path

MongoDB: The Definitive Guide: Powerful and Scalable Data Storage (PAID LINKby O’Reilly Media is a very good book on the MongoDB administration and we are highly recommend this for the MongoDB database administrators.

Final Thoughts

Thank you for following this guide on how to install MongoDB on CentOS 8. I hope this tutorial has made the installation process clear and straightforward, enabling you to set up a robust and scalable NoSQL database for your applications.

If you need further assistance with MongoDB installation, configuration, optimization, or any other related services, I am here to help. I offer professional services on Fiverr, including MongoDB setup, performance tuning, and troubleshooting. You can check out my profile and services here: Linux Server Admin

Feel free to reach out for any additional support. Happy database managing!

Leave a Reply