How To Install MongoDB 5.0 on Amazon Linux EC2. This article will walk you through installing MongoDB 5.0 on Amazon Linux 2. MongoDB is a NoSQL database server that is used to create current dynamic apps. It is a general-purpose, object-oriented, simple, and dynamic database server.
In contrast to typical relational databases, which employ rows and columns, data items are kept as individual documents in a collection. MongoDB is designed in C++ for enormous scalability and flexibility, as well as developer-friendly querying and indexing.
Advantages of Using MongoDB
Below are the advantages of using MongoDB database:
- As values, it accepts arrays and nested objects, allowing for flexible and dynamic schemas.
- It’s simple to create queries that allow for hierarchical sorting and filtering, as well as aggregation, geo-location, time-series, graph search, and more.
- Supports sharding, which divides big datasets into several dispersed collections, making querying easier.
- Multiple storage engines are supported.
- High scalability and flexibility are provided, as well as automated failover and data redundancy.
- Provides a simple-to-learn and-use expressive query language.
- Real-time analytics using ad-hoc queries.
MongoDB 5.0 New Features
The following are the new features offered by MongoDB 5.0:
- There are a variety of cloud security technologies available.
- The map-reduce procedure is being phased out.
- Your applications are future-proofed with the Versioned API.
- MongoDB Atlas is a serverless database.
- Data redistribution that is seamless.
- Allow for the configuration of auditing filters at runtime.
- Resharding in real time.
- Native time-series characteristics for storing sequences of measurements over a period of time in an effective manner.
MongoDB comes in two flavors: Community and Enterprise. The Community Edition is available for free download, but the Enterprise Edition is only available as part of the Mongo Enterprise Advanced subscription. LDAP, Kerberos support, on-disk encryption, and auditing are all included in the Enterprise edition. It also offers full MongoDB development assistance.
How To Install MongoDB 5.0 on Amazon Linux 2
Follow the steps below to install MongoDB 5.0 on Amazon Linux 2.
Step 1 – Update Amazon Linux 2 Server
Let’s upgrade the operating system before we start the installation:
sudo yum -y update
Because kernel upgrades may be required, it is suggested that the system be rebooted following a successful upgrade:
sudo reboot
Step 2 – Add MongoDB 5.0 YUM Repositories
Create a /etc/yum.repos.d/mongodb-org-5.0.repo
file so that you can install MongoDB directly using yum:
sudo tee /etc/yum.repos.d/mongodb-org-5.0.repo<<EOL
[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc
EOL
Confirm the repository is now available:
$ sudo yum repolist
Loaded plugins: dkms-build-requires, langpacks, priorities, update-motd
amzn2-core | 3.7 kB 00:00:00
mongodb-org-5.0 | 2.5 kB 00:00:00
mongodb-org-5.0/primary_db | 31 kB 00:00:00
repo id repo name status
amzn2-core/2/x86_64 Amazon Linux 2 core repository 25,698
amzn2extra-docker/2/x86_64 Amazon Extras repo for docker 46
mongodb-org-5.0 MongoDB Repository 35
repolist: 25,779
Step 3 – Install MongoDB 5.0 on Amazon Linux 2
Run the following command to install the most recent stable version of MongoDB:
sudo yum install mongodb-org
Accept installation prompt to proceed.
Dependencies Resolved
====================================================================================================================================================================
Package Arch Version Repository Size
====================================================================================================================================================================
Installing:
mongodb-org x86_64 5.0.2-1.amzn2 mongodb-org-5.0 6.1 k
Installing for dependencies:
cyrus-sasl x86_64 2.1.26-23.amzn2 amzn2-core 87 k
cyrus-sasl-gssapi x86_64 2.1.26-23.amzn2 amzn2-core 42 k
mongodb-database-tools x86_64 100.5.0-1 mongodb-org-5.0 47 M
mongodb-mongosh x86_64 1.0.5-1.el7 mongodb-org-5.0 42 M
mongodb-org-database x86_64 5.0.2-1.amzn2 mongodb-org-5.0 6.2 k
mongodb-org-database-tools-extra x86_64 5.0.2-1.amzn2 mongodb-org-5.0 11 k
mongodb-org-mongos x86_64 5.0.2-1.amzn2 mongodb-org-5.0 19 M
mongodb-org-server x86_64 5.0.2-1.amzn2 mongodb-org-5.0 27 M
mongodb-org-shell x86_64 5.0.2-1.amzn2 mongodb-org-5.0 15 M
mongodb-org-tools x86_64 5.0.2-1.amzn2 mongodb-org-5.0 6.0 k
Transaction Summary
====================================================================================================================================================================
Install 1 Package (+10 Dependent packages)
Total download size: 151 M
Installed size: 542 M
Is this ok [y/d/N]: y
Also agree to import the GPG key:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Total 71 MB/s | 151 MB 00:00:02
Retrieving key from https://www.mongodb.org/static/pgp/server-5.0.asc
Importing GPG key 0xE2C63C11:
Userid : "MongoDB 5.0 Release Signing Key <[email protected]>"
Fingerprint: f567 9a22 2c64 7c87 527c 2f8c b00a 0bd1 e2c6 3c11
From : https://www.mongodb.org/static/pgp/server-5.0.asc
Is this ok [y/N]: y
To install a specific version of MongoDB, provide each component package individually and attach the version number to the package name, as shown below:
sudo yum install -y mongodb-org-5.0.2 mongodb-org-database-5.0.2 mongodb-org-server-5.0.2 mongodb-org-shell-5.0.2 mongodb-org-mongos-5.0.2 mongodb-org-tools-5.0.2
Now, check the installed MongoDB version:
$ mongod --version
db version v5.0.2
Build Info: {
"version": "5.0.2",
"gitVersion": "6d9ec525e78465dcecadcff99cce953d380fedc8",
"openSSLVersion": "OpenSSL 1.0.2k-fips 26 Jan 2017",
"modules": [],
"allocator": "tcmalloc",
"environment": {
"distmod": "amazon2",
"distarch": "x86_64",
"target_arch": "x86_64"
}
}
Step 4 – Configure MongoDB on Amazon Linux 2
We need to make a few configurations now that MongoDB 5.0 has been properly deployed.
Start and Enable MongoDB Service
To begin, we must first start and enable the mongod service, as seen below:
sudo systemctl start mongod
sudo systemctl enable mongod
Now, check the status of the service:
$ systemctl status mongod
● mongod.service - MongoDB Database Server
Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; vendor preset: disabled)
Active: active (running) since Fri 2021-08-27 16:58:03 UTC; 2min 24s ago
Docs: https://docs.mongodb.org/manual
Main PID: 3939 (mongod)
CGroup: /system.slice/mongod.service
└─3939 /usr/bin/mongod -f /etc/mongod.conf
Aug 27 16:58:01 vagrant systemd[1]: Starting MongoDB Database Server...
Aug 27 16:58:01 vagrant mongod[3936]: about to fork child process, waiting until server is ready for connections.
Aug 27 16:58:01 vagrant mongod[3936]: forked process: 3939
Aug 27 16:58:03 vagrant systemd[1]: Started MongoDB Database Server.
Secure MongoDB instance
The MongoDB 5.0 database has no password and is freely accessible after installation, we must secure it.
Edit mongo.conf
file as shown below:
sudo vim /etc/mongod.conf
Uncomment the #Security line in the conf file and replace it with the text below. In this file, keep in mind that the syntax is extremely essential.
security:
authorization: enabled
Then restart the service for changes to apply:
sudo systemctl restart mongod
Step 5 – MongoDB Enable Remote Access
MongoDB can only be accessed locally by default. If you want to be able to access the database from afar, modify the mongo.conf
configuration file to include the MongoDB server IP address or hostname, as shown below.
# network interfaces
net:
port: 27017
bindIp: 127.0.0.1,mongodb-server-ip/hostname
Restart the mongod service after saving the modifications.
Step 6 – Using MongoDB 5.0 on Amazon Linux 2
By default, MongoDB listens on port 27017. You may use the following command to go to the MongoDB shell from localhost:
$ mongo
Output of the above command:
$ mongo
MongoDB shell version v5.0.2
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("52f71ca4-a534-420b-bc16-0c4d95c476e2") }
MongoDB server version: 5.0.2
================
Warning: the "mongo" shell has been superseded by "mongosh",
which delivers improved usability and compatibility.The "mongo" shell has been deprecated and will be removed in
an upcoming release.
We recommend you begin using "mongosh".
For installation instructions, see
https://docs.mongodb.com/mongodb-shell/install/
================
Welcome to the MongoDB shell.
For interactive help, type "help".
For more comprehensive documentation, see
https://docs.mongodb.com/
Questions? Try the MongoDB Developer Community Forums
https://community.mongodb.com
>
Create a User and Add Role in MongoDB 5.0
Create a user called mongouser, whose name you may modify to whatever you wish. After you’ve inserted the script below, you’ll need to assign a password to the newly created user.
> use admin
db.createUser(
{
user: "mongouser",
pwd: passwordPrompt(), // or cleartext password
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
Here is the sample output of the above code:
Enter password: <type your password here>
Successfully added user: {
"user" : "mongouser",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
},
"readWriteAnyDatabase"
]
}
Now exit the shell as shown below:
> exit
bye
Then login to the created user above:
mongo -u mongouser -p --authenticationDatabase admin
List databases in MongoDB 5.0
Run the following command to list databases in MongoDB 5.0.
> show dbs
admin 0.000GB
config 0.000GB
local 0.000GB
Create a Database in MongoDB 5.0
In MongoDB, a new database is established by simply switching to a non-existing database and giving it a name. Let’s start by making a database called mydb.
> use mydb
switched to db mydb
Create a Collection in MongoDB 5.0
We may now add data to the database we built before. We’re going to make a table for the user information down below:
db.userdetails.insertOne(
{F_Name: "fname",
L_NAME: "lname",
ID_NO: "34567",
AGE: "32",
TEL: "+2676745"
}
)
When we add the above data, we obtain the output below:
{
"acknowledged" : true,
"insertedId" : ObjectId("612927e2028719a727ac64f8")
}
Check the created table or collection above:
> show collections
userdetails
Create a User with Read and Write Privileges
Use the following command to create a user with read and write capabilities in MongoDB:
use testdb
db.createUser(
{
user: 'myuser',
pwd: 'P@ssWord',
roles: [ { role: 'readWrite', db: 'testdatabase' } ]
}
);
Output:
Successfully added user: {
"user" : "myuser",
"roles" : [
{
"role" : "readWrite",
"db" : "testdatabase"
}
]
}
Step 7 – Change MongoDB default Path on Amazon Linux 2
MongoDB keeps its data in the /var/lib/mongo
directory by default. MongoDB may be configured to store data in a specific path, as illustrated below.
Before doing do, you need to to stop mongod.service first:
sudo systemctl stop mongod.service
Then, to store MongoDB data, establish a new custom path:
sudo mkdir -p /data/mongo
Set the ownership of the directory to mongod
as below:
sudo chown -R mongod:mongod /data/mongo
Now, edit /etc/mongod.conf
.
sudo vim /etc/mongod.conf
make the following changes in the file above:
path: /data/log/mongodb/mongod.log #where to write logging data.
dbPath: /data/mongo #Where and how to store data.
pidFilePath: /data/mongodb/mongod.pid # location of pidfile
Step 8 – Configure SELinux for MongoDB on Amazon Linux 2
Now that we have changed the MongoDB path, we need to configure SELinux and its enforcing mode to allow MongoDB to access /sys/fs/cgroup
.
We need to install Checkpolicy before we continue to configure SELinux:
sudo yum -y install checkpolicy
Make a new check policy using the following information.
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
Now, compile and load the policy created above:
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
Now that you’ve created a new check policy, load the three directories as follows:
Log File Directory
To update the file and directory contexts, use the instructions below:
sudo semanage fcontext -a -t mongod_log_t '/data/log/mongodb/mongod.*'
sudo chcon -Rv -u system_u -t mongod_log_t '/data/log/mongodb/mongod.log'
sudo restorecon -R -v '/data/log/mongodb/mongod.log'
PID Directory
Do it as shown below:
sudo semanage fcontext -a -t mongod_var_run_t '/data/mongodb/mongod.*'
sudo chcon -Rv -u system_u -t mongod_var_run_t '/data/mongodb/mongod.pid'
sudo restorecon -R -v '/data/mongodb/mongod.pid'
Data Directory
Update the data directory as shown below:
sudo semanage fcontext -a -t mongod_var_lib_t '/data/mongo.*'
sudo chcon -Rv -u system_u -t mongod_var_lib_t '/data/mongo'
sudo restorecon -R -v '/data/mongo'
Step 9: Update the Firewall
Now update the firewall as shown below:
sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
Reload and start Mongod daemon as shown below:
sudo systemctl daemon-reload
sudo systemctl start mongod.service
If MongoDB fails to load, restart it by typing:
sudo systemctl daemon-reload
sudo systemctl start mongod
Conclusion
We learnt how to install the most recent MongoDB version, MongoDB 5.0, on Amazon Linux 2, as well as how to create users with particular roles and create and utilize databases in MongoDB, in this article. We hope you found this information useful.