Ensure you have the following installed:
- A Linux-based operating system (Ubuntu/Debian)
sudoprivileges on your machine
sudo apt update
sudo apt upgrade -yAdd the MongoDB APT repository and install MongoDB:
sudo apt install -y gnupg curl
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
--dearmor
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt update
sudo apt install -y mongodb-orgStart the MongoDB service and enable it to start on boot:
sudo systemctl start mongod
sudo systemctl enable mongodOpen the MongoDB configuration file using nano:
sudo nano /etc/mongod.confAdd or modify the following configuration settings:
# Where and how to store data.
storage:
dbPath: /var/lib/mongodb
# Where to write logging data.
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# Network interfaces
net:
bindIp: 0.0.0.0
port: 27017
# How the process runs
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: "enabled"Save and close the file (Ctrl + X, then Y, then Enter).
Ensure that MongoDB has the proper permissions to access its directories:
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodbApply the configuration changes by restarting MongoDB:
sudo systemctl restart mongodOpen the MongoDB shell (mongosh):
mongoshSwitch to the admin database and create a user with root privileges:
use admin
db.createUser({
user: "root",
pwd: "root",
roles: [
{ role: "root", db: "admin" },
{ role: "clusterMonitor", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "userAdminAnyDatabase", db: "admin" }
]
})Authenticate with the new user:
db.auth("root", "root")Check the created users:
db.getUsers()
db.getUser("root")Verify that MongoDB is running correctly:
sudo systemctl status mongod- MongoDB Not Starting: Check logs in
/var/log/mongodb/mongod.logfor errors. - Authentication Issues: Ensure the user credentials are correct and that you are connecting to the correct database.
MongoDB is now installed, configured, and secured with user authentication. You can now start using MongoDB for your applications.
https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/