MongoDB is the database layer of your MERN application. Before you can connect Mongoose or store any data, you need MongoDB running somewhere — either as a local service on your machine for development, or as a cloud cluster on MongoDB Atlas for both development and production. In this lesson you will install MongoDB Community Edition locally, start and verify the service, learn the basic mongosh shell commands, and use MongoDB Compass — MongoDB’s official visual GUI — to browse your data and run queries without writing shell commands.
Two Ways to Run MongoDB
| Local MongoDB | MongoDB Atlas (Cloud) | |
|---|---|---|
| Setup effort | Install and start a local service | Create a free account and cluster (~5 minutes) |
| Connection string | mongodb://localhost:27017 |
mongodb+srv://user:pass@cluster.mongodb.net |
| Internet required | No — works offline | Yes |
| Data persistence | Local disk — lost if machine is wiped | Managed cloud storage with backups |
| Best for | Offline development and learning | Team projects, deployment, and cloud-first workflows |
.env file.Installing MongoDB Locally
# ── macOS (Homebrew) ──────────────────────────────────────────────────────────
brew tap mongodb/brew
brew install mongodb-community@7.0
# Start MongoDB as a background service
brew services start mongodb-community@7.0
# Verify it is running
brew services list # should show mongodb-community started
# ── Ubuntu / Debian ───────────────────────────────────────────────────────────
# Import the MongoDB public GPG key
curl -fsSL https://www.mongodb.org/static/pgp/server-7.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
# Add the 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
sudo apt-get update
sudo apt-get install -y mongodb-org
# Start and enable MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
# ── Windows ───────────────────────────────────────────────────────────────────
# Download the .msi installer from: https://www.mongodb.com/try/download/community
# Run the installer — select "Install MongoD as a Service"
# MongoDB starts automatically as a Windows Service
Verifying MongoDB with mongosh
# Open the MongoDB shell
mongosh
# You should see: Current Mongosh Log ID: ... Connecting to: mongodb://127.0.0.1:27017/
# Inside mongosh — run these commands to verify everything works:
db.runCommand({ ping: 1 }) # should print: { ok: 1 }
show dbs # lists all databases
use blogdb # switch to (or create) a database
db.posts.insertOne({ title: "Test post", published: false })
db.posts.find() # should return the document you just inserted
db.posts.drop() # clean up the test collection
exit # quit mongosh
Setting Up MongoDB Atlas (Cloud Option)
Step 1: Sign up at https://cloud.mongodb.com (free — no credit card needed)
Step 2: Create a Free Cluster
→ Click "Build a Database"
→ Choose "M0 Free" tier
→ Select a cloud provider and region closest to you
→ Name your cluster (e.g. "mern-blog-cluster")
→ Click "Create"
Step 3: Create a Database User
→ Security → Database Access → Add New Database User
→ Authentication: Password
→ Username: mern_user
→ Password: (use the auto-generate button — copy it!)
→ Role: "Read and write to any database"
→ Add User
Step 4: Allow Your IP Address
→ Security → Network Access → Add IP Address
→ For development: click "Allow Access from Anywhere" (0.0.0.0/0)
→ Confirm
Step 5: Get Your Connection String
→ Deployment → Database → Connect → Drivers → Node.js
→ Copy the connection string — it looks like:
mongodb+srv://mern_user:<password>@mern-blog-cluster.xxxxx.mongodb.net/
→ Replace <password> with your actual password
→ Add your database name at the end: .../blogdb?retryWrites=true&w=majority
Using MongoDB Compass
Download: https://www.mongodb.com/products/tools/compass
Connecting to local MongoDB:
Connection string: mongodb://localhost:27017
→ Click Connect
Connecting to Atlas:
Connection string: mongodb+srv://mern_user:password@cluster.mongodb.net/
→ Click Connect
What you can do in Compass:
✓ Browse databases and collections visually
✓ Insert, edit, and delete documents with a form UI
✓ Run queries and aggregation pipelines
✓ View indexes and create new ones
✓ Monitor real-time server statistics
✓ Export collections to JSON or CSV
Common Mistakes
Mistake 1 — Forgetting to start the MongoDB service
❌ Wrong — trying to connect from Node.js when MongoDB is not running:
node index.js
# MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017
# ← MongoDB service is not started
✅ Correct — always verify MongoDB is running before starting your Express server:
brew services list # macOS — check mongodb-community is "started"
sudo systemctl status mongod # Linux — check Active: active (running)
mongosh --eval "db.runCommand({ping:1})" # quick ping test
Mistake 2 — Using the Atlas connection string without replacing the password placeholder
❌ Wrong — pasting the Atlas string directly with the <password> placeholder:
mongodb+srv://mern_user:<password>@cluster.mongodb.net/blogdb
# ← <password> is literally in the string — connection will fail
✅ Correct — replace <password> with your actual Atlas database user password before saving to .env:
mongodb+srv://mern_user:MyActualPassword123@cluster.mongodb.net/blogdb?retryWrites=true&w=majority
Mistake 3 — Not adding your IP to the Atlas allowlist
❌ Wrong — connecting from a new machine or network without updating Network Access:
MongoServerSelectionError: connection timed out
← Your current IP address is not on the Atlas allowlist
✅ Correct — in the Atlas UI go to Security → Network Access → Add IP Address. For development you can allow all IPs (0.0.0.0/0). For production, restrict to your server’s specific IP.
Quick Reference
| Task | Command / Action |
|---|---|
| Start MongoDB (macOS) | brew services start mongodb-community@7.0 |
| Stop MongoDB (macOS) | brew services stop mongodb-community@7.0 |
| Start MongoDB (Linux) | sudo systemctl start mongod |
| Open MongoDB shell | mongosh |
| Ping database | db.runCommand({ ping: 1 }) |
| List databases | show dbs |
| Use a database | use blogdb |
| Local connection string | mongodb://localhost:27017/blogdb |
| Atlas connection string | mongodb+srv://user:pass@cluster.mongodb.net/blogdb |