How to Install and Secure MongoDB on Ubuntu 24.04
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.
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:
$ 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:
$ 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:
$ sudo apt update
$ sudo apt install -y mongodb-org
1.4 Verify the MongoDB Installation
Check the installed MongoDB version to confirm the installation:
$ 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
$ sudo systemctl enable mongod
2.2 Start the MongoDB Service
$ sudo systemctl start mongod
2.3 Check the MongoDB Service Status
$ 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
$ mongosh
3.2 Create an Admin User
Switch to the admin database and create an administrative user with full privileges:
> 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:
db.getUsers()
The output should resemble the example below:
{
"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:
exit
3.4 Enable Authentication
Open the MongoDB configuration file and enable authentication:
$ sudo nano /etc/mongod.conf
Find the #security:
section and modify it as follows:
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:
$ mongosh -u mongodbadmin -p --authenticationDatabase admin
Enter the password when prompted.Database
Switch to a new database named example_db
:
> use example_db
4.3 Create a New Database User
Create a new user with read and write permissions for the example_db
database:
> 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:
> db.messages.insertOne({ message: "Hello, MongoDB!" })
4.5 Retrieve Data
View the inserted document:
> db.messages.find()
4.6 Update Data
Modify an existing document by updating the message:
> db.messages.updateOne(
{ message: "Hello, MongoDB!" },
{ $set: { message: "Welcome to MongoDB!" } }
)
4.7 Delete Data
Remove a document from the collection:
> 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:
$ mongodump --db example_db --out ~/mongodb_backup
5.2 Restore a Database Backup
To restore data from a backup, use the mongorestore
command:
$ 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
$ sudo systemctl stop mongod
6.2 Remove MongoDB Packages
Uninstall MongoDB with the following command:
$ sudo apt purge -y mongodb-org*
6.3 Delete MongoDB Data
To completely remove MongoDB, delete the data directories:
$ 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.