MongoDB Atlas & Deployment
Checking access...
MongoDB Atlas is MongoDB’s fully-managed cloud database service. It handles backups, monitoring, scaling, and failover so you don’t have to run your own database servers.
Why Atlas?
| Feature | Benefit |
|---|---|
| Zero setup | Cluster provisioned in minutes |
| Automatic backups | Point-in-time recovery |
| Monitoring | Built-in performance advisor |
| Auto-scaling | Scale storage and compute without downtime |
| Global clusters | Deploy to multiple regions |
| Free tier | 512MB storage — enough for learning and prototyping |
Creating a Free Cluster
Step 1: Sign Up
- Go to mongodb.com/atlas
- Sign up with Google or GitHub (fastest)
- Complete the onboarding
Step 2: Create Cluster
- Click Build a Database
- Select M0 Free Tier (Shared)
- Choose a cloud provider (AWS, GCP, or Azure)
- Select the region closest to you
- Click Create Cluster (takes 1-3 minutes)
Step 3: Configure Access
IP Whitelist:
# Allow access from anywhere (development only!)# In Atlas: Security → Network Access → Add IP Address# Enter: 0.0.0.0/0
# For production, add your server's IP:# Enter: Your server's static IPDatabase User:
# Security → Database Access → Add New Database User# Username: myapp_user# Password: (generate a strong password)# Built-in Role: Atlas Admin (or readWrite for specific databases)Step 4: Get Connection String
- Click Connect on your cluster
- Choose Connect your application
- Copy the connection string:
mongodb+srv://myapp_user:<password>@cluster0.abcde.mongodb.net/myapp?retryWrites=true&w=majorityReplace <password> with the user’s password and myapp with your database name.
Connecting from Node.js
const mongoose = require("mongoose");
const uri = "mongodb+srv://myapp_user:your_password@cluster0.abcde.mongodb.net/myapp?retryWrites=true&w=majority";
async function connect() { try { await mongoose.connect(uri, { maxPoolSize: 10, serverSelectionTimeoutMS: 5000, socketTimeoutMS: 45000, }); console.log("Connected to Atlas"); } catch (err) { console.error("Atlas connection error:", err); process.exit(1); }}Connection Best Practices
// Use environment variablesconst uri = `mongodb+srv://${process.env.ATLAS_USER}:${process.env.ATLAS_PASSWORD}@${process.env.ATLAS_CLUSTER}.mongodb.net/${process.env.ATLAS_DB}?retryWrites=true&w=majority`;
// .env fileATLAS_USER=myapp_userATLAS_PASSWORD=your_passwordATLAS_CLUSTER=cluster0.abcdeATLAS_DB=myapp
// Connect once on app startup, reuse the connectionlet cachedDb = null;
async function connectToDatabase() { if (cachedDb) return cachedDb;
const client = await MongoClient.connect(uri); cachedDb = client.db(); return cachedDb;}Atlas UI Tour
Database Dashboard
- Overview: Cluster metrics (connections, operations, latency)
- Collections: Browse and query data
- Search: Create Atlas Search indexes
- Triggers: Serverless functions on DB events
- Monitor: Real-time performance graphs
Key Metrics to Watch
| Metric | Healthy Range | Action if Exceeded |
|---|---|---|
| Connections | Below 80% of limit | Increase pool or scale |
| CPU Utilization | < 70% | Optimize queries or scale |
| Disk IOPS | Below provisioned | Add indexes or scale |
| Query Targeting | scanned/returned < 100 | Add missing indexes |
| Opcounters | Steady, not spiking | Check for inefficient patterns |
Performance Advisor
Atlas’s Performance Advisor automatically detects slow queries and suggests indexes:
// Example suggestion from Performance Advisor// Slow query detected:db.orders.find({ status: "pending", createdAt: { $gt: ISODate("...") } })
// Suggested index:db.orders.createIndex({ status: 1, createdAt: -1 })Backups
Automated Backups
M0 (Free Tier): 7-day continuous backup (restore to any point in 7 days)M2/M5: 7-day continuous backupM10+: 1-35 day continuous backup (configurable)Restore a Backup
- Atlas → Cluster → Backup
- Select a snapshot or point in time
- Click Restore
- Choose: Restore to same cluster or new cluster
Manual Export
# Export via mongodumpmongodump --uri="mongodb+srv://user:pass@cluster.mongodb.net/mydb" --out=./backup
# Import via mongorestoremongorestore --uri="mongodb+srv://user:pass@cluster.mongodb.net/mydb" ./backup/mydbMonitoring & Alerts
Setting Up Alerts
- Atlas → Alerts
- Add Alert
- Configure conditions:
Trigger when: Connections > 80% of max for 5 minutesNotify via: Email (or Slack, PagerDuty, webhook)
Trigger when: CPU > 70% for 10 minutesNotify via: EmailUseful Default Alerts
- Connection count exceeded
- CPU utilization high
- Disk space low (below 20%)
- Replication lag > 10 seconds
- Authentication failures spike
Scaling
Vertical Scaling (Compute)
# M0 Free → M2 ($9/month) → M5 ($15/month) → M10 ($57/month) → etc.# More RAM = better index coverage# More CPU = faster aggregation and complex queries
# Atlas: Cluster → Scale → Select tier → Apply# Zero downtime scalingStorage Scaling
# Atlas auto-scales storage (no downtime)# Default: +10% when usage reaches 90%# Max storage per tier variesHorizontal Scaling (Sharding)
For truly massive datasets (100GB+). Not available on free tier:
// Shard key determines data distribution// Choose a high-cardinality field
sh.shardCollection("mydb.orders", { userId: "hashed" });// Or: sh.shardCollection("mydb.orders", { createdAt: 1 });Security Features
Network Security
// Production: Only allow your app server's IP// VPC Peering: Connect directly to your cloud VPC// PrivateLink: Private connection to Atlas (no public internet)
// IP whitelist examples:// App server: 203.0.113.42/32// VPN: 10.0.0.0/8// CI/CD: Your CI provider's IP rangeEncryption
- In-transit: TLS 1.2+ (enabled by default)
- At-rest: AES-256 encryption (enabled by default)
- Key management: Bring your own key (AWS KMS, Azure Key Vault, GCP Cloud KMS)
Database Auditing
Track all database operations:
Atlas → Security → AuditingFilter by: operations, users, database, collectionRetention: Configurable (7 days - 6 months)Data Explorer
Browse and query data directly from the Atlas UI:
- Atlas → Cluster → Collections
- Select database and collection
- Use the query bar to filter:
// Query bar (JSON){ "status": "active", "age": { "$gte": 25 } }
// Sort{ "createdAt": -1 }
// Projection{ "name": 1, "email": 1 }You can also use the built-in aggregation builder for visual pipeline creation.
Connecting from Different Environments
Local Development
mongoose.connect("mongodb://localhost:27017/myapp");Production (Atlas)
mongoose.connect("mongodb+srv://...");Serverless (AWS Lambda)
import { MongoClient } from "mongodb";
const client = new MongoClient(uri);let cachedClient = null;
export async function handler(event) { // Reuse connection across invocations if (!cachedClient) { cachedClient = await client.connect(); } const db = cachedClient.db("myapp"); // ... query}Containerized (Docker)
// Use environment variablemongoose.connect(process.env.MONGODB_URI);# DockerfileENV MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myappCost Management
| Tier | Cost | Best For |
|---|---|---|
| M0 Free | $0 | Learning, prototyping |
| M2 | ~$9/month | Small apps, low traffic |
| M5 | ~$15/month | Growing apps |
| M10 | ~$57/month | Production, medium traffic |
| M20+ | $120+/month | High traffic, HA required |
Cost-saving tips:
- Use auto-scaling to avoid over-provisioning
- Set up alerts for unexpected cost spikes
- Use TTL indexes to auto-delete old data
- Archive infrequently accessed data to cheaper storage
Quick Reference
# Atlas connection string formatmongodb+srv://<user>:<password>@<cluster>.mongodb.net/<db>?retryWrites=true&w=majority
# Connection in Node.jsmongoose.connect(process.env.MONGODB_URI)
# Common environment variablesMONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myappATLAS_USER=myapp_userATLAS_PASSWORD=your_passwordATLAS_CLUSTER=cluster0.abcde
# Backup commandsmongodump --uri="$MONGODB_URI" --out=./backupmongorestore --uri="$MONGODB_URI" ./backup/mydbPractice Exercises
Free cluster setup: Create a free M0 cluster on Atlas. Configure a database user and IP whitelist. Connect using
mongoshand rundb.adminCommand({ ping: 1 }).Migration: Export a local MongoDB database using
mongodump. Create an Atlas cluster and import the data usingmongorestore. Verify the data with Atlas Data Explorer.Monitoring setup: Configure alerts for: connection count exceeding 50, CPU above 50%, and disk space below 500MB. Trigger each alert and verify delivery.
Connection from Node.js: Write a Node.js script that connects to Atlas, inserts 1000 documents, runs a query with
.explain("executionStats"), and logs the execution stats. Share the output.