Install and configure MongoDB on Linux the right way. Follow this step-by-step Ubuntu & RHEL guide with commands, security setup, and troubleshooting—avoid common mistakes before they break your deployment. #CentLinux #Linux #MongoDB
Table of Contents
What is MongoDB?
Definition
MongoDB is a NoSQL, document-oriented database designed to store and process data in flexible, JSON-like structures instead of rigid tables.
At its core, MongoDB replaces the traditional row/column model with documents and collections:
- Database → container for collections
- Collection → equivalent to a table
- Document → equivalent to a row (but flexible)

How MongoDB stores data
MongoDB stores data in BSON (Binary JSON) format. That means:
- Fields can vary between documents
- Nested objects and arrays are first-class citizens
- No strict schema enforcement by default
Example document
{
"_id": ObjectId("65f1a2b3c4d5e6f7"),
"name": "Alice",
"role": "DevOps Engineer",
"skills": ["Linux", "Docker", "Kubernetes"],
"projects": [
{
"name": "CI/CD Pipeline",
"status": "active"
}
]
}You don’t need to define a schema before inserting this. That’s the main shift from relational databases.
Key characteristics
1. Schema flexibility
You can add or remove fields without migrations.
Good for:
- Rapid development
- Evolving application requirements
Bad for:
- Teams without data discipline
2. Document model (JSON-native)
MongoDB aligns naturally with modern applications:
- REST APIs
- Node.js backends
- Microservices
No impedance mismatch between app objects and database structure.
3. Horizontal scalability
MongoDB supports sharding, which allows you to distribute data across multiple nodes.
This matters when:
- Data grows beyond a single server
- You need high throughput at scale
4. High write performance
MongoDB is optimized for:
- Insert-heavy workloads
- Event logging
- Real-time ingestion systems
5. Rich query capabilities
You can query documents using:
db.users.find({ role: "admin" })With support for:
- Indexes
- Aggregation pipelines
- Text search
- Geospatial queries
Read Also: Install MongoDB on Linux Server 9
Where MongoDB fits in real systems
MongoDB is commonly used for:
- Backend APIs
- Content management systems
- Product catalogs
- Logging and analytics pipelines
- IoT and event-driven systems
Example:
Instead of splitting user + orders across multiple tables, MongoDB often stores related data together in a single document for faster reads.
When MongoDB is a bad choice
MongoDB is not ideal when:
- You need strict ACID transactions across many tables
- Heavy relational joins are required
- Data integrity must be tightly enforced at the database level
Use a relational database in those cases.
Quick mental model
If your data looks like this:
{
"user": {
"name": "Alice",
"orders": [...]
}
}MongoDB fits naturally.
If your data looks like:
- multiple normalized tables
- heavy joins
- strict constraints
use MySQL or PostgreSQL.
MongoDB vs MySQL
If you’re deciding between MongoDB and MySQL, stop thinking “which is better” and start thinking “which fits the workload.” These systems solve different problems.
Core difference
- MongoDB → document database (JSON-like, schema-flexible)
- MySQL → relational database (tables, strict schema, SQL)
Quick comparison table
| Feature | MongoDB | MySQL |
|---|---|---|
| Data model | Document (BSON/JSON) | Relational (tables/rows) |
| Schema | Flexible (schema-less) | Fixed (schema-first) |
| Query language | MongoDB Query API | SQL |
| Scaling | Horizontal (native sharding) | Vertical (primary), horizontal via replicas/sharding setups |
| Transactions | Supported (multi-document, newer) | Mature, ACID by default |
| Joins | Limited ($lookup) | Native and powerful |
| Performance | High for write-heavy, flexible data | Strong for structured queries and joins |
| Use cases | APIs, microservices, logs, IoT | Finance, ERP, reporting, transactional systems |
Read Also: MySQL Cheat Sheet: DBA Edition 2025
When to use MongoDB
MongoDB is the right choice when your data is dynamic, nested, or evolving fast.
Good fits
- JSON-heavy APIs (Node.js, Python backends)
- Microservices with independent schemas
- Logging and event ingestion systems
- Product catalogs with varying attributes
- Rapid prototyping where schema changes often
Example document model
{
"user_id": 101,
"name": "John Doe",
"orders": [
{ "id": 1, "total": 250 },
{ "id": 2, "total": 99 }
]
}No schema migration needed. You add fields when you need them.
Why engineers pick MongoDB
- Faster iteration cycles
- Natural fit for modern app data (JSON everywhere)
- Built-in horizontal scaling (sharding)
When to use MySQL
MySQL is the right choice when you need consistency, relationships, and predictable structure.
Good fits
- Financial systems (ACID matters)
- Reporting and analytics queries
- Applications with strong relational data
- Systems requiring complex joins
Example relational model
CREATE TABLE users (
id INT PRIMARY KEY,
name VARCHAR(100)
);
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
total DECIMAL(10,2),
FOREIGN KEY (user_id) REFERENCES users(id)
);Why engineers pick MySQL
- Mature ecosystem
- Strong consistency guarantees
- Powerful SQL queries and joins
- Easier for structured reporting
Performance reality check
This is where most bad advice lives.
- MongoDB is not “faster” by default
- MySQL is not “outdated”
Actual behavior
- MongoDB wins:
- High write throughput
- Flexible document reads
- Denormalized data access
- MySQL wins:
- Complex joins
- Aggregations across relationships
- Strict transactional workloads
Scaling comparison
MongoDB
- Built-in horizontal scaling via sharding
- Easier to scale out across nodes
- Designed for distributed workloads
MySQL
- Vertical scaling first (bigger machine)
- Horizontal scaling via:
- Read replicas
- Manual sharding
- Proxy layers (e.g., Vitess)
MongoDB is more “cloud-native” out of the box. MySQL can scale just fine, but it takes more engineering.
Schema flexibility vs control
MongoDB
- Flexible schema
- Faster development
- Higher risk of inconsistent data if unmanaged
MySQL
- Strict schema
- Slower changes (migrations required)
- Strong data integrity
Pick your poison: speed vs control
DevOps and operational differences
MongoDB
- Easier to start
- More tuning needed at scale
- Requires discipline for schema design
MySQL
- Predictable operations
- Mature backup and replication tooling
- More rigid but stable
Common mistake
Trying to force one into the other’s job:
- Using MongoDB for heavy relational joins → bad idea
- Using MySQL for rapidly changing JSON blobs → painful
Use the right tool.
Decision cheat sheet
Use MongoDB if:
- Your data is semi-structured or evolving
- You are building APIs or microservices
- You need horizontal scaling early
Use MySQL if:
- You need strong consistency and transactions
- Your data is relational
- You rely heavily on joins and reporting
Real-world pattern (what actually works)
Serious systems often use both:
- MongoDB → application data, events, logs
- MySQL → billing, transactions, reporting
Polyglot persistence is not hype—it’s what production systems actually do.
Bottom line
- MongoDB = flexibility + scale
- MySQL = structure + reliability
Choose based on workload, not trends.
MongoDB on Linux
MongoDB on Linux is straightforward when you stick to the vendor repo, use a supported distro, and stop pretending random blog copy-paste commands from 2021 still apply.
This guide covers MongoDB Community Edition on Linux with practical install steps, service management, shell access, basic hardening, verification, and common break/fix work. It focuses on the two paths most people actually use:
- Ubuntu LTS with
apt - RHEL-compatible systems with
dnforyumsuch as RHEL, Rocky Linux, AlmaLinux, and CentOS Stream
MongoDB’s current installation docs point Linux users to distro-specific instructions, and MongoDB 8.0 has updated platform support requirements. MongoDB 8.0 Community Edition supports Ubuntu LTS installs through distro-specific docs, and on RHEL-compatible systems it supports RHEL, CentOS Stream, Oracle Linux, Rocky Linux, and AlmaLinux 8 and 9 on 64-bit x86_64. MongoDB also notes OS minimum-version requirements changed in 8.0. (Reference: MongoDB Documentation)
What you will do
By the end of this tutorial, you will know how to:
- Install MongoDB from the official repository
- Start and enable the
mongodservice - Connect with MongoDB Shell
- Confirm the database is healthy
- Adjust the bind address for remote access when needed
- Apply basic security controls
- Troubleshoot the usual Linux-side failures
Prerequisites
You need:
- A supported 64-bit Linux distribution
sudoor root access- Internet access to reach the MongoDB repo
- A systemd-based host
- Basic firewall awareness
- A use case that actually needs self-managed MongoDB
Check your OS first.
Detect distro and version
cat /etc/os-release
uname -r
archOn Ubuntu, MongoDB documents package-manager installation for LTS releases. On Red Hat family systems, MongoDB’s distro docs cover RHEL-compatible 8 and 9 series for current 8.0 Community builds.
If you’re running MongoDB locally or building a small lab to test replication, backups, or failover, hardware matters more than people admit. A compact, low-power box like the Beelink Mini S12 Pro Mini PC is a practical choice for spinning up multiple Linux VMs without burning rack space, while a reliable external drive such as the Samsung T7 Portable SSD gives you fast, portable storage for backups and dataset snapshots.
Both are widely used in homelab setups and map directly to real-world MongoDB workflows—testing restores, benchmarking I/O, and simulating production scenarios without touching live systems.
Disclosure: This section contains affiliate links. If you purchase through these links, I may earn a small commission at no extra cost to you.
MongoDB architecture on Linux in 30 seconds
For a basic single-node install, the pieces that matter are:
mongod— the database server daemonmongosh— the shell client/etc/mongod.conf— main config/var/lib/mongo— default data path/var/log/mongodb/mongod.log— default log file path on package installs
That is the whole party. Everything else is details and regret.
Option 1 — Install MongoDB on Ubuntu
MongoDB’s Ubuntu install docs cover Community Edition on supported Ubuntu LTS releases using apt.
Step 1 — Update package metadata and install prerequisites
sudo apt-get update
sudo apt-get install -y gnupg curlThis makes sure you can import the signing key and configure the vendor repository.
Step 2 — Import the MongoDB public GPG key
For MongoDB 8.0, use the vendor key and write it to a keyring file:
curl -fsSL https://pgp.mongodb.com/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmorThis avoids the old apt-key mess, which should stay dead.
Step 3 — Add the MongoDB repository
For Ubuntu 22.04:
echo "deb [ arch=amd64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.listFor Ubuntu 20.04:
echo "deb [ arch=amd64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.listQuick check:
cat /etc/apt/sources.list.d/mongodb-org-8.0.listStep 4 — Install MongoDB packages
sudo apt-get update
sudo apt-get install -y mongodb-orgThis installs the server, shell, tools, and service files.
Step 5 — Start and enable MongoDB
sudo systemctl daemon-reload
sudo systemctl enable --now mongodStep 6 — Verify the service
sudo systemctl status mongod --no-pager
sudo journalctl -u mongod -n 50 --no-pager
ss -ltnp | grep 27017You should see mongod listening on TCP 27017.
Option 2 — Install MongoDB on RHEL, Rocky, AlmaLinux, or CentOS Stream
MongoDB’s Red Hat-family docs cover Community Edition installs with the vendor repo. MongoDB 8.0 Community Edition supports RHEL, CentOS Stream, Oracle Linux, Rocky Linux, and AlmaLinux 8 and 9 on x86_64.
Step 1 — Create the repository file
sudo cat /etc/yum.repos.d/mongodb-org-8.0.repo > /dev/null << EOF
[mongodb-org-8.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/8.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-8.0.asc
EOFVerify it:
cat /etc/yum.repos.d/mongodb-org-8.0.repoStep 2 — Install MongoDB
On RHEL 8/9, Rocky 8/9, AlmaLinux 8/9, or CentOS Stream:
sudo dnf install -y mongodb-orgOn older hosts where yum is still the package front-end:
sudo yum install -y mongodb-orgStep 3 — Start and enable MongoDB
sudo systemctl enable --now mongodStep 4 — Verify the service
sudo systemctl status mongod --no-pager
sudo journalctl -u mongod -n 50 --no-pager
ss -ltnp | grep 27017Check installed package versions
On Debian/Ubuntu:
dpkg -l | grep mongodb
apt-cache policy mongodb-orgOn RHEL family:
rpm -qa | grep mongodb
dnf list installed | grep mongodbThis confirms what actually landed on disk instead of what you hope landed on disk.
Connect to MongoDB with mongosh
Once mongod is running, connect locally:
mongoshInside the shell, run:
db.runCommand({ ping: 1 })Expected output includes "ok" : 1.
You can also check version details:
db.version()
db.adminCommand({ serverStatus: 1 }).versionCreate test data
Basic CRUD smoke test:
use opslab
db.hosts.insertOne({
hostname: "node01",
role: "mongodb-test",
env: "lab",
created_at: new Date()
})
db.hosts.find().pretty()That proves the server is writable and not just sitting there looking expensive.
Default configuration file
MongoDB package installs place the main config in:
/etc/mongod.confA typical default config looks roughly like this:
storage:
dbPath: /var/lib/mongo
systemLog:
destination: file
path: /var/log/mongodb/mongod.log
logAppend: true
net:
port: 27017
bindIp: 127.0.0.1
processManagement:
timeZoneInfo: /usr/share/zoneinfoThe exact file can vary slightly by package version and distro, but the important defaults are the same: local bind, port 27017, data under /var/lib/mongo, logs under /var/log/mongodb. MongoDB package installs use mongod.conf as the main config entry point.
Always back it up before editing:
sudo cp /etc/mongod.conf /etc/mongod.conf.bak.$(date +%F-%H%M%S)Allow remote connections
By default, MongoDB usually binds to localhost for obvious reasons: the internet is full of people with scanners and bad intentions.
Edit the config:
sudo vi /etc/mongod.confChange:
net:
port: 27017
bindIp: 127.0.0.1
To either a specific interface IP:
net:
port: 27017
bindIp: 127.0.0.1,10.0.0.25Or all interfaces:
net:
port: 27017
bindIp: 0.0.0.0Restart the service:
sudo systemctl restart mongod
sudo systemctl status mongod --no-pagerConfirm listening sockets:
ss -ltnp | grep 27017Read Also: Vim Cheat Sheet for DevOps and Linux Admins
Open the firewall
On Ubuntu with UFW:
sudo ufw allow from 10.0.0.0/24 to any port 27017 proto tcp
sudo ufw statusOn RHEL family with firewalld:
sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/24" port protocol="tcp" port="27017" accept'
sudo firewall-cmd --reload
sudo firewall-cmd --list-allDo not expose 27017 to the whole internet unless you enjoy incident response.
Basic security hardening
A raw MongoDB install without access control is fine for a sealed lab box. It is not fine for anything remotely resembling production.
Step 1 — Create an admin user
First, connect locally before enabling authorization:
mongoshInside mongosh:
use admin
db.createUser({
user: "siteAdmin",
pwd: "ReplaceThisWithAStrongPassword",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})Exit the shell:
exitStep 2 — Enable authorization
Edit config:
sudo vi /etc/mongod.confAdd:
security:
authorization: enabledRestart:
sudo systemctl restart mongodStep 3 — Log in with credentials
mongosh -u siteAdmin -p --authenticationDatabase adminOr, for scripted testing:
mongosh "mongodb://siteAdmin:ReplaceThisWithAStrongPassword@127.0.0.1:27017/admin"Be careful with passwords in shell history and process tables. Interactive prompt is safer.
Create an application database and user
Do not run apps as your admin user unless you are actively trying to make future debugging worse.
Inside authenticated mongosh:
use inventory
db.createUser({
user: "inventory_app",
pwd: "UseAnotherStrongPassword",
roles: [
{ role: "readWrite", db: "inventory" }
]
})
db.products.insertOne({
sku: "srv-001",
name: "Rack Server",
qty: 12,
price: 2499
})
db.products.find().pretty()Test app login:
mongosh "mongodb://inventory_app:UseAnotherStrongPassword@127.0.0.1:27017/inventory?authSource=inventory"Useful Linux administration commands
Check service state
systemctl is-enabled mongod
systemctl is-active mongod
systemctl status mongod --no-pagerRestart after config changes
sudo systemctl restart mongodFollow logs live
sudo journalctl -fu mongodIf file logging is enabled in config, you can also use:
sudo tail -f /var/log/mongodb/mongod.logCheck process and port
pgrep -a mongod
ss -ltnp | grep 27017Check disk usage
df -h /var/lib/mongo
du -sh /var/lib/mongoConfirm data path permissions
ls -ld /var/lib/mongo
ls -ld /var/log/mongodbExample automation script for first-pass validation
Use this Bash script after install to verify the basics.
#!/usr/bin/env bash
set -euo pipefail
echo "==> Service state"
systemctl is-enabled mongod || true
systemctl is-active mongod || true
echo "==> Socket check"
ss -ltnp | grep 27017 || true
echo "==> Version check"
mongod --version | head -n 5
echo
mongosh --version
echo "==> Ping test"
mongosh --quiet --eval 'db.runCommand({ ping: 1 })'Save it as:
vi mongodb-healthcheck.shMake it executable and run it:
chmod +x mongodb-healthcheck.sh
./mongodb-healthcheck.shPin package versions when needed
If you need stable patch behavior during a controlled maintenance window, pin versions instead of letting the box drift.
On Ubuntu, MongoDB documents installing specific package versions when required. MongoDB’s install docs also note that upgrades differ depending on whether you are staying within patch releases or moving across major versions.
Example on Ubuntu:
apt-cache madison mongodb-orgThen install a specific version:
sudo apt-get install -y \
mongodb-org=8.0.0 \
mongodb-org-database=8.0.0 \
mongodb-org-server=8.0.0 \
mongodb-org-shell=8.0.0 \
mongodb-org-mongos=8.0.0 \
mongodb-org-tools=8.0.0Hold packages:
echo "mongodb-org hold" | sudo dpkg --set-selections
echo "mongodb-org-database hold" | sudo dpkg --set-selections
echo "mongodb-org-server hold" | sudo dpkg --set-selections
echo "mongodb-org-shell hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selectionsOn RHEL family, inspect available versions:
dnf list --showduplicates mongodb-orgInstall a chosen version if your repo metadata exposes it.
Upgrade workflow basics
For routine maintenance:
- Back up the database
- Read the target release notes
- Confirm OS compatibility
- Upgrade packages from the official repo
- Restart
mongod - Validate app connectivity and logs
MongoDB’s install and release docs explicitly call out version-specific platform support and upgrade considerations.
Uninstall MongoDB cleanly
Ubuntu:
sudo systemctl stop mongod
sudo apt-get purge -y mongodb-org*
sudo rm -rf /var/log/mongodb
sudo rm -rf /var/lib/mongoRHEL family:
sudo systemctl stop mongod
sudo dnf remove -y mongodb-org*
sudo rm -rf /var/log/mongodb
sudo rm -rf /var/lib/mongoBe careful with the last two commands. They do exactly what they look like they do.
Verification checklist
Use this after install or after changes.
Service health
systemctl is-active mongodExpected:
activeLocal shell connectivity
mongosh --eval 'db.runCommand({ ping: 1 })'Expected output includes:
{ ok: 1 }Socket listening
ss -ltnp | grep 27017Authentication test
mongosh -u siteAdmin -p --authenticationDatabase admin --eval 'db.runCommand({ connectionStatus: 1 })'Firewall test from a remote client
From another Linux host:
nc -zv 10.0.0.25 27017Or:
telnet 10.0.0.25 27017nc is cleaner. telnet just refuses to die.
Troubleshooting
mongod fails to start
Start with logs:
sudo systemctl status mongod --no-pager
sudo journalctl -u mongod -n 100 --no-pagerCommon causes:
- Broken YAML syntax in
/etc/mongod.conf - Invalid bind IP
- Permission issues on data or log directories
- Existing stale process or socket confusion
- Unsupported distro/version combination
Validate config formatting carefully. YAML hates sloppy indentation.
Port 27017 is not listening
Check whether the service is actually running:
systemctl is-active mongodIf active but no listener appears:
grep -nE '^\s*port:|^\s*bindIp:' /etc/mongod.confThen restart:
sudo systemctl restart mongodPermission denied on data path
Inspect ownership:
ls -ld /var/lib/mongo /var/log/mongodbRepair ownership if required:
sudo chown -R mongod:mongod /var/lib/mongo /var/log/mongodbThen restart:
sudo systemctl restart mongodSELinux issues on RHEL-family systems
Check enforcing state:
getenforceInspect AVC denials:
sudo ausearch -m AVC -ts recentIf MongoDB paths or ports were customized, SELinux context work may be required. Keep SELinux enabled and fix policy or labeling properly instead of disabling it out of laziness.
Firewall blocks remote access
Check local listener first:
ss -ltnp | grep 27017Then inspect firewall rules.
UFW:
sudo ufw status numberedFirewalld:
sudo firewall-cmd --list-allAuthentication fails
Make sure:
- You enabled
security.authorization: enabled - You are authenticating against the correct database
- The username and role exist
- The app is not trying to auth against
adminwhen the user was created in another DB
Test explicitly:
mongosh "mongodb://inventory_app:UseAnotherStrongPassword@127.0.0.1:27017/inventory?authSource=inventory"command not found: mongosh
Check package install:
Ubuntu:
dpkg -l | grep -E 'mongodb|mongosh'RHEL family:
rpm -qa | grep -E 'mongodb|mongosh'Then check path:
command -v mongoshCommon mistakes
Here is the repeat offender list:
- Installing from distro-native packages instead of MongoDB’s official repo
- Using an unsupported OS release
- Exposing
0.0.0.0:27017to the public internet - Enabling remote access before authentication
- Editing YAML with bad indentation
- Running applications as admin users
- Forgetting to open the firewall for the correct source range
- Skipping log review and guessing blindly
Best practices
For real systems, do this as standard operating procedure:
- Use the official MongoDB repository
- Stay on supported OS versions
- Keep
bindIprestricted - Enable authentication before remote exposure
- Use per-application database users with least privilege
- Monitor disk, memory, and log growth
- Back up before upgrades
- Test upgrades in a lab first
- Document your repo version, config changes, and firewall rules
MongoDB’s current docs emphasize distro-specific supported install paths and platform compatibility, especially for newer 8.0 releases. That matters because “it installed” and “it is supported” are not the same sentence.
Final thoughts
MongoDB on Linux is easy to install and easier to misconfigure. The sane path is simple:
- use the official repo
- install on a supported distro
- verify
mongod - lock down network exposure
- enable authentication
- create proper app users
- watch logs instead of guessing
That gets you a clean, repeatable baseline without turning your database into a public science experiment.
If you want the next piece done properly, the strongest follow-up topics are MongoDB replication on Linux, MongoDB backup and restore, or MongoDB hardening with TLS and systemd overrides.
FAQs
What is MongoDB and why use it on Linux?
MongoDB is a document-oriented NoSQL database designed for flexible schemas and high write throughput. On Linux, it integrates cleanly with systemd, standard logging, and automation tooling, making it a solid fit for DevOps workflows, microservices, and data-heavy applications.
Which Linux distributions are supported by MongoDB?
MongoDB Community Edition supports major 64-bit Linux distributions, including:
– Ubuntu LTS (20.04, 22.04)
– RHEL, Rocky Linux, AlmaLinux (8, 9)
– CentOS Stream
Always verify your exact version against MongoDB’s official compatibility matrix before installing.
What is the default port used by MongoDB?
MongoDB listens on TCP port: 27017
Verify on your system:
ss -ltnp | grep 27017
Where does MongoDB store data on Linux?
Default data directory: /var/lib/mongo
Log file location: /var/log/mongodb/mongod.log
Both can be changed in: /etc/mongod.conf
How do I start and enable MongoDB on Linux?
Enable and start Service:
sudo systemctl enable –now mongod
Check status:
systemctl status mongod –no-pager
How do I connect to MongoDB from the terminal?
Run following command:
mongosh
Test connection:
db.runCommand({ ping: 1 })
How do I check MongoDB logs?
sudo journalctl -u mongod -f
Or:
tail -f /var/log/mongodb/mongod.log
Logs are your first stop. Always.
How do I uninstall MongoDB from Linux?
Ubuntu:
sudo apt-get purge -y mongodb-org*
sudo rm -rf /var/lib/mongo /var/log/mongodb
RHEL-based:
sudo dnf remove -y mongodb-org*
sudo rm -rf /var/lib/mongo /var/log/mongodb
Be careful—this deletes all data.
Recommended Courses
If you’re serious about mastering modern databases, MongoDB – The Complete Developer’s Guide 2025 by Maximilian Schwarzmüller is a must-have course. It takes you from the basics of NoSQL to advanced MongoDB features with real-world projects, making it perfect for developers, data engineers, and aspiring full-stack professionals.
With Maximilian’s clear teaching style, you’ll gain practical skills that are highly in demand in today’s job market. Don’t miss the chance to future-proof your career with MongoDB expertise—[enroll now] and start building scalable, high-performance applications!
Disclaimer: This post contains affiliate links. If you purchase through these links, I may earn a small commission at no extra cost to you.

Leave a Reply
You must be logged in to post a comment.