How to install MongoDB in CentOS

MongoDB is a open source database management system document-oriented and multiplatform, designed to be scalable, have high performance (both for reading and for writes enviroments) and high availability, scaling from a single server configuration to large and complex data center architectures.

MongoDB is an agile database that allows schemas to change quickly as applications evolve, while still providing the functionality developers expect from traditional databases, such as secondary indexes, a full query language and strict consistency.

MongoDB includes integration with hadoop, official drivers for 10 programming languages, as well as 40 drivers developed and maintained by the community.

MongoDB Features:

  • JSON Data Model with Dynamic Schemas. MongoDB uses the BSON format to internally represent the data JSON format used for model the data.
  • Auto-Sharding for Horizontal Scalability
  • Built-In Replication for High Availability
  • Rich Secondary Indexes, including geospatial
  • TTL indexes
  • Text Search
  • Aggregation Framework & Native MapReduce

MongoDB components:

  • MongoDB Server (mongod): is the service that handles requests and access to data, permissions and authentication, databases and more.
  • MongoDB shell (mongo): Client to connect to the MongoDB server and perform data queries and administratives.
  • Mongos instances (mongos): provide the interface between the client applications and the sharded cluster
  • MongoDB tools.

MongoDB is developed by MongoDB Inc. and is released under a combination of the Server-side Public License and the Apache License. See MongoDB Licensing for more details

Add MongoDB repository

In this step we will create the file mongodb.repo which contains the definition of the MongoDB repository version 4.2

$ sudo bash -c 'cat > /etc/yum.repos.d/mongodb.repo <<EOF
[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
EOF
'

You can get the list of available packages by executing:

$ sudo dnf search mongodb-
...
mongodb-org.x86_64 : MongoDB open source document-oriented database system (metapackage)
mongodb-org-shell.x86_64 : MongoDB shell client
mongodb-org-tools.x86_64 : MongoDB tools
mongodb-org-mongos.x86_64 : MongoDB sharded cluster query router
mongodb-org-server.x86_64 : MongoDB database server

Install MongoDB

With the following command we install the latest stable version

$ sudo bash -c 'dnf update && dnf -y install mongodb-org' 

Configuring SELinux

mongod process needs to access /sys/fs/cgroup/ to determine the memory available on your system. If you intend to run SELinux in enforcing mode, you will need to make the following adjustment to your SELinux policy:

1. Check the checkpolicy package is installed:

$ sudo dnf install checkpolicy

2. Create a custom policy file mongodb_cgroup_memory.te

$ cat > mongodb_cgroup_memory.te <<EOF
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 };
EOF

3. Once created, compile and load the custom policy module by running these three commands:

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

Disable Diagnostic Parameters

The diagnostic parameters is a data collection mechanism, such as server statistics and status messages (only useful if you have a support agreement with MongoDB Inc. because this information can be sent to MongoDB engineers to facilitate analysis of MongoDB server behavior); this information is stored in binary format and you will not know what infomration is store on it unless you check the MongoDB source code, therefore it is recommended to disable it.

Edit the file mongod.conf (/etc/mongod.conf) and add the following lines:

setParameter:
  diagnosticDataCollectionEnabled: false

Disable Transparent Huge Pages (THP)

Transparent Huge Pages (THP) is a Linux memory management system that reduces the overhead of Translation Lookaside Buffer (TLB) lookups on machines with large amounts of memory by using larger memory pages. However, database workloads often perform poorly with THP enabled, because they tend to have sparse rather than contiguous memory access patterns.

For more information check:

1. Create the systemd service

With the this systemd unit we guarantee to disable THP before the mongod service starts

$ sudo bash -c "cat > /etc/systemd/system/disable-transparent-huge-pages.service <<EOF
[Unit]
Description=Disable Transparent Huge Pages (THP)
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=mongod.service

[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never | tee /sys/kernel/mm/transparent_hugepage/enabled > /dev/null'

[Install]
WantedBy=basic.target
EOF
"

2. Reload systemd units

Reload systemd units so the disable-transparent-huge-pages.service is available for use:

$ sudo systemctl daemon-reload

Run and manage the mongod process

In this part we will learn how to start, stop or restart the mongod service, for this we will use the systemd initialization system.

Start MongoDB

$ sudo systemctl start mongod

If you get an error like this:

Failed to start mongod.service: Unit mongod.service not found.

Type:

$ sudo systemctl daemon-reload

and later the previous command.

Verify mongod status

With this command we get information about mongod service

$ sudo systemctl status mongod
● mongod.service - MongoDB Database Server
   Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2020-04-06 11:20:19 EDT; 1min 16s ago
     Docs: https://docs.mongodb.org/manual
  Process: 3361 ExecStart=/usr/bin/mongod $OPTIONS (code=exited, status=0/SUCCESS)
  Process: 3359 ExecStartPre=/usr/bin/chmod 0755 /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 3357 ExecStartPre=/usr/bin/chown mongod:mongod /var/run/mongodb (code=exited, status=0/SUCCESS)
  Process: 3354 ExecStartPre=/usr/bin/mkdir -p /var/run/mongodb (code=exited, status=0/SUCCESS)
 Main PID: 3363 (mongod)
   Memory: 165.7M
   CGroup: /system.slice/mongod.service
           └─3363 /usr/bin/mongod -f /etc/mongod.conf

Apr 06 11:20:19 localhost.localdomain systemd[1]: Stopped MongoDB Database Server.
Apr 06 11:20:19 localhost.localdomain systemd[1]: Starting MongoDB Database Server...
Apr 06 11:20:19 localhost.localdomain mongod[3361]: about to fork child process, waiting until server is ready for connections.
Apr 06 11:20:19 localhost.localdomain mongod[3361]: forked process: 3363
Apr 06 11:20:19 localhost.localdomain mongod[3361]: child process started successfully, parent exiting
Apr 06 11:20:19 localhost.localdomain systemd[1]: Started MongoDB Database Server.

Start MongoDB with SO

You can ensure that MongoDB will start following a system reboot by issuing the following command:

$ sudo systemctl enable mongod

Stop MongoDB

As needed, you can stop the mongod process by issuing the following command:

$ sudo systemctl stop mongod

Restart MongoDB

You can restart the mongod process by issuing the following command:

$ sudo systemctl restart mongod

You can follow the state of the process for errors or important messages by watching the output in the /var/log/mongodb/mongod.log file.

Connect to MongoDB using mongo shell

Start a shell mongo on the same server that runs the mongod service. By default the mongod service listen for connections at the loopback address: 127.0.0.1 and on port 27017, you can change this behavior by modifying the net section in the configuration file, note that if you change the bindIp or bindIpAll then you can connect to the MongoDB server from another device without specifying username and password and this carries a security risk, then it is necessary to enable Role-based access control.

Role-Based Access Control

Edit the configuration file and add:

security:
  authorization: enabled
Create user admin

Connect to the server executing

$ mongo

the type:

use admin

then we create the user admin, which will have all the permissions and/or accesses in all the DBs (note the role userAdminAnyDatabase).

db.createUser({
    user: "admin",
    pwd: "MyPass",
    roles: [
        {
            role: "userAdminAnyDatabase",
            db: "admin"
        },
        "readWriteAnyDatabase"
    ],
});

Now restart the mongod service

$ sudo systemctl restart mongod

Connect using the user admin

$ mongo -u "admin"  --authenticationDatabase "admin" mongodbServer
MongoDB shell version v4.2.3
Enter password:

The --authenticationDatabase option means that the credentials will be check against the DB admin.

Further readings

The MongoDB 4.2 Manual

The tutorials here on LibreByte are provided under a free software licence. if you like my work you should consider:
Buy a Hosting/VPS or Dedicated Server at MCKHost

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.