How to Install MongoDB on CentOS and Ubuntu (Step-by-Step Guide)
Prerequisites
- Ubuntu 20.04 / 22.04 or CentOS 7/8
- Root or sudo access
- Internet connection
Install MongoDB on Ubuntu
Step 1: Update System
sudo apt update && sudo apt upgrade -y
Step 2: Import GPG Key
wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -
Step 3: Add Repository
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list
Note: Use focal for Ubuntu 20.04 and jammy for Ubuntu 22.04.
Step 4: Update Packages
sudo apt update
Step 5: Install MongoDB
sudo apt install -y mongodb-org
Step 6: Start Service
sudo systemctl start mongod
sudo systemctl enable mongod
Step 7: Check Status
sudo systemctl status mongod
Step 8: Test MongoDB
mongosh
Install MongoDB on CentOS
Step 1: Create Repository File
sudo nano /etc/yum.repos.d/mongodb-org-6.0.repo
Add the following:
[mongodb-org-6.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/6.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-6.0.asc
Step 2: Install MongoDB
sudo yum install -y mongodb-org
Step 3: Start Service
sudo systemctl start mongod
sudo systemctl enable mongod
Step 4: Check Status
sudo systemctl status mongod
Step 5: Open Firewall (Optional)
sudo firewall-cmd --permanent --add-port=27017/tcp
sudo firewall-cmd --reload
Step 6: Test MongoDB
mongosh
Basic Configuration
Config File Location
- /etc/mongod.conf
Enable Remote Access
sudo nano /etc/mongod.conf
Change:
bindIp: 127.0.0.1
To:
bindIp: 0.0.0.0
sudo systemctl restart mongod
Warning: Do not enable remote access without security.
Enable Authentication
Create Admin User
mongosh
use admin
db.createUser({
user: "admin",
pwd: "StrongPassword",
roles: [ { role: "root", db: "admin" } ]
})
Enable Authorization
security:
authorization: enabled
sudo systemctl restart mongod
Login
mongosh -u admin -p --authenticationDatabase admin
Basic MongoDB Commands
show dbs
use mydb
db.createCollection("users")
db.users.insertOne({name: "John", age: 30})
db.users.find()
Troubleshooting
Check Logs
sudo journalctl -u mongod
Check Port
sudo lsof -i :27017
Fix Permissions
sudo chown -R mongod:mongod /var/lib/mongo
Conclusion
You have successfully installed MongoDB on Ubuntu and CentOS. You can now start building scalable applications using MongoDB.