
How to Install MongoDB on Ubuntu 24
MongoDB, the widely-adopted NoSQL document database, is a go-to choice for developers building modern applications that need flexible data storage and horizontal scaling capabilities. Whether you’re working on a microservices architecture, handling unstructured data, or need rapid prototyping capabilities, MongoDB offers the schema flexibility and performance that traditional relational databases often struggle to provide. This guide walks you through installing MongoDB Community Edition on Ubuntu 24.04 LTS, covering everything from repository setup to securing your installation and troubleshooting common issues that trip up even experienced developers.
How MongoDB Works on Ubuntu Systems
MongoDB operates as a daemon service (mongod) that listens for database connections on port 27017 by default. Unlike traditional SQL databases, MongoDB stores data in BSON (Binary JSON) format within collections, which are analogous to tables in relational databases. The installation process involves adding MongoDB’s official repository to Ubuntu’s package manager, installing the necessary components, and configuring the service to run automatically.
The typical MongoDB installation includes several components:
- mongod – The primary database daemon process
- mongos – Query router for sharded clusters
- mongo – Interactive JavaScript shell (deprecated in newer versions)
- mongosh – New MongoDB shell with enhanced features
Step-by-Step Installation Guide
First, ensure your Ubuntu 24.04 system is up to date and install the required dependencies:
sudo apt update && sudo apt upgrade -y
sudo apt install wget curl gnupg2 software-properties-common apt-transport-https ca-certificates lsb-release
Import MongoDB’s GPG key to verify package authenticity:
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
Add the MongoDB repository to your system’s sources list:
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
Note: At the time of writing, MongoDB’s official repository uses “jammy” (Ubuntu 22.04) packages for Ubuntu 24.04 compatibility. This is normal and works perfectly fine.
Update the package database and install MongoDB:
sudo apt update
sudo apt install mongodb-org -y
Start and enable the MongoDB service:
sudo systemctl start mongod
sudo systemctl enable mongod
sudo systemctl status mongod
Verify the installation by connecting to MongoDB:
mongosh
You should see the MongoDB shell prompt. Test basic functionality:
test> db.runCommand({hello: 1})
test> show dbs
test> exit
Configuration and Security Setup
The default MongoDB configuration file is located at /etc/mongod.conf
. Here’s a basic security-hardened configuration:
# /etc/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 # Change to 0.0.0.0 for remote access (not recommended for production)
processManagement:
timeZoneInfo: /usr/share/zoneinfo
security:
authorization: enabled # Enable authentication
Create an administrative user before enabling authentication:
mongosh
use admin
db.createUser({
user: "admin",
pwd: "your_secure_password_here",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
exit
Restart MongoDB to apply the configuration changes:
sudo systemctl restart mongod
Test authentication:
mongosh -u admin -p your_secure_password_here --authenticationDatabase admin
Performance Optimization and Best Practices
MongoDB performance on Ubuntu can be significantly improved with proper system configuration. Here are essential optimizations:
Disable Transparent Huge Pages (THP), which can cause performance issues:
echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/enabled
echo 'never' | sudo tee /sys/kernel/mm/transparent_hugepage/defrag
# Make permanent by adding to /etc/rc.local
echo 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' | sudo tee -a /etc/rc.local
echo 'echo never > /sys/kernel/mm/transparent_hugepage/defrag' | sudo tee -a /etc/rc.local
Adjust system limits for MongoDB:
# Add to /etc/security/limits.conf
mongodb soft nproc 32000
mongodb hard nproc 32000
mongodb soft nofile 64000
mongodb hard nofile 64000
Configure the proper filesystem for optimal performance. XFS is recommended for production deployments:
sudo mkfs.xfs /dev/your_data_disk
sudo mount -o noatime /dev/your_data_disk /var/lib/mongodb
Common Issues and Troubleshooting
Here are the most frequent issues developers encounter and their solutions:
Issue 1: Service fails to start
sudo journalctl -u mongod -f
sudo chown -R mongodb:mongodb /var/lib/mongodb
sudo chown -R mongodb:mongodb /var/log/mongodb
sudo systemctl restart mongod
Issue 2: Connection refused errors
Check if MongoDB is binding to the correct interface:
sudo netstat -tulpn | grep 27017
# Edit /etc/mongod.conf and modify bindIp setting
sudo systemctl restart mongod
Issue 3: Lock file issues after improper shutdown
sudo rm /var/lib/mongodb/mongod.lock
sudo -u mongodb mongod --repair --dbpath /var/lib/mongodb
sudo systemctl start mongod
Issue 4: Authentication failures
# Temporarily disable auth, recreate user
sudo sed -i 's/authorization: enabled/# authorization: enabled/' /etc/mongod.conf
sudo systemctl restart mongod
MongoDB vs Alternatives Comparison
Feature | MongoDB | PostgreSQL | Redis | CouchDB |
---|---|---|---|---|
Data Model | Document (BSON) | Relational/JSON | Key-Value | Document (JSON) |
Query Language | MongoDB Query Language | SQL | Redis Commands | JavaScript/HTTP |
ACID Compliance | Yes (4.0+) | Yes | Partial | Eventual Consistency |
Horizontal Scaling | Native Sharding | Limited | Clustering | Replication |
Memory Usage | High | Medium | High (In-memory) | Low |
Learning Curve | Medium | High | Low | Medium |
Real-World Use Cases and Examples
MongoDB excels in several scenarios where traditional databases fall short:
Content Management Systems
Perfect for storing articles, user profiles, and dynamic content with varying schemas:
// Example blog post document
{
"_id": ObjectId("..."),
"title": "My Blog Post",
"content": "Post content here...",
"author": {
"name": "John Doe",
"email": "john@example.com"
},
"tags": ["mongodb", "database", "tutorial"],
"publishedAt": ISODate("2024-01-15T10:00:00Z"),
"comments": [
{
"author": "Jane Smith",
"text": "Great article!",
"createdAt": ISODate("2024-01-15T11:30:00Z")
}
]
}
IoT Data Collection
Handling time-series data from sensors with flexible schemas:
// IoT sensor reading
{
"_id": ObjectId("..."),
"deviceId": "sensor_001",
"timestamp": ISODate("2024-01-15T14:23:15Z"),
"location": {
"lat": 40.7128,
"lng": -74.0060
},
"readings": {
"temperature": 23.5,
"humidity": 65.2,
"pressure": 1013.25
}
}
E-commerce Product Catalogs
Managing products with varying attributes across different categories:
// Electronics product
{
"_id": ObjectId("..."),
"name": "Smartphone XYZ",
"category": "electronics",
"price": 699.99,
"specs": {
"screenSize": "6.1 inches",
"storage": "128GB",
"camera": "12MP"
},
"availability": true,
"reviews": []
}
// Clothing product with different schema
{
"_id": ObjectId("..."),
"name": "Cotton T-Shirt",
"category": "clothing",
"price": 24.99,
"specs": {
"material": "100% Cotton",
"sizes": ["S", "M", "L", "XL"],
"colors": ["red", "blue", "green"]
},
"availability": true
}
Integration with Development Environments
MongoDB integrates seamlessly with popular development stacks. For those running development environments on VPS services, here’s how to set up MongoDB with different frameworks:
Node.js with Mongoose
npm install mongoose
// connection.js
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/myapp', {
useNewUrlParser: true,
useUnifiedTopology: true
});
Python with PyMongo
pip install pymongo
# connection.py
from pymongo import MongoClient
client = MongoClient('mongodb://localhost:27017/')
db = client['myapp']
Production Deployment Considerations
For production environments, especially on dedicated servers, consider these additional configurations:
- Set up replica sets for high availability
- Configure sharding for horizontal scaling
- Implement proper backup strategies using mongodump/mongorestore
- Set up monitoring with MongoDB Compass or third-party tools
- Configure SSL/TLS for encrypted connections
Backup and Monitoring Setup
# Create backup script
#!/bin/bash
BACKUP_DIR="/backup/mongodb"
DATE=$(date +%Y%m%d_%H%M%S)
mongodump --host localhost:27017 --out $BACKUP_DIR/backup_$DATE
# Add to crontab for daily backups
0 2 * * * /path/to/backup-script.sh
MongoDB on Ubuntu 24.04 provides a robust foundation for modern applications. The installation process is straightforward, but proper configuration and security setup are crucial for production deployments. Regular monitoring, proper indexing strategies, and understanding your application’s query patterns will ensure optimal performance. For more detailed information, consult the official MongoDB documentation and the Ubuntu Server Guide.

This article incorporates information and material from various online sources. We acknowledge and appreciate the work of all original authors, publishers, and websites. While every effort has been made to appropriately credit the source material, any unintentional oversight or omission does not constitute a copyright infringement. All trademarks, logos, and images mentioned are the property of their respective owners. If you believe that any content used in this article infringes upon your copyright, please contact us immediately for review and prompt action.
This article is intended for informational and educational purposes only and does not infringe on the rights of the copyright owners. If any copyrighted material has been used without proper credit or in violation of copyright laws, it is unintentional and we will rectify it promptly upon notification. Please note that the republishing, redistribution, or reproduction of part or all of the contents in any form is prohibited without express written permission from the author and website owner. For permissions or further inquiries, please contact us.