Tutorials  /  Databases

Install MongoDB on Ubuntu 24.04 - Step-by-Step Guide

Ccentron Redaktion · March 2025 ·6 min read ·Databases, Tutorial

MongoDB is an open-source NoSQL database that stores data in flexible, JSON-like documents. It supports dynamic data structures, ad-hoc queries, indexing, and real-time aggregation, making it efficient for data analysis. Unlike traditional relational databases that use fixed schemas and tables, MongoDB offers a highly scalable solution, ideal for handling unstructured or semi-structured data.

In this guide, you will learn how to install MongoDB on Ubuntu 24.04, configure the database service, secure it with authentication, and perform essential CRUD (Create, Read, Update, Delete) operations.

Prerequisites

  • Access to an Ubuntu 24.04 system as a non-root user with sudo privileges.
  • Basic familiarity with the Linux command line.
DB

Matching infrastructure at centron

Databases need care in production: centron can take over updates, backups and monitoring – from a single instance to a full cluster. Explore managed clusters →

Step 1: Install MongoDB

MongoDB is not included in the default Ubuntu 24.04 package repositories. Therefore, you need to add the official MongoDB repository before installing it.

1.1 Import the MongoDB GPG Key

Run the following command to import MongoDB’s GPG key, which ensures package authenticity:

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

1.2 Add the MongoDB Repository

Next, add the MongoDB repository to your system’s APT sources list:

Console
$ 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

1.3 Update the Package Index and Install MongoDB

Update your package list and install MongoDB:

Console
$ sudo apt update
$ sudo apt install -y mongodb-org

1.4 Verify the MongoDB Installation

Check the installed MongoDB version to confirm the installation:

Console
$ mongod --version

Step 2: Manage the MongoDB Service

MongoDB runs as a system service called mongod. You need to start and enable it to ensure it runs automatically at boot.

2.1 Enable MongoDB at Boot

Console
$ sudo systemctl enable mongod

2.2 Start the MongoDB Service

Console
$ sudo systemctl start mongod

2.3 Check the MongoDB Service Status

Console
$ sudo systemctl status mongod

Step 3: Secure MongoDB with Authentication

By default, MongoDB does not enforce authentication, which poses a security risk. To prevent unauthorized access, enable authentication and create an admin user.

3.1 Access the MongoDB Shell

Console
$ mongosh

3.2 Create an Admin User

Switch to the admin database and create an administrative user with full privileges:

Code
> use admin
> db.createUser({
   user: "mongodbadmin",
   pwd: passwordPrompt(),
   roles: [
       { role: "userAdminAnyDatabase", db: "admin" },
       { role: "readWriteAnyDatabase", db: "admin" },
       { role: "dbAdminAnyDatabase", db: "admin" }
   ]
})

3.3 Verify the Existence of the mongodbadmin User in MongoDB

Retrieve the list of all MongoDB users and ensure that the mongodbadmin user is present by executing the following command:

Code
db.getUsers()

The output should resemble the example below:

JSON
{
  "users": [
    {
      "_id": "admin.mongodbadmin",
      "userId": "UUID('288c02ec-d4a2-4631-b896-6ce6a537529a')",
      "user": "mongodbadmin",
      "db": "admin",
      "roles": [
        { "role": "dbAdminAnyDatabase", "db": "admin" },
        { "role": "userAdminAnyDatabase", "db": "admin" },
        { "role": "readWriteAnyDatabase", "db": "admin" }
      ],
      "mechanisms": [ "SCRAM-SHA-1", "SCRAM-SHA-256" ]
    }
  ],
  "ok": 1
}

After confirming the presence of the mongodbadmin user, exit the MongoDB shell:

Code
exit

3.4 Enable Authentication

Open the MongoDB configuration file and enable authentication:

Console
$ sudo nano /etc/mongod.conf

Find the #security: section and modify it as follows:

YAML
security:
  authorization: enabled

Step 4: Access and Use MongoDB

Once MongoDB is installed and secured, you can access the database shell and perform basic operations.

4.1 Log in to MongoDB as Admin

Use the following command to log in with the newly created admin user:

Console
$ mongosh -u mongodbadmin -p --authenticationDatabase admin

Enter the password when prompted.Database

Switch to a new database named example_db:

Code
> use example_db

4.3 Create a New Database User

Create a new user with read and write permissions for the example_db database:

Code
> db.createUser({
    user: "example_user",
    pwd: passwordPrompt(),
    roles: [{ role: "readWrite", db: "example_db" }]
})

Enter a strong password when prompted.

4.4 Insert Data into a Collection

Create a new collection called messages and insert a document:

Mongodb
> db.messages.insertOne({ message: "Hello, MongoDB!" })

4.5 Retrieve Data

View the inserted document:

Mongodb
> db.messages.find()

4.6 Update Data

Modify an existing document by updating the message:

Mongodb
> db.messages.updateOne(
    { message: "Hello, MongoDB!" },
    { $set: { message: "Welcome to MongoDB!" } }
)

4.7 Delete Data

Remove a document from the collection:

Code
> db.messages.deleteOne({ message: "Welcome to MongoDB!" })

Step 5: Backup and Restore MongoDB Data

5.1 Create a Database Backup

To back up the entire MongoDB database, use the mongodump command:

Console
$ mongodump --db example_db --out ~/mongodb_backup

5.2 Restore a Database Backup

To restore data from a backup, use the mongorestore command:

Console
$ mongorestore --db example_db ~/mongodb_backup/example_db

Step 6: Uninstall MongoDB

If you need to remove MongoDB from your system, follow these steps.

6.1 Stop MongoDB Service

Console
$ sudo systemctl stop mongod

6.2 Remove MongoDB Packages

Uninstall MongoDB with the following command:

Console
$ sudo apt purge -y mongodb-org*

6.3 Delete MongoDB Data

To completely remove MongoDB, delete the data directories:

Console
$ sudo rm -r /var/lib/mongodb
$ sudo rm -r /etc/mongod.conf

Conclusion

In this guide, you installed MongoDB on Ubuntu 24.04, secured it with authentication, and performed essential database operations. You also learned how to back up, restore, and uninstall MongoDB. For more details, refer to the official MongoDB Documentation.

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie Databases
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren