HowtoForge

How to Install and Use MongoDB NoSQL Database on Rocky Linux 9

MongoDB is an open-source, cross-platform, and distributed NoSQL (Non-SQL or Non-Relational) database system. Instead of storing data in tables like traditional SQL databases, MongoDB uses flexible documents to store various data forms. MongoDB uses BSON format for storing data, which is binary JSON format.

MongoDB is a distributed NoSQL database with built-in high availability, automatic failover and data redundancy, horizontal scaling via sharding across distributed clusters, and it supports multi-region geographic deployment. MongoDB also provides query API that supports CRUD operations (read and write), data aggregation pipeline, text search, and geospatial queries.

Some notable companies that use MongoDB are Forbes, Toyota, SEGA, EA, Vodafone, Verizon, and many more.

In this tutorial, you will install MongoDB NoSQL Database on Rocky Linux 9 server. You will also learn how to optimize a Linux system for deploying MongoDB Server. At the end of this tutorial, you will also learn the basic queries of the MongoDB Database Server.

By completing this guide, you will have MongoDB installed and learn the basic MongoDB operations, such as managing users, creating databases, inserting and retrieving data from MongoDB, updating data in MongoDB, and how to remove data from the MongoDB server.

Prerequisites

To complete this tutorial, you must have the following requirements in place:

With your Rocky Linux ready, you're now ready to begin.

Adding MongoDB Repository

MongoDB is only available on the official MongoDB repository. To install it, you must add the MongoDB repository to your system. At the time of this writing, the latest version of MongoDB is v6.0, which you'll be using for the rest of this guide.

In the first step, you will add the official MongoDB repository to your Rocky Linux system.

To start, create a new repository file '/etc/yum.repos.d/mongodb-org-6.0.repo' using the below nano editor command.

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

Add the following lines of the MongoDB 6.0 repository to the file.

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

Save the file and exit the editor when finished.

Now run the below dnf command to verify the list of repositories on your Rocky Linux system.

sudo dnf repolist

You'll receive an output like this - The MongoDB 6.0 repository is added to the Rocky Linux system.

With the MongoDB repository added to your system, you'll next start the MongoDB installation.

Installing MongoDB Server and Mongosh

In this step, you'll install the MongoDB server on the Rocky Linux server. Then, you'll start and enable the MongoDB service to be run automatically upon the bootup.

Run the below dnf command to install MongoDB packages. The 'mongodb-org' is the main package of the MongoDB server, and the 'mongodb-mongosh' is the new version of the MongoDB client, an alternative to the client 'mongo'.

sudo dnf install mongodb-org mongodb-mongosh

When prompted, input y to confirm and press ENTER to proceed.

Also, you'll be prompted to accept the GPG key of MongoDB. Input y and press ENTER to confirm.

After the MongoDB server installed, run the below systemctl command utility to start the MongoDB service and verify the service to ensure it's running.

sudo systemctl start mongod
sudo systemctl status mongod

You should receive an output like the below screenshot - The MongoDB service is running and it's enabled. The MongoDB service will be run automatically upon the bootup.

Now that the MongoDB server is running, you'll set up and optimize your Rocky Linux system for the MongoDB deployment in the next step.

Setting up System

In this step, you'll set up your Rocky Linux server and optimize it for the MongoDB deployment. This includes disabling Transparent Huge Pages (THP), increasing the ulimit, and increasing max virtual memory via sysctl.conf file.

You can use different methods to disable Transparent Huge Pages (THP). In this guide, you'll disable THP permanently via the systemd service.

Create a new systemd service file '/etc/systemd/system/disable-thp.service' using the below nano editor command.

sudo nano /etc/systemd/system/disable-thp.service

Add the following lines to the file.

[Unit]
Description=Disable Transparent Huge Pages (THP)

[Service]
Type=simple
ExecStart=/bin/sh -c "echo 'never' > /sys/kernel/mm/transparent_hugepage/enabled && echo 'never' > /sys/kernel/mm/transparent_hugepage/defrag"

[Install]
WantedBy=multi-user.target

Save the file and exit the editor.

Next, run the below systemctl command utility to reload the systemd manager and apply a new service file.

sudo systemctl daemon-reload

After that, start and enable the systemd service 'disable-thp' using the below systemctl command.

sudo systemctl enable disable-thp
sudo systemctl start disable-thp

With the 'disable-thp' service enabled, the Transparent Huge Pages (THP) will automatically be disabled on every boot up.

Next, you'll increase the ulimit on your system for the MongoDB deployment. The default ulimit for a generic Linux system is '1024', and MongoDB required at least '64000'.

To change the ulimit, create a new config file '/etc/security/limits.d/mongodb.conf' using the below nano editor command.

sudo nano /etc/security/limits.d/mongodb.conf

Add the following lines to the file. With these lines, you'll set up ulimit for the specific user 'mongod', which is the default user that runs the MongoDB server.

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

Save the file and exit the editor when finished.

After configuring ulimit, you'll now increase the max virtual memory on your MongoDB server via the '/etc/sysctl.conf' file.

Open the config file '/etc/sysctl.conf' using the below nano editor command.

sudo nano /etc/sysctl.conf

Add the following lines to the file.

fs.file-max = 2097152
vm.max_map_count = 262144
vm.swappiness = 1

Save the file and exit the editor.

Lastly, run the below command to reboot your Rocky Linux system and apply the system changes that you have mode.

sudo reboot

With this, your MongoDB server should now be running with THP disabled, ulimit '64000' for MongoDB users, and the max virtual memory '262144'. In the next step, you'll set up the MongoDB admin user, then learn the basics of MongoDB operations.

Setting up Admin for MongoDB

At this point, you've now running MongoDB on the optimized Rocky Linux server. And in this step, you'll secure your MongoDB deployment by creating a new admin user and enabling the authentication and authorization on the MongoDB server.

First, log in to the MongoDB server via the 'mongosh' command below.

mongosh

Now run the below query to disable the MongoDB monitoring, which is enabled on the default MongoDB installation.

db.disableFreeMonitoring()

Next, switch to the default database 'admin' using the below query.

use admin

Now create a new MongoDB admin user using the following MongoDB query. Also, be sure to change the username in the below query.

This example will create a new admin user 'myAliceAdmin'. With the query 'passwordPrompt()', you'll set up the password via prompt, instead of using the plain text inside the query.

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

When the new user is created, you'll receive an output such as '{ ok: 1 }'.

Now press Ctrl+d or type 'quit' to exit from the MongoDB shell.

Next, open the MongoDB config file '/etc/mongod.conf' using the below nano editor command.

sudo nano /etc/mongod.conf

Uncomment the 'security' parameter and add the line 'authorization: enabled' to enable MongoDB authentication and authorization.

security:
    authorization: enabled

Save the file and exit the editor when finished.

Lastly, run the below systemctl command to restart the MongoDB service and apply the changes.

sudo systemctl restart mongod

Now that the MongoDB admin user is created and the authorization and authentication are enabled on the MongoDB server. You'll next verify the user authentication with two different methods.

Log in to the MongoDB shell via the 'mongosh' command below.

mongosh

After logging in, run the below query to authenticate as the MongoDB admin user 'myAliceAdmin'. When prompted for the password, input your MongoDB admin password.

use admin
db.auth("myAliceAdmin", passwordPrompt())

When the authentication is successful, you should receive an output such as '{ ok: 1 }'.

Another method to log in to the MongoDB shell and authenticate with the single mongosh command below. Input your password when prompted.

With this command, you'll connect to the MongoDB server that runs on port 27017, and authenticate to the database 'admin' with the username 'myAliceAdmin'.

mongosh --port 27017 --authenticationDatabase \
    "admin" -u "myAliceAdmin" -p

You should be logged in to the MongoDB shell when the authentication is successful.

Your MongoDB server is now secured with user and password authentication. Also, you've created an administrator user on MongoDB. Next, you'll learn how to create a new MongoDB user that can be used for your applications.

Creating User and Database on MongoDB

In this step, you'll create a new MongoDB user that can be used for your applications. In addition to that, you'll also verify the list of users on the MongoDB server, then log in to the MongoDB shell with your MongoDB new user.

Before you start, ensure that you've logged in to the MongoDB shell. Then, run the below command to switch to the new database 'testdb' and create a new MongoDB user.

In this example, you'll create a new MongoDB user 'myTestUser' with the role 'readWrite' to the database 'testdb' and the role 'read'-only to the database 'reporting'.

use tesdb
db.createUser(
  {
    user: "myTestUser",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "testdb" },
             { role: "read", db: "reporting" } ]
  }
)

When prompted, input the new password for the new user 'myTestUser'. And you should receive an output '{ ok: 1 }', which means the new user 'myTestUser' is created.

Next, switch to the database 'admin' and run the below query to verify the list of users on your MongoDB server.

use admin
db.system.users.find()

You'll see an output similar to this - The new user 'myTestUser' is created with the role 'readWrite' to the database 'testdb' and the role 'read' to the database reporting.

Now press Ctrl+d to quit and exit from the MongoDB shell.

To ensure that the MongoDB user 'myTestUser' is created, you'll now log in to the MongoDB via the 'myTestUser'.

Run the below command to log in to the MongoDB via the user 'myTestUser'. When prompted for the password, input your password.

mongosh --port 27017 -u "myTestUser" \
    --authenticationDatabase "testdb" -p

After logging in, run the below MongoDB query to verify your current connection.

db.runCommand({connectionStatus : 1})

You'll see an output similar to this screenshot - You've now connected and authenticated to the MongoDB server via the user 'myTestUser'.

Now that you've created a new MongoDB user, you'll next learn how to insert and retrieve data in MongoDB.

Inserting and Querying Data in MongoDB

After creating a new MongoDB user, you'll now learn how to create the database,  insert data, and retrieve data from MongoDB. You'll learn how to use the 'insertOne' query and 'insertMany' query to add data to MongoDB and use query operators such as '$in' and '$gte' with the 'find' query to reteive data from MongoDB.

First, ensure that you've logged in to the MongoDB server with your new user, this example is 'myTestUser'. Then switch to the database 'testdb' via the 'use' query below.

use testdb

Now your MongoDB shell will become likes 'testdb>'.

Next, run the below query to create a new collection and insert new data into it. In this example, you'll create a new collection 'movies' and insert new data via the 'insertOne' query, which can be used to insert only one data to a collection.

db.movies.insertOne(
  {
    title: "The Hobbit",
    genres: [ "Adventure", "Fantasy" ],
    runtime: 172,
    rated: "R",
    year: 2012,
    directors: [ "Peter Jackson" ],
    cast: [ "Martin Freeman", "Ian McKellen", "Richard Armitage" ],
    type: "movie"
  }
)

You'll now receive an output such as 'acknowledged: ok', which means the new data added and the new collection is created.

Now run the below query to verify the list of collections on the database 'testdb' and show available data within the 'testdb'.

The 'show collection' query will show you the lists of collections/tables on the current database, and the 'find' query will show available data on your database. You can also filter specific fields via the 'find' query.

show collections
db.movies.find( {} )

You should receive an output like this - The collection 'movies' is available in the 'testdb' database. Also, you'll the new data that you've added, which is

Next, you can also add multiple data at once via the 'insertMany' query. Run the below query to insert two data to the 'movies' collection via the 'insertMany' query.

db.movies.insertMany([
   {
      title: "The Lord of the Rings",
      genres: [ "Action", "Adventure", "Drama" ],
      runtime: 240,
      rated: "PG-13",
      year: 2001,
      directors: [ "Peter Jackson" ],
      cast: [ "Elijah Wood", "Ian McKellen", "Orlando Bloom" ],
      type: "movie"
    },
    {
      title: "Harry Potter",
      genres: [ "Adventure", "Family", "Fantasy" ],
      runtime: 140,
      rated: "R",
      year: 2007,
      directors: [ "David Yates" ],
      cast: [ "Daniel Radcliffe", "Emma Watson", "Rupert Grint" ],
      type: "movie"
    }
])

Output:

Now run the below 'find' query to retrieve your data. With this, you'll retrieve data with the filter 'directors: "Peter Jackson"'.

db.movies.find( { directors: "Peter Jackson" })

You'll receive an output like this - Any movies with 'directors: "Peter Jackson"' will be shown on your terminal.

Next, you can also specify conditions in the 'find' query using query operators.

Run the below query to retrieve any data where the 'genres' is 'Action' and/or 'Family'. The '$in' operator can be used to retrieve data that matches any of the values specified in an array.

db.movies.find( { genres: { $in: [ "Action", "Family" ] } } )

You should now receive an output like this:

Another query operator that you can try is '$gte', which can be used to retrieve data that are greater than or equal to a specified value.

Before that, run the below query to insert new data into the 'movies' collection.

db.movies.insertOne(
  {
    title: "Transformers",
    genres: [ "Adventure", "Action", "Sci-Fi" ],
    runtime: 150,
    rated: "PG-13",
    year: 2007,
    directors: [ "Michael Bay" ],
    cast: [ "Shia LaBeouf", "Megan Fox", "Josh Duhamel" ],
    type: "movie"
  }
)

Now run the below query to retrieve data with the '$gte' query operator. This will retrieve any movies with 'genres: "Action"' that was released after or equal 'to 2001'.

db.movies.find( { genres: "Action", "year": { $gte: 2001 } } )

You will receive an output similar to this - In this example, you'll get two movies released after or equal to 2001 with the genres 'Action', which are 'The Lord of the Rings' and 'Transformers'.

With this in mind, you've now learned how to insert and retrieve data in MongoDB. You've learned the basic query 'insertOne' for adding one data and the 'insertMany' query for adding some data at once.

Then, you've also learned the basic usage of the 'find' query to retrieve data from MongoDB. In addition to that, you've also learned how to use operator queries '$in' and '$gte' in MongoDB.

In the next step, you'll learn how to update data in MongoDB collections.

Updating Data in MongoDB

In this step, you'll learn how to update data in MongoDB using two queries, the 'updateOne' for updating one field inside the document and using the 'replaceOne' to replace entirely first matched data with new data.

To update data in MongoDB, you can use multiple methods and queries. In this example, you'll learn how to use the 'updateOne' and 'replaceOne' queries. The 'updateOne' query can be used to update a single field in the document, while the 'replaceOne' will replace the entire document.

Run the below query to update data using the 'updateOne' query. In this example, you'll update the 'rated: "PG-13"' to 'rated: "R"' on the movie 'Transformers'.

db.movies.updateOne( { title: "Transformers" },
{
  $set: {
    rated: "R"
  }
})

You should receive an output such as 'matchedCount: 1' and 'modifiedCount: 1'.

Now verify the new data with the following query. You should see the data on the 'Transformers' movie is updated.

db.movies.find( { title: "Transformers" })    

Next, run the below 'replaceOne' query to replace the first matched data in the filter and replace the entire document with the new data. In this example, you'll replace the whole document on the movie 'Transformers' with the new data.

db.movies.replaceOne(
  { title: "Transformers" },
  {
    title: "Transformers: Dark of the Moon",
    genres: [ "Adventure", "Action", "Sci-Fi" ],
    runtime: 160,
    rated: "PG-13",
    year: 2011,
    directors: [ "Michael Bay" ],
    cast: [ "Shia LaBeouf", "Rosie Huntington-Whiteley", "Tyrese Gibson" ],
    type: "movie"
  }
)

You should now get an output like this.

Now run the below query to verify the newly updated data on your MongoDB.

db.movies.find( { title: "Transformers" })
db.movies.find( { title: "Transformers: Dark of the Moon" })  

You should receive an output similar to this - The movie 'Transformers' is removed/replaced with the new movie 'Transformers: Dark of the Moon'.

Delete Data in MongoDB

In this step, you will learn how to delete data in a MongoDB document. Then, you'll learn how to delete the database and delete the user in MongoDB.

Run the below command to delete data from the MongoDB collection. In this example, you'll delete the whole document 'Transformers: Dark of the Moon' via the 'deleteMany' query.

db.movies.deleteMany( { title: "Transformers: Dark of the Moon" } )
db.movies.find( { title: "Transformers: Dark of the Moon" })

You should receive an output such as 'deletedCount: 1'.

Next, run the below command to delete a single document via the 'deleteOne' query below. This will delete the first matched data within the filter.

In this example, you'll delete the first document that matched with 'cast: "Ian McKellen"'.

db.movies.deleteOne( { cast: "Ian McKellen" } )
db.movies.find( { cast: "Ian McKellen" })

Below is the output before and after the data is deleted.

Before the remove - You should see two movies with the 'cast: "Ian McKellen"'.

After the document is removed - you should see only one movie with 'cast: "Ian McKellen"'.

Next, you'll learn how to delete users and databases in MongoDB. To delete a user in MongoDB, you must have the role 'root' on your MongoDB admin user.

Run the below command to authenticate as MongoDB admin user 'myAliceAdmin' and input your password.

use admin
db.auth("myAliceAdmin", passwordPrompt())

After being authenticated as MongoDB admin, run the below query to give the admin user the 'root' roles.

db.grantRolesToUser("myAliceAdmin", ["root"]);

Now switch to the 'testdb' and delete users within the database 'testdb' via the below query. This will delete the user 'myTestUser' from MongoDB.

use testdb
db.runCommand( { dropAllUsersFromDatabase: 1 } )

You should get an output such as '{ n:1, ok: 1 }'.

Next, run the below query to delete/remove the database 'testdb'.

db.dropDatabase()

And you should get an output such as '{ ok: 1, dropped: 'testdb' }'.

Now that the 'testdb' and users within the database are removed.

Run the below query to switch to the database 'admin' and verify the list of databases on your MongoDB server. You should see that the 'testdb' database is removed.

use admin
show dbs

Lastly, run the below query to show and list users on MongoDB.

db.system.users.find()

You should receive an output like this - The use 'myTestUser' is removed/deleted from the MongoDB server.

Conclusion

In this guide, you've installed the latest version of MongoDB Server (Community Edition) on a Rocky Linux 9 server. You've also learned how to enable authentication and authorization on the MongoDB server and how to optimize the Linux server for the MongoDB deployment.

Along the way, you've learned the basic usage of the Mongosh command for connecting and managing the MongoDB server. And learned the basic MongoDB queries for creating users, creating databases, inserting and retrieving data, updating data, and deleting/removing data from the MongoDB server.

With this, you can learn more about MongoDB queries in MongoDB Documentation. Also, if you're interested to deploy MongoDB in a large deployment, you can try to enable sharding that allows you to set up horizontal scaling in the MongoDB cluster.

How to Install and Use MongoDB NoSQL Database on Rocky Linux 9