MongoDB is the most widely used document-oriented NoSQL database, designed for storing flexible JSON-like documents with dynamic schemas. It handles high-volume reads and writes, horizontal scaling through sharding, and built-in replication for high availability – making it a solid choice for modern applications that outgrow traditional relational databases.
This guide walks through installing MongoDB 8.0 LTS on Debian 13 (Trixie), Debian 12 (Bookworm), and Ubuntu 24.04 (Noble Numbat). We cover the full stack – from repository setup to authentication, firewall rules, replica sets, backups, and performance tuning. All commands have been tested on a live server running MongoDB 8.0.20.
Prerequisites
Before starting, confirm you have the following in place:
- A server running Debian 13, Debian 12, or Ubuntu 24.04 LTS
- Root or sudo access
- At least 2 GB RAM (4 GB recommended for production workloads)
- Internet connectivity to download packages from MongoDB repositories
- Port 27017/TCP open if remote clients need to connect
Step 1: Install Required Packages
MongoDB packages are distributed through their official APT repository. Install gnupg and curl first – these are needed to import the GPG signing key and add the repo.
sudo apt update && sudo apt install -y gnupg curl
Step 2: Import MongoDB 8.0 GPG Key
Download the official MongoDB GPG key and convert it to the binary format used by modern APT.
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg
Verify the key was saved correctly.
file /usr/share/keyrings/mongodb-server-8.0.gpg
Expected output:
/usr/share/keyrings/mongodb-server-8.0.gpg: OpenPGP Public Key Version 4
Step 3: Add MongoDB 8.0 Repository
Add the official MongoDB APT repository for your distribution. Run only the command that matches your OS.
Ubuntu 24.04 (Noble)
echo "deb [signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg] http://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
Debian 12 (Bookworm)
echo "deb [signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg] http://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
Debian 13 (Trixie)
MongoDB does not yet publish dedicated packages for Debian 13. The Bookworm repository works on Trixie without issues since the library dependencies are compatible.
echo "deb [signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg] http://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
Step 4: Install MongoDB 8.0 on Debian / Ubuntu
Update the package index and install the mongodb-org meta-package. This pulls in the server, shell, tools, and mongos router.
sudo apt update && sudo apt install -y mongodb-org
Confirm the installed packages.
dpkg -l | grep mongodb
You should see mongodb-org 8.0.20, mongodb-mongosh 2.8.1, and mongodb-database-tools 100.15.0 (or newer) in the output.
Step 5: Start and Enable MongoDB Service
Enable the mongod service so it starts automatically on boot, and start it immediately.
sudo systemctl enable --now mongod
Check the service status to confirm it is running.
sudo systemctl status mongod
Expected output:
● mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled; preset: enabled)
Active: active (running)
Step 6: Verify MongoDB Version
Use mongosh to verify the running server version.
mongosh --eval "db.version()" --quiet
Output:
8.0.20
If you see the version number, MongoDB 8.0 is installed and running on your system.
Step 7: Configure MongoDB (mongod.conf)
The main configuration file is /etc/mongod.conf. Open it with your preferred editor.
sudo vim /etc/mongod.conf
Here are the key default settings and what they do:
# Data directory - where MongoDB stores database files
storage:
dbPath: /var/lib/mongodb
# Log file location
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
# Network settings
net:
port: 27017
bindIp: 127.0.0.1 # Only localhost by default
The default bindIp: 127.0.0.1 means MongoDB only accepts connections from localhost. We will change this later for remote access. The storage engine is WiredTiger by default in MongoDB 8.0 – no need to set it explicitly.
Step 8: Enable MongoDB Authentication
A fresh MongoDB install has no authentication enabled – anyone with network access to port 27017 can read and write all databases. Fix this immediately.
Create an Admin User
Connect to mongosh and create an admin user in the admin database.
mongosh
Run the following commands inside the mongosh shell. Replace StrongPassword123 with your own secure password.
use admin
db.createUser({
user: "mongoadmin",
pwd: "StrongPassword123",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
You should see { ok: 1 } in the output. Exit the shell with exit.
Enable Authorization in Config
Edit /etc/mongod.conf and add the security section.
sudo vim /etc/mongod.conf
Add these lines (or uncomment the existing security section):
security:
authorization: enabled
Restart MongoDB to apply the change.
sudo systemctl restart mongod
Test authentication by connecting with credentials. For more details on setting up MongoDB roles and permissions, see the MongoDB authentication configuration guide.
mongosh -u mongoadmin -p StrongPassword123 --authenticationDatabase admin
If you get the mongosh prompt without errors, authentication is working correctly.
Step 9: Configure Firewall Rules
If remote clients or application servers need to connect to MongoDB, open port 27017/TCP in your firewall. Only allow connections from trusted IPs – never expose MongoDB to the public internet.
UFW (Ubuntu / Debian)
Allow a specific application server to reach MongoDB.
sudo ufw allow from 10.0.1.50 to any port 27017 proto tcp comment "MongoDB access from app server"
To allow an entire subnet:
sudo ufw allow from 10.0.1.0/24 to any port 27017 proto tcp comment "MongoDB access from app subnet"
Verify the rule was added.
sudo ufw status numbered
Firewalld (Alternative)
If your server uses firewalld instead of UFW, use the rich rule approach to restrict by source IP.
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.1.50" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --reload
For a complete firewall setup guide, refer to installing and configuring firewalld on Debian.
Step 10: Basic CRUD Operations with mongosh
Connect to MongoDB and run through the core operations to confirm everything works. If authentication is enabled, connect with your admin credentials.
mongosh -u mongoadmin -p StrongPassword123 --authenticationDatabase admin
Create a Database and Insert Documents
Switch to a new database. MongoDB creates it automatically when you insert the first document.
use testdb
Insert a single document.
db.users.insertOne({ name: "Alice", email: "[email protected]", role: "admin" })
Insert multiple documents at once.
db.users.insertMany([
{ name: "Bob", email: "[email protected]", role: "developer" },
{ name: "Carol", email: "[email protected]", role: "developer" },
{ name: "Dave", email: "[email protected]", role: "viewer" }
])
Query Documents
Find all documents in the collection.
db.users.find()
Filter by a specific field.
db.users.find({ role: "developer" })
Count documents matching a condition.
db.users.countDocuments({ role: "developer" })
Output: 2
Update Documents
Update a single document by matching a field.
db.users.updateOne({ name: "Dave" }, { $set: { role: "editor" } })
Verify the update.
db.users.find({ name: "Dave" })
Delete Documents
Delete a single document.
db.users.deleteOne({ name: "Dave" })
Confirm the deletion.
db.users.countDocuments()
Output: 3
Create an Index
Indexes speed up queries on frequently searched fields. Create an index on the email field.
db.users.createIndex({ email: 1 })
List all indexes on the collection.
db.users.getIndexes()
Step 11: Backup and Restore with mongodump / mongorestore
The mongodb-database-tools package includes mongodump and mongorestore for logical backups. These work well for databases under 100 GB. For larger datasets, consider filesystem snapshots instead.
Backup All Databases
mongodump -u mongoadmin -p StrongPassword123 --authenticationDatabase admin --out /var/backups/mongodb/$(date +%Y%m%d)
This creates a directory under /var/backups/mongodb/ with BSON dumps of every database.
Backup a Single Database
mongodump -u mongoadmin -p StrongPassword123 --authenticationDatabase admin --db testdb --out /var/backups/mongodb/testdb-$(date +%Y%m%d)
Restore from Backup
Restore a specific database from a backup directory.
mongorestore -u mongoadmin -p StrongPassword123 --authenticationDatabase admin --db testdb /var/backups/mongodb/20260320/testdb
Add the --drop flag if you want to drop existing collections before restoring.
mongorestore -u mongoadmin -p StrongPassword123 --authenticationDatabase admin --drop /var/backups/mongodb/20260320
For automated backup strategies including cloud storage, see our guide on backing up databases to Amazon S3.
Step 12: Enable Replica Set (Single-Node for Development)
Some MongoDB features like change streams and transactions require a replica set. You can run a single-node replica set on a development or test server. For production multi-node MongoDB replication, deploy at least three members.
Edit /etc/mongod.conf and add the replication section.
sudo vim /etc/mongod.conf
Add the following block:
replication:
replSetName: "rs0"
Restart MongoDB to apply.
sudo systemctl restart mongod
Connect with mongosh and initiate the replica set.
mongosh -u mongoadmin -p StrongPassword123 --authenticationDatabase admin
Run the initiation command.
rs.initiate()
Check replica set status.
rs.status()
The output should show your node as PRIMARY with "stateStr" : "PRIMARY". The mongosh prompt will also change to rs0 [direct: primary].
Step 13: Configure Remote Access
By default, MongoDB only listens on 127.0.0.1. To allow remote application servers to connect, update the bindIp setting in /etc/mongod.conf.
sudo vim /etc/mongod.conf
Change the net section to bind to all interfaces, or to a specific private IP.
net:
port: 27017
bindIp: 0.0.0.0 # Listen on all interfaces
For better security, bind only to the server’s private IP instead of 0.0.0.0. For example:
net:
port: 27017
bindIp: 127.0.0.1,10.0.1.10 # Localhost + private IP
Restart MongoDB after making changes.
sudo systemctl restart mongod
Verify MongoDB is listening on the expected address.
ss -tlnp | grep 27017
Make sure authentication is enabled (Step 8) and firewall rules are in place (Step 9) before exposing MongoDB to the network. Never run MongoDB without authentication on a network-accessible interface.
Step 14: Performance Tuning
MongoDB 8.0 uses the WiredTiger storage engine. A few key settings can significantly improve performance on production servers.
WiredTiger Cache Size
By default, WiredTiger uses 50% of available RAM minus 1 GB for its internal cache. On a dedicated database server with 16 GB RAM, you can set this explicitly in /etc/mongod.conf.
storage:
dbPath: /var/lib/mongodb
wiredTiger:
engineConfig:
cacheSizeGB: 8 # Set to ~50-60% of total RAM on dedicated servers
On shared servers where MongoDB is not the only service, reduce this to 25-30% of total RAM to leave room for the OS and other processes.
Set System Ulimits
MongoDB needs higher file descriptor and process limits than the system defaults. Create a limits configuration file.
sudo vim /etc/security/limits.d/mongodb.conf
Add these entries:
mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 64000
mongod hard nproc 64000
Disable Transparent Huge Pages (THP)
THP causes memory allocation latency spikes with MongoDB. Disable it by creating a systemd service. Create the unit file.
sudo vim /etc/systemd/system/disable-thp.service
Add the following content:
[Unit]
Description=Disable Transparent Huge Pages
DefaultDependencies=no
After=sysinit.target local-fs.target
Before=mongod.service
[Service]
Type=oneshot
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/enabled'
ExecStart=/bin/sh -c 'echo never > /sys/kernel/mm/transparent_hugepage/defrag'
[Install]
WantedBy=basic.target
Enable and start the service, then restart MongoDB.
sudo systemctl daemon-reload
sudo systemctl enable --now disable-thp
sudo systemctl restart mongod
Verify THP is disabled.
cat /sys/kernel/mm/transparent_hugepage/enabled
Expected output should show [never] as the selected option.
Step 15: Uninstall MongoDB
If you need to completely remove MongoDB from your system, stop the service first and then purge all packages.
sudo systemctl stop mongod
sudo systemctl disable mongod
Remove all MongoDB packages.
sudo apt purge -y mongodb-org*
Delete data directories, logs, and the repository file.
sudo rm -rf /var/lib/mongodb /var/log/mongodb
sudo rm /etc/apt/sources.list.d/mongodb-org-8.0.list
sudo rm /usr/share/keyrings/mongodb-server-8.0.gpg
Update the package cache to clean up.
sudo apt update
Conclusion
MongoDB 8.0 is now installed and configured on your Debian 13, Debian 12, or Ubuntu 24.04 server. You have authentication enabled, firewall rules restricting access, and the knowledge to run backups and basic CRUD operations.
For production deployments, deploy a three-member replica set across separate hosts, set up automated daily backups with mongodump, enable TLS encryption for client connections, and integrate monitoring with Prometheus and Grafana using PMM. Check the MongoDB production notes for the full hardening checklist.
Related Guides
- Configure MongoDB Replication on Ubuntu
- How To Configure MongoDB Authentication
- Install RavenDB NoSQL Database on Ubuntu
- Install PostgreSQL Database Server on Ubuntu
- Monitoring MySQL and MongoDB with Prometheus and Grafana




































































Finally a proper guide to install mongodb, everyone else just copy pasted the same old apt-key version.
Jarre Johansson,
We really appreciate your feedback.