Database Guide

    Self-Hosted MongoDB

    Deploy MongoDB, the leading NoSQL document database, on RamNode VPS. Flexible schema design, horizontal scaling, and powerful querying capabilities.

    Ubuntu/Debian
    MongoDB 7.0
    ⏱️ 15-20 minutes

    Prerequisites & VPS Selection

    Development

    • • 2GB RAM
    • • 2 vCPU
    • • Small datasets

    Production

    • • 4GB+ RAM
    • • 4 vCPU
    • • Medium workloads

    High Performance

    • • 8GB+ RAM
    • • 8 vCPU
    • • Large datasets

    What You'll Need

    • Ubuntu 22.04/24.04 or Debian 11/12
    • Root or sudo access
    • Adequate disk space for your data
    • Basic understanding of database concepts
    2

    Install MongoDB

    Install MongoDB Community Edition from the official repository:

    Import MongoDB GPG Key
    sudo apt-get 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
    Add MongoDB Repository (Ubuntu 22.04)
    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

    💡 For Ubuntu 24.04: Replace jammy with noble in the repository URL.

    Install MongoDB
    sudo apt-get update
    sudo apt-get install -y mongodb-org
    Start and Enable MongoDB
    sudo systemctl start mongod
    sudo systemctl enable mongod
    sudo systemctl status mongod
    Verify Installation
    mongod --version
    mongosh --eval 'db.runCommand({ connectionStatus: 1 })'
    3

    Configure MongoDB

    Configure MongoDB for your environment:

    /etc/mongod.conf
    # mongod.conf
    
    # Data storage
    storage:
      dbPath: /var/lib/mongodb
      journal:
        enabled: true
      wiredTiger:
        engineConfig:
          cacheSizeGB: 1  # Adjust based on RAM (50% of available)
    
    # Network interfaces
    net:
      port: 27017
      bindIp: 127.0.0.1  # Change to 0.0.0.0 for remote access
    
    # Process Management
    processManagement:
      timeZoneInfo: /usr/share/zoneinfo
    
    # Security
    security:
      authorization: enabled
    
    # Operation Profiling
    operationProfiling:
      mode: slowOp
      slowOpThresholdMs: 100
    
    # Logging
    systemLog:
      destination: file
      logAppend: true
      path: /var/log/mongodb/mongod.log

    ⚠️ WiredTiger Cache: Set cacheSizeGB to about 50% of your available RAM minus 1GB for optimal performance.

    Apply Configuration Changes
    sudo systemctl restart mongod
    4

    Security Setup

    Create an admin user and enable authentication:

    Connect to MongoDB Shell
    mongosh
    Create Admin User
    use admin
    db.createUser({
      user: "admin",
      pwd: passwordPrompt(),  // Prompts for password
      roles: [
        { role: "userAdminAnyDatabase", db: "admin" },
        { role: "readWriteAnyDatabase", db: "admin" },
        { role: "dbAdminAnyDatabase", db: "admin" },
        { role: "clusterAdmin", db: "admin" }
      ]
    })
    Create Application Database User
    use myapp
    db.createUser({
      user: "appuser",
      pwd: passwordPrompt(),
      roles: [
        { role: "readWrite", db: "myapp" }
      ]
    })

    Best Practice: Create separate users for each application with minimal required permissions.

    Test Authentication
    # Exit mongosh and reconnect with authentication
    mongosh -u admin -p --authenticationDatabase admin
    5

    Firewall Configuration

    Configure UFW to protect MongoDB:

    Configure Firewall
    # Install UFW if not present
    sudo apt install -y ufw
    
    # Allow SSH first!
    sudo ufw allow 22/tcp
    
    # Allow MongoDB only from specific IPs (recommended)
    sudo ufw allow from YOUR_APP_SERVER_IP to any port 27017
    
    # Or allow from any (less secure)
    # sudo ufw allow 27017/tcp
    
    # Enable firewall
    sudo ufw enable
    sudo ufw status

    ⚠️ Security Warning: Never expose MongoDB port 27017 to the public internet without authentication and IP restrictions!

    6

    Connect to MongoDB

    Various ways to connect to your MongoDB instance:

    MongoDB Shell

    Local Connection
    mongosh -u admin -p --authenticationDatabase admin

    Connection String

    mongodb://admin:password@localhost:27017/admin
    Basic MongoDB Operations
    # Show databases
    show dbs
    
    # Use a database (creates if doesn't exist)
    use myapp
    
    # Insert a document
    db.users.insertOne({
      name: "John Doe",
      email: "john@example.com",
      created: new Date()
    })
    
    # Find documents
    db.users.find()
    
    # Create an index
    db.users.createIndex({ email: 1 }, { unique: true })
    7

    Enable Remote Access

    Configure MongoDB for secure remote connections:

    Update mongod.conf for Remote Access
    # In /etc/mongod.conf, change:
    net:
      port: 27017
      bindIp: 0.0.0.0  # Listen on all interfaces
      # Or specific IPs: 127.0.0.1,192.168.1.100
    Restart MongoDB
    sudo systemctl restart mongod

    Remote Connection String

    mongodb://appuser:password@YOUR_SERVER_IP:27017/myapp

    💡 TLS/SSL: For production, configure TLS encryption for connections. See MongoDB documentation for certificate setup.

    8

    Replica Set Setup (Optional)

    Set up a replica set for high availability (requires multiple servers):

    Enable Replication in mongod.conf
    # Add to /etc/mongod.conf on all nodes:
    replication:
      replSetName: "rs0"
    Initialize Replica Set
    # On the primary node, connect to mongosh:
    rs.initiate({
      _id: "rs0",
      members: [
        { _id: 0, host: "mongo1.example.com:27017" },
        { _id: 1, host: "mongo2.example.com:27017" },
        { _id: 2, host: "mongo3.example.com:27017" }
      ]
    })
    
    # Check replica set status
    rs.status()

    Replica Set Benefits

    • High Availability: Automatic failover if primary goes down
    • Data Redundancy: Data replicated across nodes
    • Read Scaling: Distribute reads across secondaries
    9

    Backup Strategy

    Implement a robust backup strategy:

    mongodump Backup
    # Backup all databases
    mongodump --uri="mongodb://admin:password@localhost:27017" \
      --authenticationDatabase=admin \
      --out=/backups/mongodb/$(date +%Y%m%d_%H%M%S)
    
    # Backup specific database
    mongodump --uri="mongodb://admin:password@localhost:27017/myapp" \
      --authenticationDatabase=admin \
      --out=/backups/mongodb/myapp_$(date +%Y%m%d)
    Automated Backup Script
    #!/bin/bash
    # /opt/mongodb/backup.sh
    
    BACKUP_DIR="/backups/mongodb"
    DATE=$(date +%Y%m%d_%H%M%S)
    MONGO_USER="admin"
    MONGO_PASS="your_password"
    
    # Create backup directory
    mkdir -p $BACKUP_DIR
    
    # Run backup
    mongodump --uri="mongodb://$MONGO_USER:$MONGO_PASS@localhost:27017" \
      --authenticationDatabase=admin \
      --out=$BACKUP_DIR/$DATE
    
    # Compress backup
    tar -czf $BACKUP_DIR/$DATE.tar.gz -C $BACKUP_DIR $DATE
    rm -rf $BACKUP_DIR/$DATE
    
    # Keep only last 7 days of backups
    find $BACKUP_DIR -name "*.tar.gz" -mtime +7 -delete
    
    echo "Backup completed: $DATE.tar.gz"
    Setup Automated Backups
    chmod +x /opt/mongodb/backup.sh
    mkdir -p /backups/mongodb
    
    # Add to crontab (daily at 2 AM)
    (crontab -l 2>/dev/null; echo "0 2 * * * /opt/mongodb/backup.sh") | crontab -
    Restore from Backup
    # Extract backup
    tar -xzf /backups/mongodb/20241217_020000.tar.gz -C /tmp
    
    # Restore
    mongorestore --uri="mongodb://admin:password@localhost:27017" \
      --authenticationDatabase=admin \
      /tmp/20241217_020000
    10

    Performance Tuning

    Optimize MongoDB for better performance:

    Index Optimization

    Analyze Query Performance
    # Explain a query
    db.collection.find({ field: "value" }).explain("executionStats")
    
    # Find slow queries
    db.system.profile.find({ millis: { $gt: 100 } }).sort({ ts: -1 })
    
    # List all indexes
    db.collection.getIndexes()
    
    # Create compound index
    db.users.createIndex({ status: 1, created: -1 })

    System Optimizations

    Linux System Settings
    # Disable Transparent Huge Pages
    echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
    echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
    
    # Increase file descriptors
    echo "mongod soft nofile 64000" | sudo tee -a /etc/security/limits.conf
    echo "mongod hard nofile 64000" | sudo tee -a /etc/security/limits.conf
    
    # Set swappiness
    echo "vm.swappiness = 1" | sudo tee -a /etc/sysctl.conf
    sudo sysctl -p

    WiredTiger Cache

    Adjust cache size based on your workload:

    • • 4GB RAM → 1.5GB cache
    • • 8GB RAM → 3.5GB cache
    • • 16GB RAM → 7GB cache
    11

    Monitoring

    Monitor MongoDB health and performance:

    Built-in Monitoring Commands
    # Server status
    db.serverStatus()
    
    # Current operations
    db.currentOp()
    
    # Database stats
    db.stats()
    
    # Collection stats
    db.collection.stats()
    
    # Replication status (replica sets)
    rs.status()
    
    # Connection pool stats
    db.serverStatus().connections

    Key Metrics to Monitor

    • • Connections (current/available)
    • • Operations per second
    • • Query execution time
    • • Replication lag
    • • Memory usage
    • • Cache hit ratio
    • • Disk I/O
    • • Index usage

    💡 Pro Tip: Consider using MongoDB Compass (GUI) or integrate with Prometheus + Grafana for comprehensive monitoring dashboards.

    12

    Troubleshooting

    MongoDB Won't Start

    Check Logs and Status
    sudo systemctl status mongod
    sudo journalctl -u mongod -f
    sudo tail -100 /var/log/mongodb/mongod.log
    
    # Check for lock file issues
    sudo rm /var/lib/mongodb/mongod.lock
    sudo mongod --repair --dbpath /var/lib/mongodb
    sudo chown -R mongodb:mongodb /var/lib/mongodb

    Connection Refused

    Debug Connection Issues
    # Check if MongoDB is listening
    sudo netstat -tlnp | grep 27017
    
    # Check bindIp in config
    grep bindIp /etc/mongod.conf
    
    # Test local connection
    mongosh --eval "db.adminCommand('ping')"
    
    # Check firewall
    sudo ufw status

    Authentication Failed

    Reset Admin Password
    # Temporarily disable auth in mongod.conf
    # Comment out: authorization: enabled
    sudo systemctl restart mongod
    
    # Connect and update password
    mongosh
    use admin
    db.changeUserPassword("admin", "newpassword")
    
    # Re-enable auth and restart
    sudo systemctl restart mongod

    High Memory Usage

    Check Memory Stats
    # Check WiredTiger cache usage
    db.serverStatus().wiredTiger.cache
    
    # Reduce cache size in mongod.conf
    # storage.wiredTiger.engineConfig.cacheSizeGB: 1

    MongoDB Deployed Successfully!

    Your MongoDB database is now running securely. Start building your applications with flexible document storage.