Skip to main content

Skillber v1.0 is here!

Learn more

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?

FeatureBenefit
Zero setupCluster provisioned in minutes
Automatic backupsPoint-in-time recovery
MonitoringBuilt-in performance advisor
Auto-scalingScale storage and compute without downtime
Global clustersDeploy to multiple regions
Free tier512MB storage — enough for learning and prototyping

Creating a Free Cluster

Step 1: Sign Up

  1. Go to mongodb.com/atlas
  2. Sign up with Google or GitHub (fastest)
  3. Complete the onboarding

Step 2: Create Cluster

  1. Click Build a Database
  2. Select M0 Free Tier (Shared)
  3. Choose a cloud provider (AWS, GCP, or Azure)
  4. Select the region closest to you
  5. Click Create Cluster (takes 1-3 minutes)

Step 3: Configure Access

IP Whitelist:

Terminal window
# 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 IP

Database User:

Terminal window
# 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

  1. Click Connect on your cluster
  2. Choose Connect your application
  3. Copy the connection string:
mongodb+srv://myapp_user:<password>@cluster0.abcde.mongodb.net/myapp?retryWrites=true&w=majority

Replace <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 variables
const 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 file
ATLAS_USER=myapp_user
ATLAS_PASSWORD=your_password
ATLAS_CLUSTER=cluster0.abcde
ATLAS_DB=myapp
// Connect once on app startup, reuse the connection
let 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

MetricHealthy RangeAction if Exceeded
ConnectionsBelow 80% of limitIncrease pool or scale
CPU Utilization< 70%Optimize queries or scale
Disk IOPSBelow provisionedAdd indexes or scale
Query Targetingscanned/returned < 100Add missing indexes
OpcountersSteady, not spikingCheck 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 backup
M10+: 1-35 day continuous backup (configurable)

Restore a Backup

  1. Atlas → Cluster → Backup
  2. Select a snapshot or point in time
  3. Click Restore
  4. Choose: Restore to same cluster or new cluster

Manual Export

Terminal window
# Export via mongodump
mongodump --uri="mongodb+srv://user:pass@cluster.mongodb.net/mydb" --out=./backup
# Import via mongorestore
mongorestore --uri="mongodb+srv://user:pass@cluster.mongodb.net/mydb" ./backup/mydb

Monitoring & Alerts

Setting Up Alerts

  1. Atlas → Alerts
  2. Add Alert
  3. Configure conditions:
Trigger when: Connections > 80% of max for 5 minutes
Notify via: Email (or Slack, PagerDuty, webhook)
Trigger when: CPU > 70% for 10 minutes
Notify via: Email

Useful Default Alerts

  • Connection count exceeded
  • CPU utilization high
  • Disk space low (below 20%)
  • Replication lag > 10 seconds
  • Authentication failures spike

Scaling

Vertical Scaling (Compute)

Terminal window
# 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 scaling

Storage Scaling

Terminal window
# Atlas auto-scales storage (no downtime)
# Default: +10% when usage reaches 90%
# Max storage per tier varies

Horizontal 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 range

Encryption

  • 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 → Auditing
Filter by: operations, users, database, collection
Retention: Configurable (7 days - 6 months)

Data Explorer

Browse and query data directly from the Atlas UI:

  1. Atlas → Cluster → Collections
  2. Select database and collection
  3. 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 variable
mongoose.connect(process.env.MONGODB_URI);
# Dockerfile
ENV MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myapp

Cost Management

TierCostBest For
M0 Free$0Learning, prototyping
M2~$9/monthSmall apps, low traffic
M5~$15/monthGrowing apps
M10~$57/monthProduction, medium traffic
M20+$120+/monthHigh 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

Terminal window
# Atlas connection string format
mongodb+srv://<user>:<password>@<cluster>.mongodb.net/<db>?retryWrites=true&w=majority
# Connection in Node.js
mongoose.connect(process.env.MONGODB_URI)
# Common environment variables
MONGODB_URI=mongodb+srv://user:pass@cluster.mongodb.net/myapp
ATLAS_USER=myapp_user
ATLAS_PASSWORD=your_password
ATLAS_CLUSTER=cluster0.abcde
# Backup commands
mongodump --uri="$MONGODB_URI" --out=./backup
mongorestore --uri="$MONGODB_URI" ./backup/mydb

Practice Exercises

  1. Free cluster setup: Create a free M0 cluster on Atlas. Configure a database user and IP whitelist. Connect using mongosh and run db.adminCommand({ ping: 1 }).

  2. Migration: Export a local MongoDB database using mongodump. Create an Atlas cluster and import the data using mongorestore. Verify the data with Atlas Data Explorer.

  3. Monitoring setup: Configure alerts for: connection count exceeding 50, CPU above 50%, and disk space below 500MB. Trigger each alert and verify delivery.

  4. 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.