BLOG POSTS
Install MongoDB on Linux – Step-by-Step Guide

Install MongoDB on Linux – Step-by-Step Guide

MongoDB is a popular NoSQL document database that’s become essential for modern web applications handling complex, unstructured data. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents, making it ideal for developers who need to iterate quickly and handle diverse data structures. This guide walks you through installing MongoDB Community Edition on various Linux distributions, configuring it properly, and getting it production-ready with security best practices and performance optimizations.

Understanding MongoDB Architecture

MongoDB uses a document-oriented data model where information is stored in BSON (Binary JSON) format. The database consists of collections (similar to tables) containing documents (similar to rows), but without the rigid schema requirements of SQL databases. This flexibility allows you to store nested objects, arrays, and varying field structures within the same collection.

The core MongoDB components include:

  • mongod – The primary database process
  • mongo – Interactive shell for database operations
  • mongos – Query router for sharded clusters
  • Configuration files – Control server behavior and security settings

Pre-Installation Requirements and System Preparation

Before installing MongoDB, ensure your Linux system meets the minimum requirements. MongoDB Community Edition supports most modern Linux distributions, but you’ll need at least 2GB of RAM and sufficient disk space for your data and logs.

First, update your system packages:

# For Ubuntu/Debian
sudo apt update && sudo apt upgrade -y

# For CentOS/RHEL/Fedora
sudo yum update -y
# Or for newer versions
sudo dnf update -y

Check your system architecture and available disk space:

uname -m
df -h
free -h

Installing MongoDB on Ubuntu/Debian

The most reliable method for installing MongoDB on Ubuntu/Debian systems is using the official MongoDB repository. This ensures you get the latest stable version with proper dependency management.

Import the MongoDB public GPG key:

wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add -

Add the MongoDB repository to your sources list:

# Ubuntu 22.04 (Jammy)
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

# Ubuntu 20.04 (Focal)
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

# Debian 11 (Bullseye)
echo "deb http://repo.mongodb.org/apt/debian bullseye/mongodb-org/6.0 main" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list

Update the package database and install MongoDB:

sudo apt update
sudo apt install -y mongodb-org

To prevent automatic updates that might cause compatibility issues, pin the MongoDB version:

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-selections

Installing MongoDB on CentOS/RHEL/Fedora

For Red Hat-based distributions, create a MongoDB repository file and install using yum or dnf.

Create the repository configuration file:

sudo tee /etc/yum.repos.d/mongodb-org-6.0.repo << EOF
[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
EOF

Install MongoDB:

# CentOS/RHEL 7
sudo yum install -y mongodb-org

# CentOS/RHEL 8+ or Fedora
sudo dnf install -y mongodb-org

Starting and Configuring MongoDB Service

After installation, start the MongoDB service and enable it to start automatically on boot:

sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod

If the service fails to start, check the logs for error messages:

sudo journalctl -u mongod
tail -f /var/log/mongodb/mongod.log

The default MongoDB configuration file is located at /etc/mongod.conf. Here's a basic configuration with security improvements:

# /etc/mongod.conf
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1,10.0.0.100  # Add your server's IP

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: enabled

Setting Up Authentication and Security

MongoDB installs without authentication enabled by default, which is a significant security risk. Always enable authentication for production deployments.

Connect to MongoDB shell and create an administrative user:

mongo

In the MongoDB shell, switch to the admin database and create a user with root privileges:

use admin
db.createUser({
  user: "admin",
  pwd: "your_secure_password_here",
  roles: ["root"]
})

exit

Edit the configuration file to enable authentication:

sudo nano /etc/mongod.conf

Add or uncomment the security section:

security:
  authorization: enabled

Restart MongoDB to apply the changes:

sudo systemctl restart mongod

Now connect using authentication:

mongo -u admin -p --authenticationDatabase admin

MongoDB vs Alternative Database Solutions

Feature MongoDB PostgreSQL MySQL CouchDB
Data Model Document (BSON) Relational + JSON Relational Document (JSON)
Schema Flexible Fixed Fixed Schema-less
Scaling Horizontal + Vertical Primarily Vertical Primarily Vertical Horizontal
ACID Compliance Document Level Full ACID Full ACID Eventually Consistent
Query Language JavaScript-like SQL SQL JavaScript/HTTP
Performance (Read) High Medium-High High Medium

Real-World Use Cases and Examples

MongoDB excels in several scenarios where traditional relational databases struggle:

  • Content Management Systems - Storing articles, comments, and user profiles with varying structures
  • Real-time Analytics - Logging application events and user behavior data
  • IoT Applications - Handling sensor data with different schemas from various devices
  • E-commerce Platforms - Managing product catalogs with diverse attributes
  • Social Media Applications - Storing user posts, relationships, and activity feeds

Here's a practical example of creating a collection and inserting sample data for a blog application:

// Connect to MongoDB
mongo -u admin -p --authenticationDatabase admin

// Create a new database
use blog_db

// Create a collection and insert sample posts
db.posts.insertMany([
  {
    title: "Getting Started with MongoDB",
    author: "John Doe",
    content: "MongoDB is a powerful NoSQL database...",
    tags: ["mongodb", "database", "nosql"],
    publishDate: new Date(),
    comments: [
      {
        author: "Jane Smith",
        comment: "Great article!",
        date: new Date()
      }
    ]
  },
  {
    title: "Advanced MongoDB Queries",
    author: "John Doe",
    content: "Learn how to write complex queries...",
    tags: ["mongodb", "queries", "advanced"],
    publishDate: new Date(),
    comments: []
  }
])

// Query examples
db.posts.find({"author": "John Doe"})
db.posts.find({"tags": "mongodb"})
db.posts.find({}, {"title": 1, "author": 1, "_id": 0})

Performance Optimization and Best Practices

MongoDB performance depends heavily on proper indexing, hardware configuration, and query optimization. Here are essential best practices:

Create indexes for frequently queried fields:

// Single field index
db.posts.createIndex({"author": 1})

// Compound index
db.posts.createIndex({"author": 1, "publishDate": -1})

// Text index for search
db.posts.createIndex({"title": "text", "content": "text"})

// Check existing indexes
db.posts.getIndexes()

Monitor MongoDB performance with built-in tools:

// Enable profiling for slow queries
db.setProfilingLevel(1, {slowms: 100})

// View profiling data
db.system.profile.find().limit(5).sort({ts: -1}).pretty()

// Database statistics
db.stats()
db.posts.stats()

Key performance considerations:

  • Memory - MongoDB performs best when working set fits in RAM
  • Storage - Use SSDs for better I/O performance
  • Indexes - Create selective indexes but avoid over-indexing
  • Connection Pooling - Configure appropriate connection pool sizes
  • Sharding - Distribute data across multiple servers for large datasets

Common Installation Issues and Troubleshooting

Several issues commonly occur during MongoDB installation and initial setup:

Service Won't Start:

# Check if port 27017 is already in use
sudo netstat -tlnp | grep 27017

# Verify database directory permissions
sudo chown -R mongodb:mongodb /var/lib/mongo
sudo chown mongodb:mongodb /tmp/mongodb-27017.sock

# Check disk space
df -h /var/lib/mongo

Authentication Issues:

# Reset MongoDB to no-auth mode temporarily
sudo nano /etc/mongod.conf
# Comment out: # authorization: enabled

sudo systemctl restart mongod

# Connect without auth and fix user issues
mongo
use admin
db.dropUser("admin")
db.createUser({user: "admin", pwd: "newpassword", roles: ["root"]})
exit

# Re-enable authentication
sudo nano /etc/mongod.conf
# Uncomment: authorization: enabled
sudo systemctl restart mongod

Connection Refused Errors:

# Check if MongoDB is listening on correct interface
sudo netstat -tlnp | grep mongod

# Verify firewall settings
sudo ufw allow 27017  # Ubuntu
sudo firewall-cmd --permanent --add-port=27017/tcp  # CentOS

Advanced Configuration and Security Hardening

For production deployments, implement additional security measures and performance optimizations:

# Enhanced /etc/mongod.conf configuration
storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true
  wiredTiger:
    engineConfig:
      cacheSizeGB: 4  # Adjust based on available RAM

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
  logRotate: reopen

net:
  port: 27017
  bindIp: 127.0.0.1,10.0.0.100
  maxIncomingConnections: 200

security:
  authorization: enabled
  javascriptEnabled: false  # Disable server-side JavaScript

operationProfiling:
  mode: slowOp
  slowOpThresholdMs: 100

processManagement:
  timeZoneInfo: /usr/share/zoneinfo
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid

Set up log rotation to prevent disk space issues:

sudo tee /etc/logrotate.d/mongodb << EOF
/var/log/mongodb/*.log {
    daily
    missingok
    rotate 52
    compress
    notifempty
    create 640 mongodb mongodb
    postrotate
        /bin/kill -SIGUSR1 \$(cat /var/run/mongodb/mongod.pid 2>/dev/null) 2>/dev/null || true
    endscript
}
EOF

Backup and Maintenance Strategies

Implement regular backup procedures to protect your data:

# Create backup directory
sudo mkdir -p /var/backups/mongodb

# Backup all databases
mongodump --host localhost --port 27017 -u admin -p --authenticationDatabase admin --out /var/backups/mongodb/$(date +%Y%m%d)

# Backup specific database
mongodump --host localhost --port 27017 -u admin -p --authenticationDatabase admin --db blog_db --out /var/backups/mongodb/blog_db_$(date +%Y%m%d)

# Restore from backup
mongorestore --host localhost --port 27017 -u admin -p --authenticationDatabase admin /var/backups/mongodb/20240101/

Create a automated backup script:

#!/bin/bash
# /usr/local/bin/mongodb-backup.sh

BACKUP_DIR="/var/backups/mongodb"
DATE=$(date +%Y%m%d_%H%M%S)
RETENTION_DAYS=7

# Create backup
mongodump --host localhost --port 27017 -u admin -p$MONGO_PASSWORD --authenticationDatabase admin --out $BACKUP_DIR/$DATE

# Compress backup
tar -czf $BACKUP_DIR/mongodb_backup_$DATE.tar.gz -C $BACKUP_DIR $DATE
rm -rf $BACKUP_DIR/$DATE

# Remove old backups
find $BACKUP_DIR -name "mongodb_backup_*.tar.gz" -mtime +$RETENTION_DAYS -delete

echo "Backup completed: mongodb_backup_$DATE.tar.gz"

MongoDB provides excellent scalability and flexibility for modern applications, especially when handling diverse data structures. Whether you're running a VPS for development or need dedicated servers for production workloads, proper MongoDB installation and configuration ensure optimal performance and security. The key to success lies in understanding your data access patterns, implementing appropriate indexes, and maintaining regular backup procedures.

For additional information and advanced configuration options, refer to the official MongoDB installation documentation and the production deployment guidelines.



This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.

This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.

Leave a reply

Your email address will not be published. Required fields are marked