Report this

What is the reason for this report?

How To Install MongoDB on Ubuntu

Updated on January 8, 2026
English

Not using Ubuntu 20.04?
Choose a different version or distribution.
Ubuntu 20.04
How To Install MongoDB on Ubuntu

Introduction

MongoDB is one of the most popular open-source NoSQL databases, widely used for applications that require flexible data structures, high scalability, and fast performance. It stores data in a document-oriented format using JSON-like objects, which makes it ideal for modern web, mobile, and analytics workloads. Developers favor MongoDB for its dynamic schema, automatic sharding, and built-in replication features that support both horizontal scaling and high availability. When combined with the stability and security of Ubuntu, MongoDB provides a strong foundation for running reliable and efficient database-driven applications.

In this article, we explain how to install, configure, and maintain MongoDB 8.2 on Ubuntu 24.04 LTS. We cover every essential step, from preparing the server and enabling security features to optimizing performance, setting up replication and backups, and troubleshooting common issues. By the end, you will have a production-ready MongoDB deployment that is properly secured, monitored, and tuned for long-term use. Whether you are setting up MongoDB for development, testing, or a full production environment, this guide provides the detailed instructions and operational best practices needed to run it effectively.

Key Takeaways:

  • Use the official MongoDB repository to install the latest stable version instead of relying on Ubuntu’s default repositories, which contain outdated packages.
  • Manage MongoDB as a systemd service using standard commands like systemctl start mongod and systemctl enable mongod to control and monitor the database process.
  • Understand and configure /etc/mongod.conf carefully, as it defines critical settings for storage, logging, networking, security, and replication.
  • Secure your MongoDB deployment by enabling authentication, limiting network access, configuring a firewall, and enabling TLS encryption for data in transit.
  • Follow routine maintenance practices, including regular backups, system monitoring, and log rotation, to keep the database reliable and prevent data loss.
  • Scale MongoDB appropriately by using replica sets for high availability or sharding for handling large datasets and distributed workloads.
  • Choose between self-hosted and managed deployments based on your needs: self-hosted MongoDB offers full control, while managed services like MongoDB Atlas simplify scaling and maintenance.
  • Use MongoDB’s diagnostic tools and logs for troubleshooting, such as mongostat, mongotop, and system logs, to identify and resolve performance, connection, or authentication issues efficiently.

Prerequisites

To follow this tutorial, you will need:

Installing MongoDB from the Official Repository

Ubuntu 24.04 includes a version of MongoDB in its default package repositories, but it’s usually outdated. For production systems, you should always install MongoDB directly from the official MongoDB repository. This ensures you get the latest stable version (8.2 at the time of writing) along with timely security and maintenance updates.

Let’s add the MongoDB repository to your system’s APT sources, import the GPG key used to verify packages, and then install the database.

1. Import the MongoDB GPG Key

APT uses GPG keys to verify the authenticity of packages. Without this, your system won’t trust MongoDB’s repository.

Run the following command to import the public key for MongoDB 8.0:

  1. curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg --dearmor

Here’s what this does:

  • curl -fsSL quietly fetches the GPG key from MongoDB’s official servers.
  • --dearmor converts the key from ASCII-armored format into a binary keyring format compatible with APT.
  • The output is saved in /usr/share/keyrings/mongodb-server-8.0.gpg, a standard location for trusted keys.

If the command completes without errors, the key has been successfully added.

2. Add the MongoDB Repository

Next, create a new repository list file that points to MongoDB’s official package source for Ubuntu 24.04 (“Noble”).

  1. echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.2 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.2.list

Each part of this command serves a clear purpose:

  • deb tells APT this is a binary package repository (as opposed to deb-src for source code).
  • arch=amd64,arm64 limits it to 64-bit Intel/AMD and ARM architectures supported by MongoDB.
  • signed-by=... ensures APT uses the specific MongoDB key (added above) to verify downloads.
  • https://repo.mongodb.org/apt/ubuntu is the base URL of MongoDB’s official APT repository.
  • noble/mongodb-org/8.2 specifies both the Ubuntu release codename (noble = Ubuntu 24.04) and the MongoDB version (8.2).
  • multiverse is the Ubuntu component section for third-party software.

3. Update Your Package Index

After adding a new repository, you must refresh your system’s local list of available packages so APT recognizes the new source:

  1. sudo apt update

APT will download the latest package lists and verify them using the GPG key. If you see MongoDB listed among the repositories, your configuration is correct.

4. Install MongoDB

Now install MongoDB and its associated tools:

  1. sudo apt install -y mongodb-org

The -y flag automatically confirms the installation prompts.

This will install a set of related packages, including:

  • mongodb-org-server: The MongoDB server daemon (mongod), responsible for database storage and operations.
  • mongodb-org-mongos: The sharding router used in distributed deployments.
  • mongodb-org-shell: The interactive command-line client (mongosh) used to connect to MongoDB.
  • mongodb-org-tools: Backup and restore utilities (mongodump, mongorestore, bsondump, etc.).

Once installed, the binaries are placed under /usr/bin/, and configuration files are located in /etc/mongod.conf.

5. Verify the Installation

You can verify that MongoDB 8.2 was installed successfully by checking its version:

  1. mongod --version

You should see an output similar to:

db version v8.2.3
Build Info: {
    "version": "8.2.3",
    "gitVersion": "36f41c9c30a2f13f834d033ba03c3463c891fb01",
    "openSSLVersion": "OpenSSL 3.0.13 30 Jan 2024",
    "modules": [],
    "allocator": "tcmalloc-google",
    "environment": {
        "distmod": "ubuntu2404",
        "distarch": "x86_64",
        "target_arch": "x86_64"
    }
}

If you see this, MongoDB is installed correctly and ready to be started as a service.

Starting and Managing the MongoDB Service

When you install MongoDB on Ubuntu, the package automatically includes a systemd service unit named mongod.service. This integration allows MongoDB to start, stop, and restart cleanly using Ubuntu’s standard service management commands, just like Nginx, PostgreSQL, or any other major daemon.

Start the MongoDB Service

By default, MongoDB doesn’t start automatically after installation. To launch it manually, use the following command:

  1. sudo systemctl start mongod

If the command runs without error, the service should now be active. You can confirm with:

  1. sudo systemctl status mongod

Example output:

● mongod.service - MongoDB Database Server
     Loaded: loaded (/usr/lib/systemd/system/mongod.service; disabled; preset: enabled)
     Active: active (running) since Tue 2026-01-06 07:08:28 UTC; 5s ago
       Docs: https://docs.mongodb.org/manual
   Main PID: 12462 (mongod)
     Memory: 195.4M (peak: 277.1M)
        CPU: 739ms
     CGroup: /system.slice/mongod.service
             └─12462 /usr/bin/mongod --config /etc/mongod.conf

The line “Active: active (running)” confirms the database is up and functioning.

If you instead see “failed” or “inactive”, skip ahead to the Checking MongoDB Logs section to troubleshoot.

Enable MongoDB to Start at Boot

Most production systems require the database to start automatically after a reboot. To enable MongoDB to launch on boot, run:

  1. sudo systemctl enable mongod

This creates a symbolic link in /etc/systemd/system/multi-user.target.wants/, telling systemd to start the service automatically whenever the system enters multi-user mode (the standard operating mode for servers).

You can confirm the change with:

  1. systemctl is-enabled mongod

Expected output:

enabled

If you ever want to disable automatic startup (for maintenance or testing), use:

  1. sudo systemctl disable mongod

Verify MongoDB Operation

Once MongoDB is running, it’s a good idea to confirm it’s responding properly.

Run the following command to connect to the database and check its connection status:

  1. mongosh --eval "db.runCommand({ connectionStatus: 1 })"

This command:

  • Opens a temporary shell session (mongosh is the new MongoDB shell, replacing the older mongo client).
  • Runs the connectionStatus command directly against the local instance.
  • Displays the connection result without requiring you to stay in the shell.

Example output:

{
  authInfo: { authenticatedUsers: [], authenticatedUserRoles: [] },
  uuid: UUID('be686f2a-9cb3-41c1-aad2-8849367de4e5'),
  ok: 1
}

A value of "ok": 1 confirms the server is working correctly and accepting connections on port 27017.

Manage the MongoDB Service Lifecycle

Once you’ve verified MongoDB is running, it’s helpful to know how to manage it safely in day-to-day operations.

Here are the key commands:

Command Description
sudo systemctl stop mongod Gracefully stops the MongoDB service.
sudo systemctl start mongod Starts the service if it’s stopped.
sudo systemctl restart mongod Restarts the service (useful after configuration changes).
sudo systemctl reload mongod Reloads configuration without a full restart (limited scenarios).
sudo systemctl disable mongod Prevents the service from starting automatically at boot.
sudo systemctl status mongod Shows current status and recent logs.

Restarting the service (restart) is particularly important after editing /etc/mongod.conf. This ensures your configuration changes are loaded.

Checking MongoDB Logs

If MongoDB fails to start or behaves unexpectedly, your first troubleshooting step should be checking the logs.

MongoDB logs are located at:

/var/log/mongodb/mongod.log

You can view the last 20 lines with:

  1. sudo tail -n 20 /var/log/mongodb/mongod.log

Common log messages include:

  • "Waiting for connections on port 27017": MongoDB started successfully and is ready.
  • "Data directory /var/lib/mongodb not found": Check that the data path exists and has correct permissions.
  • "Address already in use": Another process is already using port 27017.
  • "Permission denied": Ensure the MongoDB user (mongodb) owns its data and log directories.

You can also use journalctl to view service-specific logs managed by systemd:

  1. sudo journalctl -u mongod --since "5 minutes ago"

Testing MongoDB on System Startup

It’s good practice to verify that MongoDB starts automatically after a reboot, especially before deploying applications.

To reboot, run:

  1. sudo reboot

After your server restarts, log back in and check the service:

  1. sudo systemctl status mongod

If it shows “active (running)”, your configuration is correct and persistent.

Understanding MongoDB Configuration Settings

When you install MongoDB, its behavior is controlled by a single configuration file located at /etc/mongod.conf.

This file defines how MongoDB runs: everything from where it stores data, to how it logs activity, which IP addresses it listens on, and what security mechanisms are active. Understanding this file is critical, especially if you plan to run MongoDB in production. Settings in this file are equivalent to corresponding command-line options, but using a configuration file makes server management simpler, especially for larger or automated deployments.

Overview of the Configuration File

MongoDB’s configuration file uses YAML syntax, which is indentation-sensitive. That means you must use spaces (not tabs) when editing it, even one misplaced space can break the configuration.

You can view the file’s current contents with:

  1. sudo cat /etc/mongod.conf

The default file looks something like this:

# mongod.conf

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

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

net:
  port: 27017
  bindIp: 127.0.0.1

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

Let’s break this down section by section.

The storage Section

This section defines where MongoDB stores its data and how it manages journaling (which ensures data durability).

storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
  • dbPath: This is the directory where MongoDB stores its databases, collections, and indexes. By default, it points to /var/lib/mongodb. If you change this path, make sure the directory exists and is owned by the mongodb user:

    1. sudo mkdir -p /data/mongodb
    2. sudo chown -R mongodb:mongodb /data/mongodb
  • journal.enabled: When set to true, MongoDB maintains a journal file that helps recover from crashes or unexpected shutdowns. Journaling writes changes to a separate log before committing them to the data files, preventing corruption. Always keep this enabled for production systems.

Tip: With WiredTiger, separating the journal onto another disk generally does not improve performance. This optimization was relevant for older storage engines but is no longer recommended.

The systemLog Section

This controls how and where MongoDB writes its logs.

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log
  • destination: Specifies where logs are written. The default value file writes logs to a file; you can change it to syslog if you want MongoDB logs integrated with your system logs.
  • logAppend: When true, MongoDB appends new log entries to the existing file rather than overwriting it on restart.
  • path: The absolute path of the log file.

You can view logs directly with:

  1. sudo tail -f /var/log/mongodb/mongod.log

If your logs grow too large, consider enabling log rotation with a tool like logrotate or configuring your system logs to rotate automatically.

The net Section

This section defines how MongoDB listens for incoming network connections.

net:
  port: 27017
  bindIp: 127.0.0.1
  • port: The default MongoDB port is 27017. You can change this if you’re running multiple database services on the same host.
  • bindIp: This controls which network interfaces MongoDB listens on.

By default, it’s limited to 127.0.0.1 (the local loopback address), meaning only local connections are accepted. This is a critical security default that prevents remote access until you explicitly allow it.

If you plan to connect from another machine (for example, a web server or remote application), you can modify it as:

bindIp: 127.0.0.1,192.168.1.100

Or, to listen on all interfaces (use cautiously in production):

bindIp: 0.0.0.0

Security Note: If you enable remote access, always enable authentication and firewall rules to restrict which IPs can connect.

The security Section

MongoDB installs with authentication disabled by default. Anyone who can connect to the database can read or modify data. That’s fine for testing, but a security threat for any real system. To enable user-based authentication, add the following section:

security:
  authorization: enabled

Once this is enabled, MongoDB will require users to authenticate with a username and password before performing operations.

You’ll configure authentication in detail in the Securing MongoDB section.

Other optional settings in this section include:

  • keyFile: Used for replica sets to authenticate between cluster nodes.
  • javascriptEnabled: Enables or disables server-side JavaScript execution (recommended to keep disabled unless necessary).

The processManagement Section

This section controls how MongoDB handles process management and runtime information.

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

This is mostly informational; it ensures that MongoDB has access to timezone data for timestamp conversions. In advanced deployments, you can also enable forking here (for background operation) if MongoDB is started manually without systemd.

The replication and sharding Sections (Optional)

You won’t see these sections in a fresh installation, but they’re used in multi-node or distributed setups.

Example for enabling a replica set:

replication:
  replSetName: "rs0"

This tells MongoDB to start as part of a replica set named rs0. You’d then initialize and add members from within the MongoDB shell.

For sharding:

sharding:
  clusterRole: "shardsvr"

This defines the node’s role in a sharded cluster.

The setParameter Section

This optional section allows you to override runtime parameters that fine-tune MongoDB’s behavior.

Example:

setParameter:
  enableLocalhostAuthBypass: false

Setting this to false ensures that even localhost connections require authentication. Other parameters can control query timeouts, cursor behavior, or diagnostic logging.

Making and Applying Changes

Whenever you modify /etc/mongod.conf, you need to restart MongoDB for the changes to take effect:

  1. sudo systemctl restart mongod

Then verify the service is running:

  1. sudo systemctl status mongod

If MongoDB fails to restart, check for syntax errors (YAML indentation mistakes are common) or review the logs:

  1. sudo tail -n 20 /var/log/mongodb/mongod.log

Example: A Secure and Production-Ready Configuration

Here’s an example of a clean, production-oriented mongod.conf for Ubuntu 24.04:

# mongod.conf — Example production configuration

storage:
  dbPath: /data/mongodb
  journal:
    enabled: true
  engine: wiredTiger

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

net:
  port: 27017
  bindIp: 127.0.0.1,192.168.10.10

security:
  authorization: enabled
  javascriptEnabled: false

processManagement:
  timeZoneInfo: /usr/share/zoneinfo

replication:
  replSetName: "rs0"

setParameter:
  enableLocalhostAuthBypass: false

This configuration:

  • Enables authentication
  • Uses WiredTiger (the default storage engine)
  • Binds only to specific trusted interfaces
  • Prepares the instance for replica set initialization
  • Logs all operations to a dedicated log file

Securing MongoDB

MongoDB’s flexibility makes it powerful, but it also means that an insecure setup can easily lead to data exposure. In the early days of MongoDB, many servers were left open to the internet without authentication, allowing attackers to list, modify, or even delete databases simply by connecting to port 27017.

Today, MongoDB ships with safer defaults, but it’s still up to you to enforce authentication, network restrictions, and encryption.

Enabling Authentication

By default, MongoDB starts with authentication disabled. That means anyone who can connect to the database can run administrative commands, drop collections, or modify data without restriction. To prevent this, MongoDB uses a Role-Based Access Control (RBAC) system that you enable explicitly.

  1. Open the MongoDB configuration file:

    1. sudo nano /etc/mongod.conf
  2. Locate the security section, or create one if it doesn’t exist:

    security:
      authorization: enabled
    
  3. Save and exit (Ctrl+O, then Ctrl+X).

  4. Restart MongoDB so the change takes effect:

    1. sudo systemctl restart mongod

MongoDB provides a temporary localhost authentication bypass on a fresh deployment so the first administrative user can be created. This bypass is disabled automatically once an admin user exists or if certain security settings (like keyFile or clusterAuthMode) are enabled.

That means you can safely create your first admin user before full enforcement begins.

Creating the First Administrative User

The admin user is the foundation of MongoDB’s authentication system. It has permission to create other users, define roles, and grant access to specific databases.

To create this account:

  1. Start a local MongoDB shell:

    1. mongosh
  2. Switch to the admin database, which stores user credentials and role definitions:

    use admin
    
  3. Create the user with the following command:

    db.createUser({
      user: "admin",
      pwd: "StrongPasswordHere",
      roles: [
        { role: "userAdminAnyDatabase", db: "admin" },
        "readWriteAnyDatabase"
      ]
    })
    

    Let’s break this down:

    • userAdminAnyDatabase allows this user to create, modify, and remove users across all databases.
    • readWriteAnyDatabase gives read and write permissions globally. (You can omit this for a stricter admin-only user if desired.)

    This command writes a new document to MongoDB’s system.users collection inside the admin database. You can verify this by listing users afterward:

    show users
    
  4. Exit the shell:

    exit
    
  5. Reconnect as the admin user to confirm that authentication is now enforced:

    1. mongosh -u admin -p --authenticationDatabase admin

Once authenticated, you can run administrative commands such as:

show dbs

If MongoDB prompts for a password and grants access only after authentication, RBAC is functioning correctly.

Best practice: Always use long, randomly generated passwords or integrate MongoDB with a secret management system like HashiCorp Vault.

Creating Role-Based Users for Applications

In production, your application should never use the admin account. Instead, create dedicated users for each application, each with only the permissions it needs.

For example, to create a user for a web application that manages data in a specific database:

use myappdb
db.createUser({
  user: "appuser",
  pwd: "AppPassword123",
  roles: [ { role: "readWrite", db: "myappdb" } ]
})
  • readWrite allows the application to perform all standard CRUD operations (insert, query, update, delete) on this database only.
  • It cannot create other users, modify system collections, or access other databases.

You can list all users for a database with:

show users

Tip: Always separate users by application or environment (for example, appuser_prod and appuser_staging) so credentials can be rotated independently.

Restricting Network Access

Even with authentication enabled, it’s dangerous to expose MongoDB to the open internet. Automated scanners routinely look for open ports (particularly 27017, the default MongoDB port), and attempt brute-force attacks or exploit misconfigured instances.

By default, MongoDB only listens on 127.0.0.1, the local interface. If your applications and MongoDB server share the same host, you don’t need to change anything. However, if your application connects remotely, you’ll need to explicitly whitelist specific IP addresses.

  1. Edit the configuration file:

    1. sudo nano /etc/mongod.conf
  2. Locate the net section and update it:

    net:
      port: 27017
      bindIp: 127.0.0.1,192.168.10.50
    

    Replace 192.168.10.50 with your trusted application server’s IP address. This ensures MongoDB accepts connections only from localhost and that specific remote host.

  3. Restart the service to apply the changes:

    1. sudo systemctl restart mongod
  4. Confirm the active bindings:

    1. sudo ss -tulpn | grep mongod

You should see MongoDB listening on both 127.0.0.1:27017 and your specified IP.

Note: Avoid using bindIp: 0.0.0.0 on bare-metal or VM deployments unless strict network-level firewall rules are in place. In containerized or orchestrated environments, 0.0.0.0 is commonly required, but must still be protected by firewall or network policies.

Configuring Ubuntu’s Firewall (UFW)

Even if MongoDB listens only on certain interfaces, it’s best practice to reinforce network security at the operating system level.

Ubuntu’s UFW provides an easy way to control inbound and outbound connections.

  1. Verify UFW is installed and active:

    1. sudo ufw status

    If it shows as inactive, enable it:

    1. sudo ufw enable
  2. Allow MongoDB connections only from trusted IPs. For example, if your application server’s IP is 192.168.10.50:

    1. sudo ufw allow from 192.168.10.50 to any port 27017
  3. Check that the rule was added:

    1. sudo ufw status numbered

    You should see an entry allowing port 27017 from the specified source.

  4. Optionally, deny all other traffic to MongoDB explicitly:

    1. sudo ufw deny 27017/tcp

This combination, bindIp in MongoDB’s config and selective UFW rules, ensures that only known systems can reach your database, even if other processes attempt to expose it.

Note: For cloud deployments (like DigitalOcean), configure network security groups or VPC firewall rules as an additional layer of protection.

Enabling TLS/SSL Encryption

So far, you’ve ensured that only trusted users and IPs can access MongoDB. The next step is to secure the data in transit.

When a client connects to MongoDB, all data (including authentication credentials and queries) is transmitted as plain text by default. TLS encrypts this data, preventing eavesdropping or tampering.

Generate or Obtain a Certificate

In production, use a certificate from a trusted Certificate Authority (CA). For testing or internal deployments, you can generate a self-signed certificate:

  1. sudo mkdir -p /etc/ssl/mongodb
  2. sudo openssl req -newkey rsa:4096 -new -x509 -days 365 -nodes -out /etc/ssl/mongodb/mongodb.crt -keyout /etc/ssl/mongodb/mongodb.key -subj "/CN=$(hostname)"

This creates:

  • mongodb.crt: the public certificate
  • mongodb.key: the private key

Combine them into one PEM file (required by MongoDB):

  1. sudo cat /etc/ssl/mongodb/mongodb.key /etc/ssl/mongodb/mongodb.crt | sudo tee /etc/ssl/mongodb/mongodb.pem
  2. sudo chmod 600 /etc/ssl/mongodb/mongodb.pem
  3. sudo chown mongodb:mongodb /etc/ssl/mongodb/mongodb.pem

These permissions ensure only the mongodb user can access the key file.

Update the Configuration File

Edit /etc/mongod.conf and locate the net section. Add a new tls block beneath it:

net:
  port: 27017
  bindIp: 127.0.0.1,192.168.10.50
  tls:
    mode: requireTLS
    certificateKeyFile: /etc/ssl/mongodb/mongodb.pem
  • mode: requireTLS means MongoDB will refuse any non-encrypted connections.
  • certificateKeyFile specifies the combined PEM file path.

Restart MongoDB to apply the change:

  1. sudo systemctl restart mongod

Connect Using TLS

When connecting with mongosh, you must now specify the --tls option:

  1. mongosh --tls --host 192.168.10.50 -u admin -p --authenticationDatabase admin

If the connection succeeds and the prompt appears, your TLS configuration is working correctly.

You can verify encryption by inspecting the connection using OpenSSL:

  1. openssl s_client -connect 192.168.10.50:27017

The output should show the certificate chain and encryption details, for example:

SSL-Session:
    Protocol  : TLSv1.3
    Cipher    : TLS_AES_256_GCM_SHA384

This confirms that your MongoDB server is now encrypting traffic end-to-end.

Pro Tip: When enabling TLS in a replica set, configure both a keyFile and clusterAuthMode (typically set to x509 or keyFile) so nodes can authenticate each other securely.

Verifying Your Security Posture

Once everything is configured, it’s worth double-checking your setup.

  1. Check that MongoDB is bound only to allowed IPs:

    1. sudo ss -tulpn | grep mongod

    You should see connections limited to 127.0.0.1 and your trusted IPs only.

  2. Ensure authentication is enforced. Try connecting without credentials:

    1. mongosh

    You should receive an authentication error.

  3. Validate that TLS is required. Attempt to connect without --tls:

    1. mongosh --host 192.168.10.50 -u admin -p --authenticationDatabase admin

    If the connection fails with a message about TLS requirements, your encryption is correctly enforced.

  4. Review MongoDB’s internal security parameters:

    1. mongosh -u admin -p --authenticationDatabase admin --eval "db.runCommand({ getParameter: 1, tlsMode: 1 })"

    If tlsMode returns "requireTLS", encryption is confirmed active.

With authentication, access control, network restrictions, and TLS all configured, your MongoDB instance is now hardened against the most common attack vectors.

Operational Best Practices

Once MongoDB is installed and secured, the next major priority is maintaining it effectively. Even the most carefully configured database can become unreliable without regular maintenance. Routine operations such as backups, monitoring, and system updates ensure that MongoDB remains performant, stable, and recoverable over time.

Backing Up MongoDB Data

A well-planned backup strategy is fundamental to any production database. Backups allow you to recover quickly from hardware failures, software bugs, or accidental deletions. MongoDB supports both logical and physical backups, each suited to different scenarios.

Logical Backups Using mongodump

A logical backup captures database contents in BSON format using the mongodump utility. This approach is portable, human-readable, and easy to automate.

To create a full backup of all databases, run:

  1. mongodump --out /backups/mongodb/$(date +%F)

This command creates a directory named with the current date under /backups/mongodb/ and stores all BSON dumps inside it.

If authentication is enabled, use a URI connection string that includes credentials:

  1. mongodump --uri="mongodb://admin:YourPassword@localhost:27017/admin" --out /backups/mongodb/$(date +%F)

You can also back up a specific database:

  1. mongodump --db=myappdb --out /backups/mongodb/$(date +%F)

To restore from a logical backup, use mongorestore:

  1. mongorestore /backups/mongodb/2026-01-05/

Or restore a single database:

  1. mongorestore --db=myappdb /backups/mongodb/2026-01-05/myappdb

Logical backups are flexible and easy to script, but they can take longer to complete for very large datasets.

Recommendation: Schedule daily logical backups using a cron job or systemd timer, and always verify the restore process on a staging server before relying on backups in production.

Physical Backups (Filesystem Snapshots)

Physical backups capture the database files directly from the storage volume. This method is faster and more space-efficient for large databases, but it requires consistent snapshots to avoid corruption.

If you use journaling (which is enabled by default), you can take volume snapshots while MongoDB is running. WiredTiger supports crash-consistent snapshots while MongoDB is running, as long as journaling is enabled. For full application-consistent snapshots, stopping MongoDB is recommended but not required:

  1. sudo systemctl stop mongod

Take snapshot using your cloud provider or storage system and restart the service:

  1. sudo systemctl start mongod

Store snapshots in an offsite or separate region whenever possible. This protects against data center outages or accidental local deletions.

Monitoring MongoDB Health

Monitoring is critical to prevent issues before they impact users. MongoDB provides built-in command-line tools as well as support for external monitoring systems.

Using Built-In Tools

The mongostat tool displays live database metrics such as operations per second, memory usage, and active connections. Run it as follows:

  1. mongostat --uri "mongodb://admin@localhost:27017/?authSource=admin"

This produces a real-time table showing inserts, queries, updates, and deletes. Each column represents a key performance indicator, such as the ratio of dirty memory pages or the number of active connections.

The mongotop utility focuses on how long MongoDB spends reading and writing per collection. To run it every two seconds, use:

  1. mongotop 2

This is useful for identifying collections that experience heavy I/O.

Using External Monitoring Tools

For persistent visibility and alerting, you can integrate MongoDB with external systems such as:

Important metrics to monitor include:

  • Memory usage and cache hit rate
  • Disk I/O latency and throughput
  • Connection counts and queue length
  • Operation latency (insert, update, query times)
  • Replica lag (if running a replica set)

Recommendation: Configure alerts for critical thresholds such as high disk utilization, connection spikes, or replication lag exceeding five seconds.

Managing Disk Space and Storage Growth

MongoDB databases expand dynamically as documents and indexes grow. If disk usage is left unchecked, the database may run out of space, causing it to lock or crash.

Checking Disk Usage

Check current filesystem usage with:

  1. df -h /var/lib/mongodb

This displays available and used space for MongoDB’s data directory.

You can also check memory and cache usage through MongoDB itself:

  1. mongosh --eval "db.serverStatus().wiredTiger.cache"

The bytes currently in the cache value indicates how much RAM the WiredTiger storage engine is using.

Setting Up Disk Usage Alerts

To stay proactive, set up alerts or monitoring checks that notify you when disk usage exceeds 85%. For example, a simple script could be scheduled to run periodically:

  1. df -h | awk '$5 > 85 {print $0}'

You can integrate this into systemd timers or monitoring tools for automation.

Managing Old Data and Logs

Large or unused collections and log files can consume significant space over time. To manage logs, configure rotation in /etc/logrotate.d/mongodb (as shown later in this section) or clean up manually:

  1. sudo journalctl --vacuum-time=7d
  2. sudo rm -f /var/log/mongodb/*.gz

For application data, consider using TTL (time-to-live) indexes for collections that store temporary or time-sensitive data:

db.sessionLogs.createIndex({ "createdAt": 1 }, { expireAfterSeconds: 604800 })

This automatically deletes documents older than seven days.

Performing Safe Upgrades

Upgrading MongoDB requires careful planning, especially when moving between major versions. The following process minimizes downtime and ensures compatibility.

Check the Current Version

Confirm the installed version:

  1. mongod --version

Back Up Before Upgrading

Always create a full backup before upgrading:

  1. mongodump --out /backups/mongodb/pre-upgrade-$(date +%F)

Update the Package Repository and Upgrade

If you previously pinned MongoDB packages to prevent automatic updates, remove the holds:

  1. echo "mongodb-org install" | sudo dpkg --set-selections

Then update your package list and upgrade MongoDB:

  1. sudo apt update
  2. sudo apt install -y mongodb-org

MongoDB preserves your configuration and data files during upgrades, but a backup guarantees you can roll back if something goes wrong.

Validate the Upgrade

After the upgrade:

  1. Verify the service status:

    1. sudo systemctl status mongod
  2. Check recent logs for warnings or migration notes:

    1. sudo tail -n 30 /var/log/mongodb/mongod.log
  3. Confirm the new version:

    1. mongosh --eval "db.version()"

Recommendation: For major version upgrades (for example, from 7.x to 8.x), always read the official MongoDB release notes.

Some query behaviors or internal storage structures may change.

Automating Routine Maintenance

Manual maintenance works for small environments, but automation ensures consistency. You can schedule recurring backups, log rotations, or monitoring checks using cron or systemd timers.

Schedule Automatic Backups

Edit the root crontab:

  1. sudo crontab -e

Add the following line to back up your MongoDB instance every night at 2 a.m.:

0 2 * * * mongodump --out /backups/mongodb/$(date +\%F)

This creates a dated backup folder every day.

Configure Log Rotation

To prevent log files from consuming disk space, create a log rotation configuration file:

  1. sudo nano /etc/logrotate.d/mongodb

Add the following content:

/var/log/mongodb/mongod.log {
    weekly
    rotate 5
    compress
    delaycompress
    missingok
    notifempty
    create 640 mongodb adm
    postrotate
        systemctl reload mongod > /dev/null 2>&1 || true
    endscript
}

This configuration keeps five weeks of logs, compresses older files, and reloads MongoDB after rotation.

Maintaining Accurate System Time

MongoDB’s journaling and replication features rely on accurate timestamps. If the system clock drifts, replication lag or journal corruption may occur after a crash.

Ubuntu 24.04 uses systemd-timesyncd by default, but you can also use chrony for more precise time synchronization:

  1. sudo apt install chrony -y
  2. sudo systemctl enable --now chrony

You can verify synchronization with:

  1. timedatectl status

If NTP synchronized shows as yes, your system clock is in sync.

Checking MongoDB Health in Real Time

MongoDB provides the serverStatus command for comprehensive runtime diagnostics. You can query it directly from the shell:

  1. mongosh --eval "db.serverStatus()"

This returns a detailed JSON object containing metrics such as:

  • Memory consumption
  • Cache usage
  • Connection count
  • Operation throughput
  • Replication state

You can extract specific fields for targeted checks. For example, to view connection statistics:

  1. mongosh --eval "db.serverStatus().connections"

This allows quick insights into whether the system is experiencing connection saturation or resource constraints.

Preparing for High Availability

Single-node MongoDB deployments work well for development or low-criticality applications. For production environments, you should implement replica sets. Replica sets provide redundancy and automatic failover, ensuring availability even if one node fails.

In a typical setup:

  • One node acts as the primary, handling all writes and most reads.
  • One or more secondary nodes replicate data in real time.
  • If the primary node goes offline, one of the secondaries automatically becomes the new primary.

Replica sets also simplify maintenance tasks like backups and scaling. You can offload backups or analytics queries to secondary nodes without impacting primary performance.

Your MongoDB instance is now fully operational and properly maintained.

Scaling and Performance Optimization

MongoDB is designed to scale horizontally, meaning you can increase capacity and performance by adding more servers rather than relying solely on a single, more powerful machine. As your dataset grows or your application begins handling more concurrent queries, scaling ensures that MongoDB continues to perform reliably and efficiently.

There are two primary ways to scale MongoDB:

  1. Replica sets, which increase reliability and read performance through redundancy.
  2. Sharding, which distributes data across multiple servers to handle larger datasets and write loads.

Understanding Replica Sets

A replica set is a group of MongoDB servers that maintain identical copies of your data. Replica sets provide high availability and protect against hardware or network failures. If the primary node fails, one of the secondary nodes automatically takes over, ensuring minimal downtime.

A standard replica set consists of:

  • One primary node that handles all write operations.
  • Two or more secondary nodes that replicate data from the primary.
  • Optional arbiter nodes that participate in elections but do not store data.

For production systems, MongoDB recommends at least three members in a replica set.

Configuring a Replica Set

To create a replica set, you need at least two or three servers (physical or virtual). Each node should have MongoDB installed and configured.

  1. On each node, open the configuration file /etc/mongod.conf and add the replication section:

    replication:
      replSetName: "rs0"
    
  2. Restart MongoDB on each server:

    1. sudo systemctl restart mongod
  3. On the primary node, connect to MongoDB and initialize the replica set:

    1. mongosh

    Then run:

    rs.initiate({
      _id: "rs0",
      members: [
        { _id: 0, host: "mongodb1.example.com:27017" },
        { _id: 1, host: "mongodb2.example.com:27017" },
        { _id: 2, host: "mongodb3.example.com:27017" }
      ]
    })
    
  4. Verify the status:

    rs.status()
    

    The output should show one primary and two secondaries with their state labeled as “PRIMARY” and “SECONDARY.”

Benefits of Replica Sets

Replica sets offer several important advantages:

  • High availability: Automatic failover ensures continued operation if the primary node goes offline.
  • Data redundancy: Each node maintains a full copy of the data.
  • Read scalability: Secondary nodes can handle read operations, reducing load on the primary.
  • Maintenance flexibility: You can perform backups or system updates on secondary nodes without affecting availability.

Best practice: Use even distribution of replica nodes across different physical zones or availability regions to prevent data loss during outages.

Understanding Sharding

Sharding is MongoDB’s strategy for horizontal scaling. When a dataset becomes too large for a single server to store or process efficiently, MongoDB can divide it into smaller chunks distributed across multiple servers called shards.

Each shard holds a subset of the data, and the cluster collectively behaves as one logical database.

Components of a Sharded Cluster

A typical MongoDB sharded cluster includes:

  • Shards: The data-bearing nodes, often deployed as replica sets for redundancy.
  • Config servers: Store metadata and cluster configuration, including chunk distribution.
  • Mongos routers: Route client queries to the correct shard based on the sharding key.

Choosing a Shard Key

The shard key determines how MongoDB distributes data across shards. A poorly chosen shard key can lead to uneven data distribution (known as data skew) or hotspots.

Good shard keys typically have:

  • High cardinality (many unique values).
  • Even data access patterns.
  • A predictable query pattern that includes the shard key in most queries.

Example of enabling sharding for a database:

sh.enableSharding("salesdb")
sh.shardCollection("salesdb.orders", { "customer_id": 1 })

This command enables sharding on the salesdb database and shards the orders collection using the customer_id field.

When to Use Sharding

You should consider sharding when:

  • The database approaches or exceeds the limits of a single server’s storage capacity.
  • Write throughput is consistently maxing out CPU or disk I/O.
  • The working set no longer fits into RAM, causing frequent page swaps.
  • You anticipate exponential growth in your dataset.

Sharding adds architectural complexity, so it is best introduced only when necessary.

Note: After a collection is sharded, MongoDB does not support unsharding it. Plan your shard key carefully before enabling sharding.

Tuning WiredTiger for Performance

MongoDB uses the WiredTiger storage engine by default. It is optimized for modern hardware and uses compression, caching, and multi-threaded I/O. Understanding how WiredTiger manages memory and disk I/O helps improve performance.

Memory Usage

WiredTiger typically uses approximately 50% of available RAM for its cache, with MongoDB dynamically adjusting this value based on system memory.

You can adjust this in the configuration file:

storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 8

This is useful if your system runs other memory-intensive services alongside MongoDB. For dedicated MongoDB servers, leaving the default cache setting is generally best.

You can view current cache usage by running:

  1. mongosh --eval "db.serverStatus().wiredTiger.cache"

Compression

WiredTiger supports data and index compression to reduce disk usage. By default, it uses Snappy compression, which balances performance and space efficiency. You can switch to zlib (for better compression) or zstd (for newer setups) if you prioritize disk savings over speed.

Example configuration:

storage:
  wiredTiger:
    collectionConfig:
      blockCompressor: zstd

Journaling and Durability

Journaling ensures that write operations are durable, even in case of power loss. You can adjust the commitIntervalMs parameter to control how often journal writes occur:

storage:
  journal:
    commitIntervalMs: 100

Lower intervals improve durability but may reduce write performance slightly.

Recommendation: For most production workloads, retain default journaling settings, as WiredTiger’s balance between performance and durability is well tested.

Monitoring and Scaling Triggers

It is important to recognize when to scale your MongoDB deployment. Monitoring metrics such as CPU load, memory usage, and I/O wait times will help determine when it is time to add more capacity.

Common Triggers for Scaling

  • CPU utilization consistently above 80%.
  • Disk I/O latency exceeding acceptable thresholds (for example, more than 10 ms).
  • RAM utilization near maximum for extended periods.
  • Rapid growth in working set size.
  • Increased replication lag between nodes.

When these indicators appear, consider adding more secondaries (for reads) or shards (for write-heavy loads).

Vertical vs. Horizontal Scaling

Vertical scaling involves adding more resources (CPU, RAM, faster disks) to existing servers. It is simpler to manage but limited by hardware capacity.

Horizontal scaling involves adding new servers to distribute the workload. This is MongoDB’s strength, as it scales nearly linearly when designed properly.

Migration to Managed MongoDB

As your system grows, managing a self-hosted cluster can become complex. At this stage, migrating to a managed MongoDB service, like MongoDB Atlas, can significantly reduce operational overhead.

Managed platforms handle automatic backups, patching, monitoring, scaling, and encryption. However, they may introduce additional cost and slightly less flexibility compared to self-managed setups.

<$> Recommendation: Stay self-hosted until your team faces consistent operational challenges such as performance bottlenecks, cluster management complexity, or compliance requirements that managed platforms handle more efficiently. <$>

Comparison: Self-Hosted vs Managed MongoDB

MongoDB can be deployed in two main ways:

  1. Self-hosted, where you install, configure, and maintain the database yourself (as covered in this guide).
  2. Managed, where a third-party provider hosts and operates MongoDB for you as a service.

Each approach has distinct advantages and trade-offs. The right choice depends on your technical expertise, workload characteristics, compliance needs, and operational priorities.

Let’s examine these two options in depth.

Self-Hosted MongoDB

When you self-host MongoDB, you install it directly on your own infrastructure, whether that’s a physical server, a virtual machine, or a cloud instance such as a DigitalOcean Droplet. You control every aspect of the environment, from installation to upgrades and monitoring.

Advantages of Self-Hosting

  1. Full Control and Flexibility: You have complete authority over configuration settings, file systems, networking, and performance tuning. You can modify the mongod.conf file, choose your storage paths, and apply custom security or backup policies that fit your organization’s standards.
  2. Cost Efficiency for Small Deployments: For small or medium workloads, self-hosting can be cheaper than using a managed service. You pay only for the underlying compute and storage resources rather than an additional management layer.
  3. Custom Security Policies: You can integrate MongoDB with internal VPNs, firewalls, or private networks, ensuring full compliance with local or industry-specific security requirements. Some organizations require on-premises deployment due to data residency or regulatory constraints, which makes self-hosting the only viable option.
  4. Performance Optimization: Since you control the hardware, you can fine-tune system parameters such as I/O schedulers, cache sizes, and compression algorithms. You can also co-locate MongoDB with related services to minimize network latency.

Challenges of Self-Hosting

  • Operational Overhead: You are responsible for managing everything; from installing updates and patches to handling outages and performance tuning. This requires dedicated staff with expertise in database administration and Linux system management.
  • Scalability Complexity: Scaling a self-hosted MongoDB cluster means provisioning new servers, rebalancing data, updating configurations, and maintaining replication or sharding topologies manually. These tasks can be error-prone without automation.
  • Backup and Disaster Recovery: You must design, test, and maintain your own backup, restore, and offsite storage processes. While MongoDB’s tools (mongodump, mongorestore, and volume snapshots) make this possible, it requires disciplined operational planning.
  • Monitoring and Alerting: Self-hosted MongoDB requires you to set up monitoring and alert systems using tools like Prometheus, Grafana, or Percona PMM. Without continuous visibility, failures or performance bottlenecks may go unnoticed until they cause downtime.

In summary, self-hosted MongoDB provides flexibility, independence, and lower cost at small scale but demands significant ongoing maintenance effort.

Managed MongoDB Services

A managed MongoDB service hosts the database on your behalf, handling all infrastructure, updates, scaling, and security patches automatically. These services eliminate most of the administrative overhead while offering high availability and global scalability.

Advantages of Managed MongoDB

  1. Minimal Operational Effort: The service provider handles database provisioning, backups, upgrades, and failover automatically. You can deploy new clusters with just a few clicks or API calls, significantly reducing administrative workload.
  2. Automatic Scaling: Managed services can dynamically adjust compute and storage resources as your dataset grows. For example, MongoDB Atlas supports automatic sharding and vertical scaling without downtime.
  3. Built-In Monitoring and Alerts: Managed platforms include dashboards for CPU usage, disk performance, connection statistics, and query latency. You can set alert thresholds for critical metrics without deploying separate monitoring tools.
  4. High Availability by Default: Most managed services deploy clusters with three or more replica set nodes across different availability zones. This ensures automatic failover and high uptime with minimal configuration.
  5. Security and Compliance: Managed MongoDB platforms offer built-in encryption, role-based access, network isolation (VPC peering), and integration with identity providers. They are also certified for standards like SOC 2, GDPR, HIPAA, and ISO 27001, which simplifies compliance audits.
  6. Global Distribution: MongoDB Atlas and similar services support multi-region clusters. Data can be replicated geographically close to your users, improving latency for distributed applications.

Limitations of Managed Services

  1. Higher Cost at Scale: Managed services charge a premium for automation and convenience. As data volume and traffic grow, monthly costs can exceed the expense of running self-hosted instances, especially for large datasets stored on SSDs.
  2. Limited Customization: Managed environments restrict access to low-level configuration options. You cannot modify filesystem-level settings, cache tuning, or underlying OS parameters.
  3. Vendor Lock-In: Each provider has unique APIs and deployment configurations, making it difficult to migrate between services later.
  4. Network Dependence: Managed databases rely on external network connectivity. If your application runs in an on-premises environment, connecting securely to a managed service may introduce latency or dependency on VPN tunnels.

In summary, Managed MongoDB services drastically reduce administrative burden and improve reliability but at the cost of flexibility and higher recurring expense.

Feature Comparison Table

Feature Self-Hosted MongoDB Managed MongoDB (e.g., Atlas)
Setup Effort Manual installation and configuration One-click or automated provisioning
Control Over Configuration Full control over system and storage settings Limited; provider manages internals
Performance Tuning Customizable (hardware and OS level) Pre-optimized by provider
Scalability Manual; add shards or replicas manually Automatic vertical and horizontal scaling
High Availability Must configure replica sets Enabled by default
Backups Manual using mongodump or snapshots Automated with retention options
Monitoring External tools (Prometheus, PMM, Grafana) Integrated dashboards and alerts
Security & Compliance Fully customizable; user responsibility Managed encryption, RBAC, certifications
Operational Overhead High; requires skilled DBAs Low; handled by the provider
Cost (Long-Term) Lower for small setups Higher, especially at scale
Ideal Use Case Small teams, development, regulated environments Large-scale, distributed, or cloud-native apps

Choosing the Right Deployment Model

The decision between self-hosted and managed MongoDB depends primarily on your organization’s priorities, resources, and constraints. Consider the following scenarios:

  • Choose Self-Hosted MongoDB if:

    • You require full control over infrastructure and data.
    • Your workload is moderate and predictable.
    • You have in-house expertise in Linux and MongoDB administration.
    • Compliance or data residency laws require on-premises storage.
  • Choose Managed MongoDB if:

    • You prefer to focus on application development rather than infrastructure.
    • You need automatic scaling and high availability with minimal setup.
    • Your team lacks dedicated database administrators.
    • You need globally distributed clusters or compliance certifications (SOC 2, HIPAA, GDPR).

Practical recommendation: Many organizations adopt a hybrid approach: they use self-hosted MongoDB for testing, staging, or regional workloads, and managed MongoDB (Atlas) for production systems that demand high uptime and scalability.

Troubleshooting and Maintenance

Even with the most careful configuration and monitoring, issues can arise in a MongoDB deployment. These may include slow performance, failed startups, replication lag, or disk space exhaustion. The key to maintaining a stable MongoDB environment is having a structured approach to diagnosing problems and applying preventive maintenance routines.

Checking MongoDB Service Status

The first step when troubleshooting MongoDB is to verify whether the database service is running correctly.

You can check the current status with the following command:

  1. sudo systemctl status mongod

If MongoDB is running, you should see output that includes:

  1. Active: active (running)
  2. Main PID: 3564 (mongod)

If the service is inactive, failed, or dead, restart it:

  1. sudo systemctl restart mongod

After restarting, check its status again. If it immediately fails, proceed to check the log file for specific errors.

Reviewing MongoDB Logs

Logs are the most direct source of diagnostic information. MongoDB records all major events, warnings, and errors in its main log file located at:

/var/log/mongodb/mongod.log

To view the most recent entries, run:

  1. sudo tail -n 30 /var/log/mongodb/mongod.log

If MongoDB fails to start, you will typically see one of the following errors:

  • Permission denied: Incorrect ownership or permissions on /var/lib/mongodb or /var/log/mongodb. Check permissions and fix them:

    1. sudo chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb
  • Data directory not found: Ensure /var/lib/mongodb exists and matches the path defined in /etc/mongod.conf.

  • Address already in use: Another process is using port 27017. Identify it with:

    1. sudo lsof -i :27017

    and stop or reconfigure the conflicting service.

  • Corrupted data files: This may occur if MongoDB was shut down abruptly. In such cases, the journal should recover data automatically on restart. If it fails, you may need to restore from backup.

Tip: For continuous log inspection during debugging, use:

  1. sudo tail -f /var/log/mongodb/mongod.log

Diagnosing Connection Issues

Connection problems are another frequent issue. When clients cannot reach MongoDB, it is usually due to a network, authentication, or configuration problem.

Verify That MongoDB Is Listening on the Correct Interfaces

Run:

  1. sudo ss -tulpn | grep mongod

The output should show MongoDB bound to 127.0.0.1 (for local connections) and any configured external IPs. If MongoDB is not listening on the expected IP, verify the bindIp field in /etc/mongod.conf:

net:
  bindIp: 127.0.0.1,192.168.10.50

Restart MongoDB after editing:

  1. sudo systemctl restart mongod

Check Firewall Rules

If remote connections fail, confirm that your firewall allows traffic on port 27017:

  1. sudo ufw status

If not, allow connections from specific IPs:

  1. sudo ufw allow from 192.168.10.50 to any port 27017

Test Connectivity with Telnet or Ping

From a client system, test whether the port is reachable:

  1. telnet mongodb-server-ip 27017

or

  1. nc -vz mongodb-server-ip 27017

If the connection succeeds, the issue is likely related to authentication or user privileges.

Troubleshooting Authentication Failures

Authentication issues often occur after enabling access control or changing user credentials.

Confirm That Authentication Is Enabled

Connect locally and verify:

  1. mongosh --eval "db.runCommand({ getParameter: 1, authenticationMechanisms: 1 })"

If the output includes "SCRAM-SHA-256", authentication is active.

Verify Login Credentials

Try connecting using the admin account:

  1. mongosh -u admin -p --authenticationDatabase admin

If this fails, connect locally without authentication (possible only from localhost when no users exist) and recreate the admin account:

use admin

db.createUser({
  user: "admin",
  pwd: "NewStrongPassword",
  roles: ["userAdminAnyDatabase", "readWriteAnyDatabase"]
})

Check Database Context

Each MongoDB user is defined within a specific database. If you authenticate against the wrong database, authentication will fail. For example, if the user was created in the admin database, you must authenticate against it explicitly:

  1. mongosh -u admin -p --authenticationDatabase admin

Resolving Performance Issues

Performance degradation can arise from high memory usage, slow disk I/O, unoptimized queries, or excessive concurrent connections. MongoDB includes several diagnostic tools to identify these issues.

Check Resource Utilization

Use Linux commands to check system-level metrics:

  1. top
  2. vmstat 2
  3. iostat -x 2

Look for high CPU usage by mongod or disk latency exceeding 10 milliseconds.

Monitor Database Operations

Run:

  1. mongostat 2

This displays real-time metrics, including inserts, queries, updates, and deletes per second.

If certain operations appear slow, use the MongoDB profiler to identify long-running queries.

Enable Query Profiling

You can enable the profiler temporarily to log slow queries:

use myappdb

db.setProfilingLevel(1, { slowms: 100 })

This logs any query that takes longer than 100 milliseconds.

Review the results:

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

Recommendation: Keep profiling disabled in production when not troubleshooting to avoid performance overhead.

Analyze Index Efficiency

Inefficient queries often stem from missing indexes. To see if MongoDB is using indexes correctly, prepend explain() to your query:

db.orders.find({ customer_id: 12345 }).explain("executionStats")

If executionStages.stage shows "COLLSCAN", MongoDB is performing a full collection scan. You can create an index to improve performance:

db.orders.createIndex({ customer_id: 1 })

Repairing Corrupted Databases

Data corruption is rare, but it can occur due to power loss or disk errors. If MongoDB refuses to start and logs show corruption in the WiredTiger files, follow these steps:

  1. Stop MongoDB:

    1. sudo systemctl stop mongod
  2. Backup the current data directory:

    1. sudo cp -r /var/lib/mongodb /var/lib/mongodb-corrupt-backup
  3. Attempt a repair operation:

    1. sudo -u mongodb mongod --repair --config /etc/mongod.conf
  4. Restart MongoDB:

    1. sudo systemctl start mongod

If the repair fails, restore data from your most recent backup.

Routine Maintenance Tasks

Preventive maintenance greatly reduces the chance of unexpected failures.

Rotate Logs Regularly

Ensure that your log rotation policy is active. MongoDB supports both internal log rotation (logRotate command) and external rotation via logrotate when logAppend is enabled. You can manually trigger it if logs grow quickly:

  1. sudo logrotate -f /etc/logrotate.d/mongodb

Compact Collections

Collections can become fragmented after many inserts and deletes. compact can reclaim space but is a blocking operation and should rarely be used in production. WiredTiger automatically handles most fragmentation, so compacting is usually unnecessary.

Note that this operation locks the database, so perform it during low traffic periods.

Validate Collections

Run periodic data integrity checks:

db.runCommand({ validate: "collection_name" })

This verifies that indexes and documents are consistent.

Monitor Disk and Memory Usage

Use automated alerts to warn when disk usage exceeds 85% or memory utilization becomes critical. Monitoring tools like Prometheus, Percona PMM, or MongoDB Atlas Monitor can track these metrics over time.

Applying System Updates Safely

When updating MongoDB or the underlying Ubuntu system, always follow a structured process:

  1. Backup your data first.

  2. Stop the MongoDB service before kernel or library upgrades:

    1. sudo systemctl stop mongod
  3. Apply updates:

    1. sudo apt update && sudo apt upgrade -y
  4. Restart the service and confirm it runs correctly:

    1. sudo systemctl start mongod
    2. sudo systemctl status mongod

Note: Never interrupt MongoDB during writes or while the journal is active, as this can cause data corruption.

Tools for Proactive Maintenance

Several tools simplify ongoing maintenance and health checks:

  • MongoDB Compass: A GUI for exploring data and performance metrics visually.
  • Atlas CLI: For managing clusters, users, and backups on MongoDB Atlas.
  • Mongosh Scripts: Custom scripts can automate health checks or generate daily reports on connection counts and disk usage.
  • Ansible Playbooks: Automate installations, configuration validation, and backup scheduling.

Disaster Recovery Testing

The final step in maintenance planning is testing recovery procedures. A backup is only useful if it restores correctly.

At least once per quarter:

  1. Restore your latest backup to a staging server.
  2. Verify that indexes, users, and permissions load correctly.
  3. Measure restoration time to ensure it meets your recovery time objectives (RTO).
  4. Document the process so any administrator can execute it in an emergency.

Long-Term Maintenance Checklist

Task Frequency Purpose
Verify backups Daily Confirm that backups are complete and restorable
Check replication and logs Daily Detect lag or node sync issues
Monitor disk and memory usage Daily Prevent capacity exhaustion
Review slow query logs Weekly Identify performance bottlenecks
Apply OS and MongoDB updates Monthly Keep software secure and current
Test restore procedures Quarterly Validate disaster recovery readiness
Review user access Quarterly Maintain least-privilege security

By following these troubleshooting and maintenance practices, you can maintain a healthy MongoDB deployment on Ubuntu that remains performant, secure, and resilient over time. Consistent monitoring and maintenance are far less costly than recovering from an outage or data loss event.

FAQs

1. Why is MongoDB not available in default Ubuntu repositories?

MongoDB was removed from Ubuntu’s default repositories after version 18.04 because of licensing changes. The MongoDB Server Side Public License (SSPL) is not recognized as open-source by the Debian and Ubuntu projects. As a result, Canonical no longer distributes MongoDB in its official repositories, and users must install it from MongoDB’s own APT repository instead.

2. How do I uninstall MongoDB completely?

To uninstall MongoDB and remove all associated files, run the following commands:

  1. sudo systemctl stop mongod
  2. sudo apt purge -y mongodb-org*
  3. sudo rm -rf /var/lib/mongodb
  4. sudo rm -rf /var/log/mongodb
  5. sudo rm -f /etc/apt/sources.list.d/mongodb-org-*.list
  6. sudo apt autoremove -y

This stops the MongoDB service, removes all related packages, deletes data and log directories, and cleans up the repository entry.

3. How do I check if MongoDB is running?

You can check the status of the MongoDB service using:

  1. sudo systemctl status mongod

If MongoDB is running, you will see a line stating “Active: active (running)”. Alternatively, you can confirm connectivity by running:

  1. mongosh --eval "db.runCommand({ connectionStatus: 1 })"

If the command returns "ok": 1, MongoDB is active and accepting connections.

4. Can MongoDB run on a small VPS?

Yes, MongoDB can run on a small VPS, but with limitations. For basic development or testing workloads, a server with 2 CPU cores, 2 GB of RAM, and 10–20 GB of SSD storage is sufficient.

However, for production use, MongoDB performs best on systems with at least 4 CPU cores, 8 GB of RAM, and high-speed SSD or NVMe storage. Low-memory environments may require adjusting the WiredTiger cache size to prevent excessive swapping.

5. Why does MongoDB fail to start after running a repair operation?

MongoDB may fail to start after a repair if the repair process was run as root, which changes ownership of the data files in /var/lib/mongodb to root:root. Since the mongod service runs as the mongodb user, it will not have permission to read or write these files. To fix this, ensure you run the repair command as the mongodb user or restore correct ownership afterward:

  1. sudo chown -R mongodb:mongodb /var/lib/mongodb

6. How can I tell whether MongoDB is listening on the correct network interfaces?

You can verify MongoDB’s active listeners using:

  1. sudo ss -tulpn | grep mongod

This shows the IP addresses and ports MongoDB is bound to. If you don’t see the expected IP (for example, your application server’s IP), check the bindIp value in /etc/mongod.conf and restart the service.

7. Should I change MongoDB’s default WiredTiger cache size?

In most cases, no. WiredTiger automatically uses about 50% of system RAM and dynamically adjusts cache usage based on available memory. Only adjust the cacheSizeGB setting if MongoDB shares the server with other memory-intensive applications. Dedicated MongoDB servers should typically keep the default behavior.

8. Why are my MongoDB logs growing so large?

MongoDB continuously writes operational data to its log file at /var/log/mongodb/mongod.log. Without log rotation, this file can become very large. Ensure you have log rotation configured using logrotate, as described in the maintenance section of the guide, so older logs are compressed or deleted automatically.

9. When should I consider adding more nodes to my replica set?

You should expand your replica set when you notice sustained increases in read traffic, frequent node elections, replication lag, or when you need higher availability across multiple zones or regions. Adding secondaries distributes read load and improves fault tolerance, especially for production environments.

10. How can I confirm that TLS is correctly enabled on my MongoDB server?

After configuring TLS in /etc/mongod.conf, connect using:

  1. mongosh --tls --host <server-ip> -u admin -p --authenticationDatabase admin

If the connection succeeds, run:

  1. openssl s_client -connect <server-ip>:27017

A valid TLS handshake and details such as Protocol: TLSv1.3 confirm that encryption is active.

Conclusion

Running MongoDB effectively is not only about installation and setup; it is about maintaining a balance between performance, security, and reliability over time. You now have a fully capable MongoDB system that can support production workloads, scale with demand, and recover from unexpected failures.

By applying the principles and best practices outlined in this guide, from daily monitoring to long-term capacity planning, you can operate MongoDB with confidence in any environment. Whether you continue managing it yourself or migrate to a managed service like MongoDB Atlas, your understanding of MongoDB’s inner workings ensures you’ll always remain in control of your data.

To learn more about databases, check out the following tutorials:

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

Tutorial Series: Getting Started With Cloud Computing

This curriculum introduces open-source cloud computing to a general audience along with the skills necessary to deploy applications and websites securely to the cloud.

About the author(s)

Mark Drake
Mark Drake
Author
Manager, Developer Education
See author profile

Former Technical Writer at DigitalOcean. Focused on SysAdmin topics including Debian 11, Ubuntu 22.04, Ubuntu 20.04, Databases, SQL and PostgreSQL.

Manikandan Kurup
Manikandan Kurup
Editor
Senior Technical Content Engineer I
See author profile

With over 6 years of experience in tech publishing, Mani has edited and published more than 75 books covering a wide range of data science topics. Known for his strong attention to detail and technical knowledge, Mani specializes in creating clear, concise, and easy-to-understand content tailored for developers.

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Thanks for the tutorial, but I’m stuck!

When I try to run the cURL command to get the key added, I get the following error:

curl: (77) error setting certificate verify locations: CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead(see apt-key(8)). gpg: no valid OpenPGP data found.

What’s weird is, when I run sudo apt-key list, it shows MongoDB 4.4 key has been added… but when I run sudo apt update, I get an error basically saying there’s no certificate.

Hi, thanks for your helpful article.

I have used your instructions once and it worked fine. But I’m doing the same thing in my new server, and surprisingly it’s not working!

after line:

sudo apt update

in step 1, I get the following error:

E: Failed to fetch https://repo.mongodb.org/apt/ubuntu/dists/focal/mongodb-org/4.4/InRelease  403  Forbidden [IP: 65.9.58.40 443]
E: The repository 'https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/4.4 InRelease' is not signed.

The tutorial is okay but after the install I tried to start the mongo service but it failed with the exit-code

I used the following commands to fix it and it worked.

chown -R mongodb:mongodb /var/lib/mongodb
chown mongodb:mongodb /tmp/mongodb-27017.sock

worked like a charm !

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.