Website Vidya
DeploymentStep-by-Step Guide

How to Install MongoDB on Ubuntu 24.04 and 22.04

Learn how to install mongodb on ubuntu 24.04 and 22.04 with official MongoDB 7.0 repositories, systemd configuration, mongosh shell, and security rules.

RR
Rajesh RayLead Systems Educator
Published:
5 min read
PDF Cheat Sheet
How to Install MongoDB on Ubuntu 24.04 and 22.04
AI Executive SummaryCORE CIS AI

5 min read

Learn how to install mongodb on ubuntu 24.04 and 22.04 with official MongoDB 7.0 repositories, systemd configuration, mongosh shell, and security rules.

Key Highlights
  • Prerequisites and Supported Releases
  • Step 1: Installing Dependencies and Importing the MongoDB GPG Key
  • Step 2: Adding the Official MongoDB APT Repository
Grounded in full engineering runbookCORE CIS Ai Engine

Modern full-stack web applications, real-time analytics engines, and mobile backends demand flexible, schema-free database engines capable of handling dynamic JSON-like data at scale.

MongoDB is the world's most popular document-oriented NoSQL database system, storing data in binary JSON (BSON) records with dynamic schemas, rich aggregation pipelines, and distributed replica set high availability.

While Ubuntu's default package repositories provide an older snapshot of MongoDB, installing the official MongoDB Community Edition from upstream repositories guarantees access to the latest performance improvements, security patches, and the modern mongosh shell.

In this guide, we walk through how to install mongodb on ubuntu step-by-step on both Ubuntu 24.04 LTS and 22.04 LTS, verify service health, and secure database connections.

Advertisement

Prerequisites and Supported Releases

This guide is thoroughly verified on Ubuntu 24.04 LTS (Noble Numbat) & Ubuntu 22.04 LTS. The instructions apply cleanly to cloud instances (AWS EC2, Google Compute Engine, DigitalOcean, Hetzner), bare-metal servers, and local virtual machines.

Before proceeding, ensure you have the following requirements satisfied:

  • A server or workstation running Ubuntu 24.04 LTS or Ubuntu 22.04 LTS.
  • An unprivileged user account with sudo administrative privileges.
  • An x86_64 or ARM64 64-bit architecture CPU with AVX instruction set support.
  • At least 2 GB of available system RAM.

Step 1: Installing Dependencies and Importing the MongoDB GPG Key

MongoDB signs all official Debian packages with dedicated public GPG keys to guarantee package authenticity.

First, install the curl and gnupg utilities required for cryptographic keyring management:

Advertisement

Download and dearmor the official MongoDB Community Edition 7.0 public key into /etc/apt/keyrings/:

# Update local package index and install prerequisite tools:
sudo apt update
sudo apt install -y curl gnupg

# Ensure the secure keyrings directory exists:
sudo mkdir -p /etc/apt/keyrings

# Download and dearmor MongoDB 7.0 GPG signing key:
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
  sudo gpg --dearmor -o /etc/apt/keyrings/mongodb-server-7.0.gpg

# Set correct read permissions for the key:
sudo chmod 644 /etc/apt/keyrings/mongodb-server-7.0.gpg

Step 2: Adding the Official MongoDB APT Repository

Create a dedicated source list file at /etc/apt/sources.list.d/mongodb-org-7.0.list.

Link the downloaded GPG keyring using the signed-by directive and reference your active Ubuntu release:

Update your local APT cache to make MongoDB Community packages available for installation:

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

# Refresh APT repository cache:
sudo apt update

Step 3: Installing MongoDB Community Edition Packages

The mongodb-org metapackage installs the complete MongoDB database suite, including the daemon (mongod), sharded router (mongos), modern shell (mongosh), and database management tools (mongodump, mongorestore):

Advertisement

Install the suite using apt:

# Install MongoDB Community Edition:
sudo apt install -y mongodb-org

# Verify installed binary version:
mongod --version
# Expected output confirms:
# db version v7.0.x
# Build Info: ... OpenSSL 3.0.x

Step 4: Starting and Enabling the MongoDB (mongod) Service

Ubuntu does not automatically start daemon services immediately after installation.

Start the mongod systemd service and enable it to launch automatically upon system boot:

Verify the operational state of the database daemon:

# Reload systemd daemons:
sudo systemctl daemon-reload

# Start MongoDB daemon and enable on boot:
sudo systemctl enable --now mongod

# Check service status:
sudo systemctl status mongod
# Expected output confirms:
# Active: active (running) since ...
# Main PID: 12345 (mongod)

Step 5: Connecting to the Database with mongosh Shell

MongoDB 6.0 and newer completely replaced the legacy mongo shell with the modern Node.js-based mongosh (MongoDB Shell).

Connect to your local database instance by typing mongosh in your terminal:

Test database creation, document insertion, and collection querying:

// Launch the interactive shell:
// mongosh

// Switch to or create a database named 'testdb':
use testdb;

// Insert a document into the 'customers' collection:
db.customers.insertOne({
  name: "Rajesh Rai",
  role: "Administrator",
  active: true,
  createdAt: new Date()
});
// Response: { acknowledged: true, insertedId: ObjectId("...") }

// Query the collection:
db.customers.find();

// Exit shell:
exit;

Step 6: Hardening Security and Configuring Authentication

By default, MongoDB allows unauthenticated administrative connections on localhost (127.0.0.1:27017).

For production servers, create an administrative user account in the admin database, then enable role-based authorization in /etc/mongod.conf:

Follow these security hardening steps:

// Step 1: Open mongosh and switch to admin database:
// mongosh
use admin;

// Step 2: Create root administrative user:
db.createUser({
  user: "adminUser",
  pwd: "SuperSecretPassword123!",
  roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
});
exit;

Enabling Authorization in /etc/mongod.conf

Open /etc/mongod.conf and locate the security: section.

Uncomment the section and add authorization: "enabled":

Restart mongod to enforce mandatory authentication:

# In /etc/mongod.conf:
security:
  authorization: "enabled"

# Restart MongoDB service to enforce authentication:
# sudo systemctl restart mongod

# Connect using authentication credentials:
# mongosh -u adminUser -p --authenticationDatabase admin

Troubleshooting and Common Errors

When configuring Ubuntu servers, unexpected permission errors, network timeouts, or lock contention can occur. Review these common issues and verified resolutions:

mongod.service: Failed with result 'core-dump' / Illegal instruction

Cause: The host CPU lacks AVX (Advanced Vector Extensions) instruction set support required by MongoDB 5.0+.

Resolution: Verify CPU support with grep -i avx /proc/cpuinfo. On older CPUs or budget VPS hypervisors, upgrade CPU features or use MongoDB 4.4.

grep -i avx /proc/cpuinfo

Failed to connect to 127.0.0.1:27017: Connection refused

Cause: The mongod daemon is stopped, or port 27017 is blocked by an unconfigured socket.

Resolution: Check sudo systemctl status mongod and inspect /var/log/mongodb/mongod.log for file permission errors.

sudo tail -n 50 /var/log/mongodb/mongod.log

Package mongodb-org has no installation candidate

Cause: The official MongoDB repository list was added for an unsupported Ubuntu codename or GPG key import failed.

Resolution: Verify /etc/apt/sources.list.d/mongodb-org-7.0.list references $(lsb_release -cs) and run sudo apt update.

cat /etc/apt/sources.list.d/mongodb-org-7.0.list

Security Best Practices and Hardening

Ensure net.bindIp in /etc/mongod.conf remains set to 127.0.0.1 unless remote connections across a private VPC are strictly required.

Always enable security.authorization: enabled to prevent unauthorized data access.

Restrict port 27017 access in UFW strictly to trusted application servers when operating across private networks.

Deepen your Linux system administration skills with our related production-tested guides:

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Canonical's default repository packages an unmaintained, older release of MongoDB that lacks modern aggregation features, bug fixes, and security patches. Upstream repositories maintained by MongoDB Inc. guarantee access to current stable releases (7.0 and 8.0).
The legacy mongo shell was deprecated in MongoDB 5.0 and completely removed in MongoDB 6.0+. It has been replaced by mongosh, which includes intelligent syntax highlighting, multi-line editing, and modern JavaScript ES6 support.
By default, MongoDB stores all collections and indexes in /var/lib/mongodb/, writes operational logs to /var/log/mongodb/mongod.log, and runs under the mongodb system user.
While MongoDB can boot with 1 GB of RAM for development, production workloads require at least 2 GB to 4 GB of RAM because MongoDB's WiredTiger storage engine dynamically allocates 50% of total physical RAM to its internal data cache.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Uncategorized•

How to Redirect HTTP to HTTPS in Nginx

If you’re running a website today and it’s still accessible over plain HTTP, you’re already behind. Modern browsers flag non-HTTPS sites as “Not Secure,” search engines favor encrypted websites, and users are far more cautious about where t...

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout