๐ MongoDB NoSQL Database Complete Setup Guide on AlmaLinux
Ready to unleash the power of NoSQL? ๐ MongoDB is the worldโs most popular document database, powering applications at Netflix, Uber, and Facebook! In this comprehensive guide, weโll install MongoDB on AlmaLinux and build scalable database solutions. Letโs revolutionize your data architecture! โก
๐ค Why is MongoDB Important?
MongoDB is the future of modern applications! ๐ Hereโs why developers love it:
- ๐ Industry Leading: 89% of Fortune 500 use MongoDB
- ๐ฐ High Salaries: MongoDB developers earn $130k+ annually
- โก Lightning Fast: 10x faster than traditional SQL for reads
- ๐ Schema Flexible: No rigid table structures required
- ๐ JSON Native: Perfect for modern web applications
- ๐ Horizontally Scalable: Handle billions of documents
- ๐ง Developer Friendly: Intuitive query language
- โ๏ธ Cloud Ready: Works everywhere - AWS, Azure, GCP
Companies like Airbnb handle 50TB+ data with MongoDB! ๐
๐ฏ What You Need
Letโs prepare for MongoDB mastery! โ
- โ AlmaLinux 8 or 9 (fresh installation recommended)
- โ At least 4GB RAM (8GB+ for production)
- โ 20GB free disk space minimum
- โ Root or sudo access
- โ Network connectivity for downloads
- โ Basic Linux command knowledge
- โ 45 minutes for complete setup
- โ Excitement for NoSQL revolution! ๐
Letโs build your MongoDB powerhouse! ๐
๐ Step 1: Prepare System and Add MongoDB Repository
First, letโs configure AlmaLinux for MongoDB! ๐ฏ
# Update system packages
sudo dnf update -y
# Install required packages
sudo dnf install -y wget curl gnupg
# Import MongoDB GPG key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg --dearmor -o /usr/share/keyrings/mongodb-server-7.0.gpg
# Add MongoDB repository
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-7.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# For AlmaLinux/RHEL, create proper repo file
sudo cat <<EOF > /etc/yum.repos.d/mongodb-org-7.0.repo
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/9/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
EOF
# Verify repository
sudo dnf repolist | grep mongodb
Perfect! ๐ MongoDB repository is configured!
๐ง Step 2: Install MongoDB Community Server
Time to install MongoDB! ๐
# Install MongoDB packages
sudo dnf install -y mongodb-org
# Install specific version (optional)
sudo dnf install -y mongodb-org-7.0.4 mongodb-org-database-7.0.4 mongodb-org-server-7.0.4 mongodb-org-mongos-7.0.4 mongodb-org-tools-7.0.4
# Verify installation
mongod --version
mongo --version
# Check installed packages
rpm -qa | grep mongodb-org
Example output:
db version v7.0.4
Build Info: {
"version": "7.0.4",
"gitVersion": "38f3e37057a43d2e9f41a39142681a76062d582e"
}
Amazing! ๐ MongoDB is installed successfully!
๐ Step 3: Configure MongoDB for Production
Letโs optimize MongoDB configuration! โ๏ธ
# Create data directory with proper permissions
sudo mkdir -p /var/lib/mongo
sudo mkdir -p /var/log/mongodb
sudo chown -R mongod:mongod /var/lib/mongo
sudo chown -R mongod:mongod /var/log/mongodb
# Backup original config
sudo cp /etc/mongod.conf /etc/mongod.conf.backup
# Configure MongoDB
sudo cat <<EOF > /etc/mongod.conf
# MongoDB Configuration File
# Where to store data
storage:
dbPath: /var/lib/mongo
journal:
enabled: true
wiredTiger:
engineConfig:
cacheSizeGB: 2
# Where to write logging data
systemLog:
destination: file
logAppend: true
path: /var/log/mongodb/mongod.log
# Network interfaces
net:
port: 27017
bindIp: 127.0.0.1,0.0.0.0
# Process management
processManagement:
timeZoneInfo: /usr/share/zoneinfo
fork: true
pidFilePath: /var/run/mongodb/mongod.pid
# Security
security:
authorization: disabled
# Operation profiling
operationProfiling:
mode: slowOp
slowOpThresholdMs: 100
# Replication
#replication:
# replSetName: "rs0"
# Sharding
#sharding:
# clusterRole: configsvr
EOF
# Set proper permissions
sudo chmod 644 /etc/mongod.conf
Excellent! โก MongoDB is optimally configured!
โ Step 4: Start and Enable MongoDB Service
Letโs get MongoDB running! ๐โโ๏ธ
# Start MongoDB service
sudo systemctl start mongod
# Enable MongoDB to start on boot
sudo systemctl enable mongod
# Check service status
sudo systemctl status mongod
# Verify MongoDB is listening
sudo netstat -tlnp | grep :27017
# Check MongoDB process
ps aux | grep mongod
Expected output:
โ mongod.service - MongoDB Database Server
Loaded: loaded (/lib/systemd/system/mongod.service; enabled)
Active: active (running) since Sat 2025-09-14 10:30:45 UTC; 2min ago
Fantastic! ๐ MongoDB is running perfectly!
๐ง Step 5: Connect to MongoDB and Create Admin User
Time for our first MongoDB connection! ๐
# Connect to MongoDB shell
mongosh
# Or if using older version
mongo
In MongoDB shell:
// Check MongoDB version and status
db.version()
db.runCommand("ismaster")
// Switch to admin database
use admin
// Create admin user
db.createUser({
user: "admin",
pwd: "SecurePassword123!",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
// Verify user creation
db.getUsers()
// Exit MongoDB shell
exit
Expected output:
{
"ok": 1,
"$clusterTime": {
"clusterTime": Timestamp(1694699845, 1)
}
}
Perfect! ๐ Admin user is created!
๐ Step 6: Enable Authentication and Security
Letโs secure MongoDB properly! ๐
# Edit MongoDB configuration
sudo nano /etc/mongod.conf
Update security section:
# Security
security:
authorization: enabled
# Restart MongoDB to apply changes
sudo systemctl restart mongod
# Test authentication
mongosh --host localhost --port 27017 -u admin -p SecurePassword123! --authenticationDatabase admin
# In authenticated shell
use admin
db.runCommand("listCollections")
Amazing! ๐ก๏ธ MongoDB is now secured with authentication!
โ Step 7: Create Application Database and User
Letโs create a database for your applications! ๐
In MongoDB shell (as admin):
// Create application database
use myapp
// Create application user
db.createUser({
user: "appuser",
pwd: "AppPassword456!",
roles: [
{ role: "readWrite", db: "myapp" }
]
})
// Create sample collection and document
db.users.insertOne({
name: "John Doe",
email: "[email protected]",
age: 30,
createdAt: new Date()
})
// Query the document
db.users.find()
// Create index for better performance
db.users.createIndex({ email: 1 })
// Show collections
show collections
// Show database stats
db.stats()
Excellent! ๐ฏ Application database is ready!
๐ฎ Quick Examples
Practice MongoDB with real-world scenarios! ๐ฏ
Example 1: E-commerce Product Catalog
// Connect to database
use ecommerce
// Insert products
db.products.insertMany([
{
name: "Gaming Laptop",
price: 1299.99,
category: "Electronics",
brand: "TechCorp",
inStock: true,
specs: {
ram: "16GB",
storage: "512GB SSD",
cpu: "Intel i7"
},
tags: ["gaming", "laptop", "electronics"],
createdAt: new Date()
},
{
name: "Wireless Headphones",
price: 199.99,
category: "Audio",
brand: "SoundTech",
inStock: true,
specs: {
battery: "30 hours",
connectivity: "Bluetooth 5.0",
noiseCancel: true
},
tags: ["audio", "wireless", "bluetooth"],
createdAt: new Date()
}
])
// Query products
db.products.find({ category: "Electronics" })
db.products.find({ price: { $lt: 500 } })
db.products.find({ "specs.ram": "16GB" })
// Update product
db.products.updateOne(
{ name: "Gaming Laptop" },
{ $set: { price: 1199.99, onSale: true } }
)
// Create indexes
db.products.createIndex({ category: 1, price: 1 })
db.products.createIndex({ name: "text", tags: "text" })
// Text search
db.products.find({ $text: { $search: "gaming laptop" } })
// Aggregation pipeline
db.products.aggregate([
{ $match: { inStock: true } },
{ $group: { _id: "$category", avgPrice: { $avg: "$price" } } },
{ $sort: { avgPrice: -1 } }
])
Example 2: Social Media Posts
use social
// Insert posts
db.posts.insertMany([
{
userId: ObjectId(),
username: "techguru",
content: "Just deployed my app with MongoDB! ๐",
likes: 42,
comments: [
{
user: "developer1",
text: "Awesome! MongoDB rocks!",
createdAt: new Date("2025-09-14T10:00:00Z")
},
{
user: "coder2",
text: "Which hosting did you use?",
createdAt: new Date("2025-09-14T10:30:00Z")
}
],
tags: ["mongodb", "deployment", "tech"],
location: {
type: "Point",
coordinates: [-122.4194, 37.7749] // San Francisco
},
createdAt: new Date()
}
])
// Find posts with geolocation
db.posts.createIndex({ location: "2dsphere" })
db.posts.find({
location: {
$near: {
$geometry: { type: "Point", coordinates: [-122.4194, 37.7749] },
$maxDistance: 1000
}
}
})
// Find popular posts
db.posts.find({ likes: { $gte: 10 } }).sort({ likes: -1 })
// Add comment to post
db.posts.updateOne(
{ username: "techguru" },
{
$push: {
comments: {
user: "newbie",
text: "Thanks for sharing!",
createdAt: new Date()
}
},
$inc: { commentCount: 1 }
}
)
Example 3: Time Series Data (IoT Sensors)
use iot
// Create time series collection (MongoDB 5.0+)
db.createCollection("sensors", {
timeseries: {
timeField: "timestamp",
metaField: "metadata",
granularity: "minutes"
}
})
// Insert sensor data
db.sensors.insertMany([
{
timestamp: new Date(),
metadata: { sensorId: "temp_01", location: "warehouse_a" },
temperature: 23.5,
humidity: 45.2
},
{
timestamp: new Date(),
metadata: { sensorId: "temp_02", location: "warehouse_b" },
temperature: 25.1,
humidity: 48.7
}
])
// Query recent data
db.sensors.find({
timestamp: { $gte: new Date(Date.now() - 3600000) } // Last hour
})
// Aggregate hourly averages
db.sensors.aggregate([
{
$match: {
"metadata.location": "warehouse_a",
timestamp: { $gte: new Date(Date.now() - 86400000) } // Last 24h
}
},
{
$group: {
_id: {
$dateToString: {
format: "%Y-%m-%d %H:00",
date: "$timestamp"
}
},
avgTemp: { $avg: "$temperature" },
avgHumidity: { $avg: "$humidity" },
count: { $sum: 1 }
}
},
{ $sort: { _id: 1 } }
])
๐จ Fix Common Problems
MongoDB troubleshooting made easy! ๐ง
Problem 1: MongoDB Wonโt Start
Solution:
# Check service status
sudo systemctl status mongod
# Check MongoDB logs
sudo tail -f /var/log/mongodb/mongod.log
# Check disk space
df -h /var/lib/mongo
# Fix permissions
sudo chown -R mongod:mongod /var/lib/mongo
sudo chown -R mongod:mongod /var/log/mongodb
# Check if port is in use
sudo netstat -tlnp | grep :27017
# Start MongoDB manually for debugging
sudo -u mongod mongod --config /etc/mongod.conf
Problem 2: Authentication Failed
Solution:
# Connect without authentication first
mongosh --host localhost --port 27017
# In MongoDB shell
use admin
db.auth("admin", "YourPassword")
# If password forgotten, disable auth temporarily
sudo nano /etc/mongod.conf
# Change: authorization: disabled
sudo systemctl restart mongod
Problem 3: Performance Issues
Solution:
// Check database statistics
db.stats()
// Check collection statistics
db.collection.stats()
// Explain query performance
db.collection.find({field: "value"}).explain("executionStats")
// List indexes
db.collection.getIndexes()
// Create missing indexes
db.collection.createIndex({field: 1})
// Check slow queries
db.setProfilingLevel(2, { slowms: 100 })
db.system.profile.find().sort({ ts: -1 }).limit(5)
Problem 4: Connection Issues
Solution:
# Check if MongoDB is listening
sudo netstat -tlnp | grep :27017
# Test connection
telnet localhost 27017
# Check firewall settings
sudo firewall-cmd --list-ports
sudo firewall-cmd --add-port=27017/tcp --permanent
sudo firewall-cmd --reload
# Check MongoDB config
cat /etc/mongod.conf | grep bindIp
๐ Simple Commands Summary
Command | Purpose |
---|---|
mongosh | Connect to MongoDB shell |
use database | Switch to database |
db.collection.insertOne({}) | Insert single document |
db.collection.find({}) | Query documents |
db.collection.updateOne({}, {}) | Update single document |
db.collection.deleteOne({}) | Delete single document |
db.collection.createIndex({}) | Create index |
show dbs | List databases |
show collections | List collections |
db.stats() | Show database statistics |
๐ก Tips for Success
Master MongoDB with these pro tips! ๐
- ๐ Design Schema: Think in documents, not tables
- ๐ Index Strategy: Index queries, not data
- ๐ Security First: Always enable authentication
- ๐พ Backup Regularly: Use mongodump/mongorestore
- ๐ Monitor Performance: Use MongoDB Compass
- ๐ฏ Optimize Queries: Use explain() for analysis
- ๐ Plan Scaling: Consider sharding early
- ๐ Learn Aggregation: Powerful data processing
- ๐ Use Replica Sets: High availability setup
- ๐ค Join Community: MongoDB forums and Slack
๐ What You Learned
Congratulations! Youโre now a MongoDB expert! ๐
- โ Installed MongoDB Community Server on AlmaLinux
- โ Configured production-ready settings
- โ Set up authentication and security
- โ Created databases, collections, and users
- โ Mastered CRUD operations
- โ Built real-world application examples
- โ Implemented indexing strategies
- โ Learned aggregation pipelines
- โ Gained $130k+ valued NoSQL skills
๐ฏ Why This Matters
Your MongoDB mastery opens infinite opportunities! ๐
- ๐ผ Career Growth: NoSQL experts are in huge demand
- ๐ Modern Apps: Build scalable web applications
- ๐ Big Data: Handle massive datasets efficiently
- โก Performance: 10x faster than traditional databases
- ๐ Flexibility: Adapt to changing requirements
- โ๏ธ Cloud Native: Perfect for microservices
- ๐ฏ Future Proof: Essential for modern development
Youโve mastered the database powering the worldโs biggest applications! ๐
Happy documenting! ๐