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 Apr 23, 2026

MongoDB is a NoSQL database that stores data as JSON-like documents rather than in rows and tables. It handles unstructured and semi-structured data well, making it a common choice for web applications, real-time analytics, and IoT platforms.

In this tutorial, you will install MongoDB 8.0 on Ubuntu 24.04, create an admin user, enable authentication, configure remote access, and run basic CRUD operations. You will also learn how to back up and restore databases, update MongoDB, and uninstall it cleanly.

#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-efficient dedicated or virtual servers. Get seamless scaling, hourly pricing, and premium 24/7 support.

#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:

Command Line
sudo apt update

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:

Command Line
sudo apt upgrade

#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:

Command Line
sudo apt install -y gnupg curl

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

Command Line
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:

Command Line
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

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.

Command Line
sudo apt update

Next, install MongoDB using the command below:

Command Line
sudo apt install -y mongodb-org

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:

Command Line
sudo systemctl start mongod  
sudo systemctl enable mongod

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:

Command Line
sudo systemctl status mongod
Output● mongod.service - MongoDB Database Server
     Loaded: loaded (/usr/lib/systemd/system/mongod.service; enabled; preset: enabled)
     Active: active (running) since Mon 2026-03-16 08:57:10 EET; 14s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 10673 (mongod)
     Memory: 89.5M (peak: 89.9M)
        CPU: 235ms
     CGroup: /system.slice/mongod.service
             └─10673 /usr/bin/mongod --config /etc/mongod.conf

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:

Command Line
mongosh
OutputCurrent Mongosh Log ID:  69b7aa1a5ad1aabe7c8563b0  
Connecting to:  mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+2.7.0  
Using MongoDB:  8.0.19  
Using Mongosh:  2.7.0  
  
For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/  
  
  
To help improve our products, anonymous usage data is collected and sent to MongoDB periodically (https://www.mongodb.com/legal/privacy-policy).  
You can opt-out by running the disableTelemetry() command.  
  
------  
The server generated these startup warnings when booting  
2026-03-16T08:57:11.038+02:00: Using the XFS filesystem is strongly recommended with the WiredTiger storage engine. See http://dochub.mongodb.org/core/prodnotes-filesystem  
2026-03-16T08:57:11.192+02:00: Access control is not enabled for the database. Read and write access to data and configuration is unrestricted  
2026-03-16T08:57:11.192+02:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile  
2026-03-16T08:57:11.192+02:00: For customers running the current memory allocator, we suggest changing the contents of the following sysfsFile  
2026-03-16T08:57:11.192+02:00: We suggest setting the contents of sysfsFile to 0.  
------  
  
test>

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

db.runCommand({ connectionStatus: 1 })
test> db.runCommand({ connectionStatus: 1 })
{
  authInfo: { authenticatedUsers: [], authenticatedUserRoles: [] },
  ok: 1
}
test>

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:

Command Line
mongod --version
Outputdb version v8.0.19
Build Info: {
    "version": "8.0.19",
    "gitVersion": "cc1adb6b0875cc3003854ac2489818e459686f0b",
    "openSSLVersion": "OpenSSL 3.0.13 30 Jan 2024",
    "modules": [],
    "allocator": "tcmalloc-google",
    "environment": {
        "distmod": "ubuntu2404",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

Also read: How to Install Grub Customizer on Ubuntu

#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:

Command Line
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" ]
})
test> use admin
switched to db admin
admin> db.createUser({
|   user: "newadmin",
|   pwd: "newadmin123",
|   roles: [ { role: "userAdminAnyDatabase", db: "admin" } , "readWriteAnyDatabase" ]
| })
{ ok: 1 }
admin> 

Then exit the Mongo shell.

exit

#Step 7: Securing MongoDB

Now, enable authentication in the MongoDB configuration file. Open it with nano:

Command Line
sudo nano /etc/mongod.conf

Under the security section, add the following line:

security:
  authorization: "enabled"
# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
#  engine:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1


# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:
security:
  authorization: "enabled"

#operationProfiling:

After saving the file, restart MongoDB.

Command Line
sudo systemctl restart mongod

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

Command Line
mongosh -u newadmin -p --authenticationDatabase admin

Here, newadmin is the admin username.

OutputEnter password: ***********  
Current Mongosh Log ID:  69b7ad222b4435d4a38563b0  
Connecting to:  mongodb://<credentials>@127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=admin&appName=mongosh+2.7.0  
Using MongoDB:  8.0.19  
Using Mongosh:  2.7.0  

For mongosh info see: https://www.mongodb.com/docs/mongodb-shell/  
  
test>

Then exit the Mongo shell.

exit

#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:

Command Line
sudo lsof -i | grep mongo
Outputmongod 12109 mongodb 9u IPv4 36380 0t0 TCP localhost:27017 (LISTEN)

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.

Command Line
sudo ufw allow from 192.168.50.0 to any port 27017

Use ufw to verify the change in firewall settings.

Command Line
sudo ufw status
OutputStatus: active  
  
To                   Action             From  
--                     ------                ----  
27017             ALLOW          192.168.50.0

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

Command Line
sudo nano /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.

Command Line
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:

Command Line
ssh user@trusted-server-ip

Run the following nc (netcat) command from your trusted remote server. Netcat is a networking utility for reading and writing data across network connections. It is commonly used to test whether a specific port on a remote host is open and accepting connections:

Command Line
nc -zv mongodb-server-ip 27017

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.

Command Line
Connection to 84.32.97.226  27017 port [tcp/*] succeeded!

Now, you have successfully installed and configured MongoDB!

Let's run a few basic MongoDB commands.

Also read: How to Install Grafana on Ubuntu 24.04

#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
test> show dbs  
admin 148.00 KiB  
config 108.00 KiB  
local 72.00 KiB  
test>

#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
test> use admin  
switched to db admin  
admin>

#3. Show Collections

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

show collections
admin> show collections  
system.users  
system.version  
admin>

#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")
admin> db.createCollection("Employee")  
{ ok: 1 }  
admin>

#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 })
admin> db.createCollection("Employee")
{ ok: 1 }
admin> db.Employee.insertOne({ name: "John", age: 30 })
{
  acknowledged: true,
  insertedId: ObjectId('69b7afe481c24849a88563b1')
}
admin> 

#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" }])
admin> db.Employee.insertMany([{ name: "Megan" }, { name: "Robin" }])
{
  acknowledged: true,
  insertedIds: {
    '0': ObjectId('69b7b00981c24849a88563b2'),
    '1': ObjectId('69b7b00981c24849a88563b3')
  }
}
admin> 

#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 })
admin> db.Employee.find({ age: 30 })
[
  { _id: ObjectId('69b7afe481c24849a88563b1'), name: 'John', age: 30 }
]
admin>

#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 } }
)
admin> db.Employee.updateOne(
|   { name: "John" }, 
|   { $set: { age: 31 } }
| )
{
  acknowledged: true,
  insertedId: null,
  matchedCount: 1,
  modifiedCount: 1,
  upsertedCount: 0
}
admin> 

#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" })
admin> db.Employee.deleteOne({ name: "John" })
{ acknowledged: true, deletedCount: 1 }
admin>

#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()
admin> db.Employee.countDocuments()  
2

#11. Drop collection

To delete an entire collection and all its documents, run:

db.Employee.drop()
admin> db.Employee.drop()  
true  
admin>

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

#How to back up and restore a MongoDB database

Backups are essential for any production MongoDB deployment. The mongodump utility creates a binary export of your database, and mongorestore imports it back.

#Create a backup

To start creating database backups, create a dedicated backup user with the required backup permissions.

Once again, log in to MongoDB as an admin user and authenticate.

Command Line
mongosh -u newadmin -p --authenticationDatabase admin

Create a proper backup user:

use admin
db.createUser({
  user: "backupuser",
  pwd: "StrongBackupPassword123!",
  roles: [
    { role: "backup", db: "admin" },
    { role: "readAnyDatabase", db: "admin" }
  ]
})

Why these roles?

backup → intended for backup operations

readAnyDatabase → ensures it can actually read all DBs

Once done, run the following command to back up all the databases on the server:

Command Line
mongodump --host localhost --port 27017 \
  --username backupuser \
  --password 'StrongBackupPassword123!' \
  --authenticationDatabase admin \
  --out /path/to/backup/mongodb-$(date +%F)

The --out flag specifies the output directory. The $(date +%F) appends the current date to the folder name, making it easy to identify backups by date.

To back up a single database, add the --db flag:

Command Line
mongodump --host localhost --port 27017 \
  --username backupuser \
  --password 'StrongBackupPassword123!' \
  --authenticationDatabase admin \
  --db myapp \
  --out /path/to/backup/mongodb-$(date +%F)

#Restore from a backup

Restore all databases from a backup directory:

Command Line
mongorestore --host localhost --port 27017 \
  --username backupuser \
  --password 'StrongBackupPassword123!' \
  --authenticationDatabase admin \
  /home/path/to/backup/mongodb-2026-03-16/

To restore a single database, specify the path to its folder inside the backup directory:

Command Line
mongorestore --host localhost --port 27017 \
  --username backupuser \
  --password 'StrongBackupPassword123!' \
  --authenticationDatabase admin \
  --db myapp \
  /home/backup/mongodb-2026-03-16/myapp/

Add --drop before the path if you want to drop existing collections before restoring. Schedule automated backups using cron jobs to avoid manual effort.

#How to update MongoDB to a newer version

MongoDB releases patch updates regularly to fix bugs and security vulnerabilities. Update to the latest version within your current major release (e.g., 8.0.x) by refreshing the package index and upgrading:

Command Line
sudo apt update  
sudo apt upgrade mongodb-org

Verify the new version:

Command Line
mongod --version

For major version upgrades (e.g., 8.0 to 8.2), you need to update the repository URL. Replace 8.0 with the target version in the source list file:

Command Line
sudo nano /etc/apt/sources.list.d/mongodb-org-8.0.list

Change the version number in the URL, save the file, then run:

Command Line
sudo apt update  
sudo apt upgrade mongodb-org

Always check the MongoDB release notes for compatibility changes before upgrading between major versions. Back up your databases first.

#How to uninstall MongoDB from Ubuntu

If you no longer need MongoDB, remove it completely with these steps.

Stop the MongoDB service:

Command Line
sudo systemctl stop mongod  
sudo systemctl disable mongod

Purge all MongoDB packages:

Command Line
sudo apt purge mongodb-org*

Remove the data and log directories:

Command Line
sudo rm -rf /var/lib/mongodb  
sudo rm -rf /var/log/mongodb

Clean up the repository and GPG key:

Command Line
sudo rm /etc/apt/sources.list.d/mongodb-org-8.0.list  
sudo rm /usr/share/keyrings/mongodb-server-8.0.gpg  
sudo apt update

#Troubleshooting common MongoDB installation issues

#MongoDB service fails to start

Check the log file for error details:

Command Line
sudo cat /var/log/mongodb/mongod.log | tail -20

The most common cause is incorrect permissions on the data directory. Fix it with:

Command Line
sudo chown -R mongodb:mongodb /var/lib/mongodb  
sudo chown -R mongodb:mongodb /var/log/mongodb

Port conflicts can also prevent startup. Verify that nothing else is using port 27017:

Command Line
sudo lsof -i :27017

#Authentication errors after enabling security

If you enabled authorization but cannot log in, you may have created the admin user on the wrong database. The admin user must exist in the admin database. Connect without authentication by temporarily setting authorization: "disabled" in /etc/mongod.conf, restart MongoDB, recreate the user on the admin database, then re-enable authorization.

#Connection refused from remote hosts

Verify that bindIp in /etc/mongod.conf includes the server's public IP address or 0.0.0.0 to listen on all interfaces. Also, confirm that your firewall allows traffic on port 27017 from the remote IP.

#GPG key or repository errors during apt update

If apt update throws GPG errors after adding the MongoDB repository, the key may not have been downloaded correctly. Re-import it:

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

Then run sudo apt update again.

#Conclusion

MongoDB's document-based model and horizontal scalability make it well-suited for applications with evolving data structures and high throughput requirements. With authentication enabled, regular backups configured, and firewall rules in place, your deployment is ready for production workloads.

For hosting MongoDB at scale, see our guide on how to host MongoDB on a dedicated server. You can also explore the official MongoDB documentation for advanced features like replica sets, sharding, and aggregation pipelines.

FAQs

What is the default port for MongoDB?

MongoDB listens on TCP port `27017` by default. You can change it in the `net.port` setting inside `/etc/mongod.conf`. After changing the port, restart MongoDB and update your firewall rules.

Can I install MongoDB from the default Ubuntu repositories?

Ubuntu's default repositories may include an older version of MongoDB. The official MongoDB repository provides the latest stable release with security patches and performance improvements. Always use the official repository for production environments.

How much RAM does MongoDB need?

At least 2 GB for development. Production workloads benefit from 8 GB or more, depending on the working dataset size.

Is MongoDB free to use?

MongoDB Community Edition is free and open-source under the Server Side Public License (SSPL). MongoDB also offers a commercial Enterprise edition with additional security features, monitoring tools, and vendor support.

How do I check if MongoDB is running?

Run `sudo systemctl status mongod` to check the service status. You can also connect to the shell with `mongosh` and run `db.runCommand({ connectionStatus: 1 })` to confirm the server is accepting connections.

What is the difference between MongoDB and MySQL?

MongoDB stores data in flexible JSON-like documents and supports evolving data structures. MySQL uses structured tables with predefined schemas and is well-suited to applications requiring strict data relationships.

Cloud VPS Hosting

Starting at just $3.51 / month, get virtual servers with top-tier performance.

Share this article

Related Articles

Published on May 5, 2026 Updated on May 6, 2026

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

Learn how to install OpenVPN on Ubuntu 24.04 using an automated script. Set up a secure, self-hosted VPN server quickly with step-by-step instructions.

Read More
Published on Apr 16, 2026 Updated on Apr 17, 2026

Grep Command in Linux: Syntax, Examples & Options Guide

Master the grep command in Linux: learn syntax, options, and practical examples to search, filter, and analyze text, logs, and files efficiently.

Read More
Published on Apr 12, 2026 Updated on Apr 13, 2026

Ubuntu 26.04 LTS: New Features & Release Date

Ubuntu 26.04 LTS Resolute Raccoon brings Wayland default, Linux Kernel 7.0, GNOME 50, better AMD support, security upgrades, snap improvements for 2026 LTS rel.

Read More
No results found for ""
Recent Searches
Navigate
Go
ESC
Exit