MongoDB Installation on Linux

MongoDB is a popular document-oriented NoSQL database known for its flexibility and scalability. This tutorial covers installing and configuring MongoDB Community Edition on Ubuntu and RHEL-based systems.

Prerequisites

  • Ubuntu 20.04/22.04 LTS or RHEL/Rocky Linux 8/9
  • Root or sudo privileges
  • Minimum 2GB RAM (4GB+ recommended for production)
  • At least 10GB of free disk space
  • Basic knowledge of Linux command line
Ubuntu/Debian
RHEL/CentOS

1 Import MongoDB Public GPG Key

First, import the MongoDB public GPG key to verify package authenticity:

sudo apt-get install gnupg curl
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | \
   sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg \
   --dearmor

2 Create MongoDB Repository List File

Create the MongoDB repository list file for Ubuntu:

echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu $(lsb_release -cs)/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list

3 Update Package List and Install MongoDB

Update your package list and install MongoDB:

sudo apt-get update
sudo apt-get install -y mongodb-org

To install a specific version of MongoDB:

sudo apt-get install -y mongodb-org=7.0.2 mongodb-org-database=7.0.2 mongodb-org-server=7.0.2 mongodb-mongosh=7.0.2 mongodb-org-mongos=7.0.2 mongodb-org-tools=7.0.2

4 Prevent Unintentional Upgrades

Pin the package to prevent unintended upgrades:

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-mongosh hold" | sudo dpkg --set-selections
echo "mongodb-org-mongos hold" | sudo dpkg --set-selections
echo "mongodb-org-tools hold" | sudo dpkg --set-selections

5 Start MongoDB Service

Start the MongoDB service and enable it to start on boot:

sudo systemctl start mongod
sudo systemctl enable mongod

Check the service status:

sudo systemctl status mongod

6 Verify MongoDB Installation

Connect to MongoDB to verify the installation:

mongosh

Run a test command in the MongoDB shell:

db.runCommand({ connectionStatus: 1 })

Exit the MongoDB shell:

exit

7 Configure MongoDB

Edit the MongoDB configuration file:

sudo nano /etc/mongod.conf

Key configuration options to consider:

# Network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1  # Change to 0.0.0.0 for remote access

# Storage
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

# Security
security:
  authorization: enabled  # Enable authentication

# Process management
processManagement:
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid

Restart MongoDB to apply changes:

sudo systemctl restart mongod

8 Create Admin User

Connect to MongoDB without authentication first:

mongosh

Switch to the admin database and create an admin user:

use admin
db.createUser(
  {
    user: "adminUser",
    pwd: "securePassword",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
exit

Enable authentication in the config file and restart MongoDB:

sudo nano /etc/mongod.conf

Add or uncomment the security section:

security:
  authorization: enabled

Restart MongoDB:

sudo systemctl restart mongod

9 Configure Firewall

Allow MongoDB through the firewall (default port 27017):

sudo ufw allow 27017
sudo ufw enable
sudo ufw status
Security Note: Only open port 27017 to trusted IP addresses in production environments. Consider using VPN or SSH tunneling for remote access.

10 Basic MongoDB Operations

Connect to MongoDB with authentication:

mongosh -u adminUser -p --authenticationDatabase admin

Create a new database and collection:

use mydatabase
db.createCollection("users")
db.users.insertOne({name: "John Doe", email: "john@example.com", age: 30})
db.users.find()

Common administrative commands:

# Show databases
show dbs

# Show collections in current database
show collections

# Get statistics about current database
db.stats()

# Get server status
db.serverStatus()

1 Create MongoDB Repository File

Create a MongoDB repository file for yum:

sudo nano /etc/yum.repos.d/mongodb-org-7.0.repo

Add the following content to the file:

[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://pgp.mongodb.com/server-7.0.asc

2 Install MongoDB

Install MongoDB using yum or dnf:

# For RHEL 8/9, Rocky Linux, AlmaLinux
sudo dnf install -y mongodb-org

# For CentOS 7
sudo yum install -y mongodb-org

To install a specific version of MongoDB:

sudo dnf install -y mongodb-org-7.0.2 mongodb-org-database-7.0.2 mongodb-org-server-7.0.2 mongodb-mongosh-7.0.2 mongodb-org-mongos-7.0.2 mongodb-org-tools-7.0.2

3 Prevent Unintentional Upgrades

Add an exclude directive to prevent unintended upgrades:

# Add to /etc/yum.conf or /etc/dnf/dnf.conf
echo "exclude=mongodb-org,mongodb-org-database,mongodb-org-server,mongodb-mongosh,mongodb-org-mongos,mongodb-org-tools" | sudo tee -a /etc/yum.conf

4 Start MongoDB Service

Start the MongoDB service and enable it to start on boot:

sudo systemctl start mongod
sudo systemctl enable mongod

Check the service status:

sudo systemctl status mongod

5 Configure SELinux for MongoDB

If SELinux is enabled, configure it for MongoDB:

# Check SELinux status
sestatus

# If enforcing, adjust SELinux policies
sudo semanage port -a -t mongod_port_t -p tcp 27017

# Or set permissive mode for MongoDB (not recommended for production)
sudo setsebool -P mongod_can_connect_ldap 1

6 Configure Firewall

Allow MongoDB through the firewall:

sudo firewall-cmd --zone=public --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
Security Note: For production environments, consider restricting access to specific IP addresses only.

7 MongoDB Configuration

Edit the MongoDB configuration file:

sudo nano /etc/mongod.conf

Key configuration options for RHEL-based systems:

# Where and how to store data.
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

# Where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# Network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1  # Change to 0.0.0.0 for remote access

# Security configuration
security:
  authorization: enabled

Restart MongoDB to apply changes:

sudo systemctl restart mongod

8 Create Admin User

Connect to MongoDB and create an admin user:

mongosh

Switch to the admin database and create user:

use admin
db.createUser(
  {
    user: "adminUser",
    pwd: "securePassword",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
exit

9 Performance Tuning

Adjust system limits for better MongoDB performance:

# Edit limits configuration
sudo nano /etc/security/limits.d/mongodb.conf

Add the following content:

mongod soft nofile 64000
mongod hard nofile 64000
mongod soft nproc 64000
mongod hard nproc 64000

Adjust kernel parameters:

# Edit sysctl configuration
sudo nano /etc/sysctl.d/mongodb.conf

Add the following content:

vm.swappiness = 1
net.core.somaxconn = 4096
vm.max_map_count = 262144

Apply the changes:

sudo sysctl -p /etc/sysctl.d/mongodb.conf

10 Backup and Restore

Create a backup of a MongoDB database:

mongodump --uri="mongodb://adminUser:securePassword@localhost:27017" --db=myDatabase --out=/backup/mongodb/

Restore a MongoDB database from backup:

mongorestore --uri="mongodb://adminUser:securePassword@localhost:27017" --db=myDatabase /backup/mongodb/myDatabase/

Create a backup script:

sudo nano /usr/local/bin/mongodb-backup.sh

Add the following content:

#!/bin/bash
# MongoDB backup script
DATE=$(date +%Y-%m-%d_%H-%M-%S)
BACKUP_DIR="/backup/mongodb"
MONGODB_URI="mongodb://adminUser:securePassword@localhost:27017"

# Create backup directory if it doesn't exist
mkdir -p $BACKUP_DIR

# Backup all databases
mongodump --uri="$MONGODB_URI" --out="$BACKUP_DIR/$DATE"

# Delete backups older than 30 days
find $BACKUP_DIR -type d -name "*-*-*_*-*-*" -mtime +30 -exec rm -rf {} +

Make the script executable:

sudo chmod +x /usr/local/bin/mongodb-backup.sh
Command copied to clipboard!