- Published on
MongoDB Installation and Setup: Local, Atlas, and Docker
- Authors
- Name
- Mamun Rashid
- @mmncit
MongoDB Installation and Setup: Local, Atlas, and Docker
Now that you understand MongoDB fundamentals, it's time to get your hands dirty! In this guide, we'll cover three different ways to set up MongoDB, from local development to cloud-ready solutions.
🎯 Setup Options Overview
Method | Best For | Pros | Cons |
---|---|---|---|
Local Installation | Development | Full control, offline work | Manual maintenance |
MongoDB Atlas | Production, Learning | Managed service, scalable | Requires internet |
Docker | Development, Testing | Isolated, reproducible | Requires Docker knowledge |
🖥️ Local Installation
Windows Installation
Method 1: MongoDB Installer (Recommended)
Download MongoDB Community Server
- Visit MongoDB Download Center
- Select "Windows x64" and download the MSI file
Run the Installer
# Run as Administrator # Follow the installation wizard # Choose "Complete" installation # Install MongoDB as a Windows Service (recommended)
Verify Installation
# Open Command Prompt or PowerShell mongod --version mongosh --version
Method 2: Using Chocolatey
# Install Chocolatey first (if not installed)
# Then install MongoDB
choco install mongodb
# Start MongoDB service
net start MongoDB
macOS Installation
Method 1: Using Homebrew (Recommended)
# Install Homebrew (if not installed)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# Add MongoDB tap
brew tap mongodb/brew
# Install MongoDB Community Edition
brew install mongodb-community
# Start MongoDB service
brew services start mongodb-community
# Verify installation
mongod --version
mongosh --version
Method 2: Manual Installation
# Download from MongoDB website
curl -O https://fastdl.mongodb.org/osx/mongodb-macos-x86_64-7.0.4.tgz
# Extract
tar -zxvf mongodb-macos-x86_64-7.0.4.tgz
# Move to /usr/local
sudo mv mongodb-macos-x86_64-7.0.4 /usr/local/mongodb
# Add to PATH
echo 'export PATH="/usr/local/mongodb/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
Linux Installation (Ubuntu/Debian)
# Import MongoDB public GPG key
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
# 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
# Update package database
sudo apt-get update
# Install MongoDB
sudo apt-get install -y mongodb-org
# Start MongoDB service
sudo systemctl start mongod
sudo systemctl enable mongod
# Verify installation
mongod --version
mongosh --version
Post-Installation Setup
Create Data Directory
# Windows
mkdir C:\data\db
# macOS/Linux
sudo mkdir -p /data/db
sudo chown $(whoami) /data/db
Start MongoDB Manually
# Start MongoDB server
mongod
# In another terminal, connect with MongoDB Shell
mongosh
Test Your Installation
// In mongosh
show dbs
use testdb
db.testCollection.insertOne({name: "Hello MongoDB!"})
db.testCollection.find()
☁️ MongoDB Atlas (Cloud)
MongoDB Atlas is the official cloud service - perfect for production applications and learning without local setup complexity.
Setting Up Atlas
Create Account
- Visit MongoDB Atlas
- Sign up for free account
- Verify your email
Create Your First Cluster
# Atlas UI steps: # 1. Click "Build a Database" # 2. Choose "FREE" tier (M0 Sandbox) # 3. Select cloud provider (AWS recommended) # 4. Choose region (closest to your location) # 5. Name your cluster (e.g., "learning-cluster") # 6. Click "Create Cluster"
Configure Security
# Database Access: # 1. Go to "Database Access" in left sidebar # 2. Click "Add New Database User" # 3. Choose "Password" authentication # 4. Username: admin (or your choice) # 5. Password: Generate secure password # 6. Database User Privileges: "Atlas admin" # 7. Click "Add User" # Network Access: # 1. Go to "Network Access" in left sidebar # 2. Click "Add IP Address" # 3. Choose "Allow Access from Anywhere" (for learning) # 4. Or add your current IP address # 5. Click "Confirm"
Get Connection String
# 1. Go to "Clusters" and click "Connect" # 2. Choose "Connect your application" # 3. Select "Node.js" and version # 4. Copy connection string # Example connection string: mongodb+srv://admin:<password>@learning-cluster.abc123.mongodb.net/?retryWrites=true&w=majority
Connecting to Atlas
Using MongoDB Shell
# Install mongosh if not already installed
# Replace <password> with your actual password
mongosh "mongodb+srv://admin:<password>@learning-cluster.abc123.mongodb.net/"
# Test connection
show dbs
use sample_db
db.users.insertOne({name: "Atlas User", type: "cloud"})
Environment Variables
# Create .env file
MONGODB_URI=mongodb+srv://admin:<password>@learning-cluster.abc123.mongodb.net/myapp?retryWrites=true&w=majority
🐳 Docker Setup
Docker provides an isolated, reproducible MongoDB environment perfect for development and testing.
Basic Docker Setup
# Pull MongoDB Docker image
docker pull mongo:latest
# Run MongoDB container
docker run --name mongodb-dev \
-p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=password123 \
-d mongo:latest
# Verify container is running
docker ps
Docker Compose (Recommended)
Create docker-compose.yml
:
version: '3.8'
services:
mongodb:
image: mongo:7.0
container_name: mongodb-dev
restart: always
ports:
- '27017:27017'
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: password123
MONGO_INITDB_DATABASE: myapp
volumes:
- mongodb_data:/data/db
- ./init-scripts:/docker-entrypoint-initdb.d
networks:
- mongodb-network
mongo-express:
image: mongo-express:latest
container_name: mongo-express-dev
restart: always
ports:
- '8081:8081'
environment:
ME_CONFIG_MONGODB_ADMINUSERNAME: admin
ME_CONFIG_MONGODB_ADMINPASSWORD: password123
ME_CONFIG_MONGODB_URL: mongodb://admin:password123@mongodb:27017/
depends_on:
- mongodb
networks:
- mongodb-network
volumes:
mongodb_data:
networks:
mongodb-network:
driver: bridge
Running with Docker Compose
# Start services
docker-compose up -d
# Check status
docker-compose ps
# View logs
docker-compose logs mongodb
# Connect with mongosh
docker exec -it mongodb-dev mongosh -u admin -p password123
# Stop services
docker-compose down
# Stop and remove volumes (careful - deletes data!)
docker-compose down -v
Development Database Initialization
Create init-scripts/init.js
:
// This script runs when container starts for the first time
db = db.getSiblingDB('myapp');
// Create a user for the application
db.createUser({
user: 'appuser',
pwd: 'apppassword',
roles: [
{
role: 'readWrite',
db: 'myapp',
},
],
});
// Insert sample data
db.users.insertMany([
{
name: 'John Doe',
email: 'john@example.com',
role: 'admin',
createdAt: new Date(),
},
{
name: 'Jane Smith',
email: 'jane@example.com',
role: 'user',
createdAt: new Date(),
},
]);
db.posts.insertMany([
{
title: 'Getting Started with MongoDB',
author: 'John Doe',
content: 'MongoDB is a powerful NoSQL database...',
tags: ['mongodb', 'tutorial'],
publishedAt: new Date(),
},
]);
print('Database initialized successfully!');
🧭 MongoDB Compass (GUI Tool)
MongoDB Compass is the official GUI tool for MongoDB, perfect for visualizing and manipulating your data.
Installation
# Download from official website
# https://www.mongodb.com/products/compass
# Or using package managers:
# macOS
brew install --cask mongodb-compass
# Windows (Chocolatey)
choco install mongodb-compass
# Linux (Ubuntu/Debian)
wget https://downloads.mongodb.com/compass/mongodb-compass_1.40.4_amd64.deb
sudo dpkg -i mongodb-compass_1.40.4_amd64.deb
Connecting with Compass
Local Connection
# Default local connection string
mongodb://localhost:27017
# With authentication
mongodb://username:password@localhost:27017/database
Atlas Connection
# Use the connection string from Atlas
mongodb+srv://admin:<password>@cluster.abc123.mongodb.net/
Docker Connection
# If using Docker with authentication
mongodb://admin:password123@localhost:27017/
Compass Features
Schema Analysis
- Visual representation of document structure
- Field types and value distributions
- Index usage statistics
Query Builder
- Visual query construction
- Real-time query performance
- Export queries to various languages
Data Visualization
- Document view and editing
- Import/export data
- Aggregation pipeline builder
🔧 Connection Configuration
Connection String Anatomy
mongodb://[username:password@]host[:port][/database][?options]
# Examples:
mongodb://localhost:27017 # Local, no auth
mongodb://user:pass@localhost:27017/mydb # Local with auth
mongodb+srv://user:pass@cluster.net/mydb # Atlas (SRV format)
Common Connection Options
// Node.js connection with options
const { MongoClient } = require('mongodb');
const uri = 'mongodb://localhost:27017/myapp';
const options = {
maxPoolSize: 10, // Maximum number of connections
serverSelectionTimeoutMS: 5000, // How long to try selecting a server
socketTimeoutMS: 45000, // How long a socket stays open
family: 4, // Use IPv4
};
const client = new MongoClient(uri, options);
Environment-Based Configuration
// .env file
NODE_ENV=development
MONGODB_URI_DEV=mongodb://localhost:27017/myapp-dev
MONGODB_URI_PROD=mongodb+srv://admin:pass@cluster.net/myapp
MONGODB_URI_TEST=mongodb://localhost:27017/myapp-test
// config.js
const config = {
development: {
mongodb: {
uri: process.env.MONGODB_URI_DEV,
options: {
maxPoolSize: 5
}
}
},
production: {
mongodb: {
uri: process.env.MONGODB_URI_PROD,
options: {
maxPoolSize: 20,
retryWrites: true,
w: 'majority'
}
}
},
test: {
mongodb: {
uri: process.env.MONGODB_URI_TEST,
options: {
maxPoolSize: 1
}
}
}
};
module.exports = config[process.env.NODE_ENV || 'development'];
🔒 Security Best Practices
1. Authentication
// Always use authentication in production
// Create application-specific users
db.createUser({
user: 'myapp',
pwd: 'securepassword',
roles: [{ role: 'readWrite', db: 'myapp' }],
});
2. Network Security
# Bind to localhost only for development
mongod --bind_ip 127.0.0.1
# Use firewall rules for production
# Only allow necessary IP addresses
3. SSL/TLS
# Atlas uses SSL by default
# For local production deployments:
mongod --sslMode requireSSL --sslPEMKeyFile server.pem
🚀 Testing Your Setup
Let's verify everything is working correctly:
// Basic functionality test
// Connect to your MongoDB instance and run:
// 1. Create a database
use testSetup
// 2. Insert test data
db.setupTest.insertMany([
{ name: "Local Setup", status: "working", timestamp: new Date() },
{ name: "Connection Test", status: "successful", timestamp: new Date() }
]);
// 3. Query data
db.setupTest.find().pretty()
// 4. Create an index
db.setupTest.createIndex({ name: 1 })
// 5. Check indexes
db.setupTest.getIndexes()
// 6. Aggregation test
db.setupTest.aggregate([
{ $group: { _id: "$status", count: { $sum: 1 } } }
])
// 7. Clean up
db.setupTest.drop()
🎯 What's Next?
Congratulations! You now have MongoDB up and running. In the next part, we'll dive into CRUD operations and start building real applications.
👉 Continue to Part 3: CRUD Operations
📚 Quick Reference
Useful Commands
# Start/Stop MongoDB (local)
mongod # Start server
brew services start mongodb-community # macOS service
sudo systemctl start mongod # Linux service
# MongoDB Shell
mongosh # Connect to localhost
mongosh "connection-string" # Connect to remote
# Docker
docker-compose up -d # Start containers
docker-compose logs mongodb # View logs
docker exec -it mongodb-dev mongosh # Connect to container
Default Ports
- MongoDB: 27017
- Mongo Express: 8081
- MongoDB Compass: Uses MongoDB port
🎯 Key Takeaways
✅ Multiple setup options - Choose what works best for your use case
✅ MongoDB Atlas is perfect for learning and production
✅ Docker provides isolated, reproducible environments
✅ MongoDB Compass makes data exploration visual and intuitive
✅ Security should be configured from the beginning
Ready to start creating, reading, updating, and deleting data? Let's explore CRUD operations!
Enjoyed this post?
Subscribe to get notified about new posts and updates. No spam, unsubscribe anytime.
By subscribing, you agree to our Privacy Policy. You can unsubscribe at any time.
Discussion (0)
This website is still under development. If you encounter any issues, please contact me