MongoDB is a NoSQL, document-oriented database designed for flexibility and horizontal scalability — commonly used for APIs, content management systems, and applications with evolving or unstructured data models.
Prerequisites
- Ubuntu 22.04/24.04 or Debian 11/12 VPS
- Root or sudo access
Step 1 — Install Required Packages
sudo apt update
sudo apt install gnupg curl -y
Step 2 — Import the MongoDB GPG Key
curl -fsSL https://pgp.mongodb.com/server-8.0.asc | \
sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server.gpg
Step 3 — Add the MongoDB Repository
For Ubuntu:
echo "deb [signed-by=/usr/share/keyrings/mongodb-server.gpg] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/8.0 multiverse" | \
sudo tee /etc/apt/sources.list.d/mongodb-org.list
For Debian:
echo "deb [signed-by=/usr/share/keyrings/mongodb-server.gpg] https://repo.mongodb.org/apt/debian $(lsb_release -cs)/mongodb-org/8.0 main" | \
sudo tee /etc/apt/sources.list.d/mongodb-org.list
Step 4 — Install MongoDB
sudo apt update
sudo apt install mongodb-org -y
Step 5 — Enable and Start MongoDB
sudo systemctl enable mongod
sudo systemctl start mongod
sudo systemctl status mongod
Step 6 — Connect and Verify
mongosh
db.version()
Step 7 — Enable Authentication (Important)
By default, MongoDB has no authentication enabled — enable it before any production use.
Create an admin user:
use admin
db.createUser({
user: "admin",
pwd: "CHANGE_ME_STRONG_PASSWORD",
roles: [{ role: "root", db: "admin" }]
})
exit
Enable authorization:
sudo nano /etc/mongod.conf
security:
authorization: enabled
sudo systemctl restart mongod
Connect using credentials going forward:
mongosh -u admin -p --authenticationDatabase admin
Restricting Network Access
By default, MongoDB binds only to 127.0.0.1 — keep it that way unless remote access is genuinely required, and restrict any exception to specific trusted IPs at the firewall level.
Common Errors
MongoDB won't start:
sudo journalctl -u mongod
"Authentication failed" — confirm you're connecting with --authenticationDatabase admin and the correct credentials.
Best Practices
- Always enable authentication before production use
- Never expose MongoDB directly to the public internet without authentication and firewall restrictions
- Create separate users with minimal required roles per application
- Schedule regular backups with
mongodump
FAQ
Is MongoDB a SQL database?
No — it's a NoSQL, document-oriented database storing data as flexible JSON-like documents rather than fixed relational tables.
Related Articles
- How to Run MySQL, PostgreSQL & Redis in Docker Containers
- How to Set Up Automated VPS Backups
- VPS Security Checklist for Beginners
