Winter Sale - up to 36% OFF

How to Install MongoDB on Ubuntu 24.04: Step-by-Step Guide

How to Install MongoDB on Ubuntu 24.04: Step-by-Step Guide
Published on Jan 10, 2025 Updated on Jan 10, 2025

#Introduction

MongoDB is one of today's most prolific NoSQL databases and is flexible and scalable. It lets you store and fetch huge data sets most efficiently and is a perfect fit for apps that require big data, real-time analytics, and IoT solutions. Although there’s nothing too tricky about installing MongoDB on Ubuntu 24.04, you should take some essential steps to make the process go as smoothly as possible. This guide will walk you through every installation step and provide brief configuration notes to set up MongoDB for the stage, whether production or development.

Before we move to installing MongoDB, let’s understand what MongoDB is.

#What is MongoDB?

The popular MongoDB is a NoSQL database that can store large amounts of unstructured data. JSON-like documents in MongoDB differ from relational databases, allowing you to store data faster and dynamically. Both are well suited for modern web, mobile, and IoT applications that require scalability and real-time processing.

Since MongoDB is document-based, handling complex data with nested fields that reside in documents is easy. It is a horizontally scalable and cloud-friendly database. For developers and data engineers, the combined power of querying and indexing makes it a go-to choice for efficiently developing programs.

#Prerequisites

Before getting started, make sure that you have the following prerequisites ready:

  • An instance of Ubuntu 24.04 installed and running
  • A user account with sudo privileges
  • MongoDB performs best with at least 2GB of RAM and a moderate amount of disk space, especially for production environments.

Deploy and scale your projects with Cherry Servers' cost-effective dedicated or virtual servers. Enjoy seamless scaling, pay-as-you-go pricing, and 24/7 expert support—all within a hassle-free cloud environment.

#How to install MongoDB on Ubuntu 24.04

Let’s start by updating and upgrading the Ubuntu packages.

#Step 1: Update the system

Start by updating the package lists and upgrading the system packages to ensure everything is current. To update the package lists, run the command:

sudo apt update

Update the system

Upgrading the system ensures you start off with the latest software versions. This is recommended before installing any new software packages. To upgrade the system, run the command:

sudo apt upgrade

Upgrade the system

#Step 2: Add MongoDB repository

Before installing the MongoDB package, it’s recommended to install the GnuPG and cURL utilities. These are prerequisite packages that will be needed in subsequent steps. To install them, run the command:

sudo apt install -y gnupg curl

Install gnupg and curl

Next, use the cURL utility to import the MongoDB public GPG key, which is essential for verifying the authenticity of the MongoDB packages.

curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor

Note that the URL varies depending on the MongoDB packages. This tutorial will install MongoDB 8.0, the current stable release.

This step ensures you install the official MongoDB packages from MongoDB's official repository to avoid potential security risks.

Next, add the MongoDB repository to the list of sources on your system. To do so, run the following command:

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list

Add mongodb repository

The line adds the MongoDB 8.0 repository to the system.

#Step 3: Install MongoDB

Now that the repository has been added, update the package lists to notify the system of the newly added MongoDB repository.

sudo apt update

Update the system with mongodb packages

Next, install MongoDB using the command below:

sudo apt install -y mongodb-org

Install mongodb

This command installs the latest version of MongoDB along with its dependencies. The -y flag automatically agrees to the installation prompts, speeding up the process.

#Step 4: Start and enable MongoDB

After installation, start the MongoDB service using systemctl and enable it to start automatically at boot time:

sudo systemctl start mongod
sudo systemctl enable mongod

Start and enable mongodb

The systemctl start mongod command initiates MongoDB, and systemctl enable mongod ensures it starts automatically whenever the system reboots.

To check the MongoDB status, run the command:

sudo systemctl status mongod

Check mongodb status

You should see MongoDB active and running. If you encounter any issues, reviewing the service status can offer insight into potential errors.

#Step 5: Verify MongoDB installation

Once MongoDB is installed and running, verify the installation by connecting to MongoDB’s shell. You can do this by typing:

mongosh

Open mongodb shell

From the MongoDB shell, check the connection status by running:

db.runCommand({ connectionStatus: 1 })

Check mongodb connection

This command returns connection information if MongoDB is functioning correctly, allowing you to confirm the installation was successful.

To exit the shell, run the command:

exit

To check the MongoDB version on the shell, run the command:

mongod --version

Check mongodb version

#Step 6: Create MongoDB admin user

By default, MongoDB does not require authentication, and this presents a potential risk to the data, especially in production environments. It’s, therefore, crucial to enable authentication. To achieve this, you need to create an admin user.

So, connect to the MongoDB shell:

mongosh

Next, switch to the admin database.

use admin

Create an admin user with the following command, where user is the admin user's name and pwd is the password.

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

Create mongodb admin user

Then exit the Mongo shell.

exit

#Step 7: Securing MongoDB

Now, enable authentication in the MongoDB configuration file. To achieve this, use your preferred text editor. In this case, I’m using gedit.

sudo gedit /etc/mongod.conf

Under the security section, add the following line:

security:
  authorization: "enabled"

Enable authentication in mongodb

After saving the file, restart MongoDB.

sudo systemctl restart mongod

Restart mongodb

With authentication enabled, you must provide a username and password to access the MongoDB shell. The command is:

mongosh -u newadmin -p --authenticationDatabase admin

Here, newadmin is the admin username.

Login with new admin user

#Allowing Remote access to MongoDB

To connect to your MongoDB server from a remote location, you need to allow incoming connections to port 27017, the default port that the MongoDB database listens on. You can do this by adding a new UFW rule.

You can verify the port your MongoDB installation listens on by running:

sudo lsof -i | grep mongo

 Mongodb port check

Run the following command to allow inbound traffic from a trusted remote system you want to use to access your MongoDB instance. Here, 192.168.49.1 is the IP address of the remote server.

sudo ufw allow from 192.168.50.0 to any port 27017

Use ufw to verify the change in firewall settings.

sudo ufw status

Change firewall settings

Next, bind MongoDB to the server’s public IP address so you can access it remotely. Open and edit the MongoDB configuration:

sudo gedit /etc/mongod.conf

Append a comma to the bindIp line followed by your MongoDB server’s public IP address:

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1, mongodb_server_ip

Then, to put this change into effect, restart MongoDB.

sudo systemctl restart mongod

Make sure your trusted computer can now connect to the MongoDB instance. Start by logging into your trusted server with SSH:

ssh user@trusted-server-ip

Run the following nc command from your trusted remote server:

nc -zv 192.168.49.1 27017

Check remote connection

The output will indicate that the connection was successful if the trusted server can access the MongoDB daemon. With that, it’s confirmed that your MongoDB server can accept connections from the trusted server.

Now, you have successfully installed and configured MongoDB!

Let’s execute a few basic commands of MongoDB.

#Basic MongoDB commands

Here’s a list of basic MongoDB commands to get you started:

#1. Show databases

To list all the available databases, run the following query. By default, MongoDB contains three databases: admin, config, and local.

show dbs

Show databases in mongodb

#2. Switch database

To switch to a specified database, run the use database query where database is the name of the database. For example, to switch to the admin` database, run:

use admin

Switch database in mongodb

#3. Show Collections

To list all collections (tables) within the selected database, run the command

show collections

Show collections in mongodb

#4. Create collection

To create the new collection, execute the following command. In this example, we are creating a collection called Employee.

db.createCollection("Employee")

Create collection in mongodb

#5. Insert document into collection

To add a single document or record to a collection, run the db.collection_name.insertOne( ) query and define the document or record in key-value pairs In this example, we are adding the employee’s name and age to the Employee collection.

db.Employee.insertOne({ name: "John", age: 30 })

Insert document in mongodb

#6. Insert multiple documents

To insert multiple records or documents into a collection, run the db.collection_name.insertMany( ) query and provide the records, each enclosed in curly braces. In this example, we have added two employee names: Megan and Robin.

db.Employee.insertMany([{ name: "Megan" }, { name: "Robin" }])

Insert multiple documents in mongodb

#7. Find documents

To retrieve documents that match the query, use the db.collection_name.find( ) query. In this example, we are searching for an employee record whose age is set to 30.

db.Employee.find({ age: 30 })

Find documents in mongodb

#8. Update document

To update a document, use the db.collection_name.updateOne( ) query. In this example, we are updating the age of the employee called John from 30 to 31.

db.Employee.updateOne(
  { name: "John" }, 
  { $set: { age: 31 } }
)

Update documents in mongodb

#9. Delete document

To delete a single document that matches a condition, run the db.collection_name.deleteOne( ) query. In this example, the query deletes a record whose employee name is John.

db.Employee.deleteOne({ name: "John" })

Delete document in mongodb

#10. Count documents

To count all the records or documents in a collection, run the d⁣b.collection_name.countDocuments( ) query. The query returns the sum of all the documents in a collection.

db.Employee.countDocuments()

Count documents in mongodb

#11. Drop collection

To delete an entire collection and all its documents run:

db.Employee.drop()

Drop collection in mongodb

These commands are great starting points for basic CRUD (Create, Read, Update, Delete) operations in MongoDB.

#Conclusion

Congratulations! You have installed MongoDB on Ubuntu 24.04. This guide covered everything from the initial setup to security configuration and running in production. Your data is now ready to reside and be managed by MongoDB, which, by design, will scale as your data swells.

You have installed your new MongoDB. You are ready to learn about databases, collections, and documents or use feature mechanisms like indexing and aggregation. For development and production purposes, this general-purpose robust and scalable database is now within your grasp to quickly build data-rich applications.

Cloud VPS - Cheaper Each Month

Start with $9.99 and pay $0.5 less until your price reaches $6 / month.

Share this article

Related Articles

Published on Jun 7, 2021 Updated on Jun 29, 2022

AlmaLinux Review: a CentOS Clone Supported by CloudLinux

AlmaLinux is an open-source Linux distribution focused on long-term stability, that is a 1:1 binary compatible fork of Red Hat Enterprise Linux (RHEL)

Read More
Published on Sep 14, 2021 Updated on Jun 29, 2022

Debian 11 "bullseye" Review: What‘s New?

Debian 11 “bullseye” was released on 14th of August 2021. This release contains over 11294 new packages out of 59551 packages overall in its repositories.

Read More
Published on May 31, 2022 Updated on May 5, 2023

A Complete Guide to Linux Bash History

Learn how to work with Bash history to become more efficient with any modern *nix operating system.

Read More
We use cookies to ensure seamless user experience for our website. Required cookies - technical, functional and analytical - are set automatically. Please accept the use of targeted cookies to ensure the best marketing experience for your user journey. You may revoke your consent at any time through our Cookie Policy.
build: 33846e280.865