How to Install MongoDB on Rocky Linux

MongoDB is a distributed NoSQL database system with built-in support for high availability, horizontal scaling, and geographical distribution. It is the most popular document-oriented database program that uses JSON-like documents to store data. Unlike tablelike relational databases, MongoDB provides different mechanisms for storing and retrieving data.

MongoDB is a high-performance No-SQL database system that works on all types of computing technology, both on-premises and cloud (public and private). It's widely used in different types of industries, from high-profile news sites like Forbes to software and technology companies such as Google, Cisco, Adobe, etc.

This tutorial will teach you how to install MongoDB on Rocky Linux. You will install the latest stable version from the official MongoDB repository. Also, you will learn how to secure the deployment by enabling MongoDB authentication and learn the basic CRUD (Create, Read, Update, and Delete) on MongoDB.

Prerequisites

  • A Rocky Linux system.
  • A user with root or sudo privileges. This user will be used for installing new packages and making changes system-wide.

Adding MongoDB Repository

In the first stage, you will be adding the MongoDB repository for the RHEL-based operating system, in this case, a Rocky Linux system.

1. Execute the following nano command to create new repository file '/etc/repos.d/mongodb-org-5.0.repo'.

sudo nano /etc/yum.repos.d/mongodb-org-5.0.repo

Please copy and paste the following configuration into it.

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

Press the 'Ctrl+x' button, type 'y', then press 'Enter' to save and exit.

2. Now verify all available repositories on the Rocky Linux system using the DNF command below.

sudo dnf repolist

Below is the similar output you will get.

Add mongodb repository

As the screenshot shows, the MongoDB repository is available on the Rocky Linux system, and you're ready to install MongoDB packages.

Installing MongoDB on Rocky Linux

1. To install MongoDB on Rocky Linux, execute the DNF command below.

sudo dnf install mongodb-org

Type 'y' and press 'Enter' to confirm the installation.

Installing MongoDB on Rocky Linux

Also, you will be asked to add the GPG key of MongoDB, type 'y', and press 'Enter' to add and confirm.

Add MongoDB GPG key

2. If MongoDB installation is completed, enable the MongoDB service using the command below.

sudo systemctl enable mongod
sudo systemctl is-enabled mongod

3. After that, execute the command below to start the MongoDB service and check the service status.

sudo systemctl start mongod
sudo systemctl status mongod

You will get a similar output to the screenshot below.

Check MongoDB service status

The MongoDB service is 'active (running)' with the default configuration. Also, the MongoDB service is 'enabled', which means it will automatically run at system boot.

Connect to MongoDB with MongoDB Shell

MongoDB provides a command-line tool for managing the MongoDB deployment. It's called 'mongosh' or MongoDB Shell. It's supported for MongoDB 4.0 or greater, available on multiple operating systems, and automatically installed on your deployment.

1. To connect to your MongoDB server, run the 'mongosh' command as below.

mongosh

The default command will automatically connect to the local MongoDB deployment.

2. If you want to connect to the MongoDB server with the custom IP address or hostname and the custom MongoDB port, execute the 'mongosh' command as below.

mongosh "mongodb://localhost:27017"

3. After connecting to the MongoDB shell, execute the following query to disable the MongoDB telemetry.

disableTelemetry()

Now type 'exit' to log out from the mongosh shell.

Log in to MongoDB using mongosh

Create Admin and Enable Authentication

At this stage, you will create a new admin user for MongoDB and secure the MongoDB deployment by enabling its authentication through the configuration '/etc/mongod.conf'.

1. Connect to your MongoDB server using the 'mongosh' command below.

mongosh

2. Switch to the database 'admin' using the query 'use' as below.

use admin

3. After that, execute the MongoDB query below to create a new user 'superadminuser' with the password 'superadminpass' and the role multiple roles.

db.createUser(
   {
     user: "superadminuser",
     pwd: "superadminpass",
     roles: ["userAdminAnyDatabase", "dbAdminAnyDatabase", "readWriteAnyDatabase"]
   }
 )

After that, grant the user 'superadminuser'  to a role 'root' using the following query.

db.grantRolesToUser('superadminuser',[{ role: "root", db: "admin" }])

You will see the output like '{ ok: 1 }', which means the query is successful and the new user 'superadminuser' is created.

Create admin user MongoDB

4. Verify the MongoDB 'admin' user using the following query.

db.getUsers()

And you will get the new user 'superadminuser' with the database 'admin' and multiple roles. Also, with the default authentication mechanism 'SCRAM-SHA-1' and 'SCRAM-SHA-256'.

Verify Admin user MongoDB

Now type 'exit' and press 'Enter' to log out from the mongosh shell.

5. Next, to enable the MongoDB authentication, edit the configuration '/etc/mongod.conf' using the nano command below.

sudo nano /etc/mongod.conf

Uncomment the option 'security' and add the configuration as below.

security:
  authorization: enabled

Save the configuration by pressing the 'Ctrl+x' button, type 'y', then press 'Enter' to exit.

6. To apply the changes that you've made, execute the following command to restart the MongoDB service.

sudo systemctl restart mongod

The new MongoDB configuration has been applied. Check the MongoDB service status using the following command.

sudo systemctl status mongod

Now, you will see the MongoDB service is active (running) with the authentication enabled.

Enable MongoDB Authentication

Verifying MongoDB Authentication

For this stage, you will verify the MongoDB authentication to authenticate to the server.

1. Execute the mongosh command below to log in to the MongoDB server.

mongosh

2. Now switch to database admin using the following query.

use admin

3. Then, execute the following query to authenticate to the MongoDB server.

db.auth("superadminuser", "superadminpass")

4. Or you can use the JSON-like format as below.

db.auth( {
   user: "superadminuser",
   pwd: "superadminpass",
   mechanism: "SCRAM-SHA-256"
} )

And you will see the output '{ ok: 1 }', which means the authentication is successful.

Authenticate MongoDB Server

4. To verify that you're authenticated, run the following query.

db.getUsers()
show users;

If you're authenticated to the MongoDB server, you will see the details of the admin user you're using for authenticating.

Verify MongoDB Users

5. Optionally, you can use the mongosh command to authenticate directly to the MongoDB server using the command as below.

mongosh --username "superadminuser" --password

Type the password for the user 'superadminuser' and press 'Enter'.

If your authentication is successful, you will get the mongosh shell interface. Otherwise, you will get an error 'Authentication failed' as shown in the screenshot below.

Authenticate to MongoDB using mongosh command

Create User and Database on MongoDB

For this stage, you will learn how to create a new database and user on MongoDB.

1. Before creating a new database and user, log in to MongoDB using the mongosh command below.

mongosh

Now switch to the database 'admin' and authenticate yourself as the user 'superadminuser' using the following query.

use admin
db.auth( {
user: "superadminuser",
pwd: "superadminpass",
mechanism: "SCRAM-SHA-256"
} )

Make sure you get the output as '{ ok: 1 }', which means the authentication is successful.

2. Next, to create a new database on MongoDB, you can use the query 'use dbname' as below.

use demodb

For this example, you've created a new database 'demodb'.

3. Now execute the following query to create a new user 'DemoUser' and grant the role 'readWrite' to the database 'demodb' and the role 'read' to the database 'school'.

db.createUser(
  {
    user: "DemoUser",
    pwd:  "passworddbuser",
    roles: [ { role: "readWrite", db: "demodb" },
             { role: "read", db: "school" } ]
  }
)

After that, check the user using the following query.

show users;

And you will get the details of the 'DemoUser' you just created.

Create database and user MongoDB

Basic CRUD Operations

After creating the new user and database, you will learn the basic CRUD (Create, Read, Update, and Delete) operations on MongoDB.

1. First, log in to the MongoDB shell and authenticated as the 'DemoUser' to the database 'demodb' using the following queries.

Login to MongoDB shell.

mongosh

Switch to the database 'demodb' and authenticate as 'DemoUser'.

use demodb
db.auth( {
user: "DemoUser",
pwd: "passworddbuser",
mechanism: "SCRAM-SHA-256"
} )

Pict14

Insert Document to MongoDB

1. Next, insert new data to the database 'demodb' using the query 'db.insertOne()' as below.

db.demodb.insertOne(
{
   name: "Paul",
   age: 32,
   address: "California",
   salary: 20000.00
})

Now, you will see a similar output as below.

Insert Data to MongoDB

2. Another query that you should know is 'db.insertMany()', which allows you to insert multiple documents at once using the array format.

Insert multiple data to the MongoDB using the following query.

db.demodb.insertMany(
[
   { name: "Jesse", age: 32, address: "Mexico", salary: 30000.00 },
   { name: "Linda", age: 25, address: "Canada", salary: 40000.00 },
   { name: "Nana", age: 27, address: "California", salary: 35000.00 }
]
)

You will get a similar output as below.

insert multiple documents on MongoDB

As seen on the screenshot, multiple data records have been added to the database 'demodb'.

Query Document on MongoDB

To show all available data on MongoDB, use the 'db.find()' query as below.

1. Show all data inside the database 'demodb' using the following query.

db.demodb.find()

Below is the similar output you will get.

Query Document on MongoDB

2. To show specific data on MongoDB, use the 'db.find()' query followed by the filter as below.

db.demodb.find(
{
   address: "California"
}
)

And you will get all data with the collection 'address: "California"' as below.

Show specific document

Update Documents on MongoDB

1. To update the document on MongoDB, you can use the query 'db.updateOne()' followed by the filter and the column you want to change as below.

db.demodb.updateOne(
   { "name": "Jesse" },
   { $set: { "address": "Canada" } }
)

And you will see a similar output as below.

Update documents MongoDB

As can be seen on the screenshot, the 'matchedCount: 1' means the query matches for N number of data, and the 'modifiedCount: 1' means the data has been changed.

2. verify the new data using the following query.

db.demodb.find(
{
   name: "Jesse"
}
)

And you will see the changed document to 'address: Canada'.

Delete Data on MongoDB

To delete a document with a specific match on MongoDB, you can use the query 'db.deleteOne()'.

1. Delete all data matched with the filter 'name: "Nana"' using the query below.

db.demodb.deleteOne( { "name" : "Nana" } )

Now you will see the output as 'deletedCount: 1', which means the matched data is only 1 and it's deleted.

Delete Document MongoDB

2. Next, delete multiple documents using the query 'db.deleteMany()' as below.

db.demodb.deleteMany(
{
   "address": "Canada",
}
)

Now you will see the output 'deletedCount: 2', which means 2 documents are deleted.

Delete multiple documents MongoDB

3. You can verify if the document is deleted or not using the 'db.find()' query as below.

db.demodb.find ( { address: "Canada" } )
db.demodb.find ( { name: "Nana" } )

And you will see the blank output, which means the document is unavailable.

Conclusion

Congratulations! You've successfully installed MongoDB with the authentication enabled and the admin user created on the Rocky Linux server. Also, you've learned the basic CRUD (Create, Read, Update, and Delete) operations-related documents or databases on MongoDB. For the next step, you can discover more about the MongoDB query in the official documentation.