Setting Up the Environment and Mongosh: Complete Configuration of a MongoDB Development Environment
mongosh is the official MongoDB command-line client—it is the most direct tool for interacting with MongoDB.
This tutorial is designed for developers with no prior experience, covering everything from local installation to connecting to Atlas, and from basic mongosh commands to your first ping test.
1. What You'll Learn
- Install MongoDB Community Edition on Windows, macOS, or Linux
- Quickly Deploy a MongoDB Container Using Docker
- Create a free MongoDB Atlas cloud cluster
- Core Usage of the Mongosh Command-Line Client
- VSCode MongoDB Plugin Configuration
- First Database Connection Test (
db.runCommand({ ping: 1 })) - Troubleshooting Common Installation Issues
2. A True Story of a Full-Stack Engineer
(1) Pain Point: Setting up a MongoDB environment from scratch on a new computer
Bob just got a new MacBook Pro M3, and he wants to set up a MongoDB development environment on his brand-new machine:
"I want to get my Node.js code connected to MongoDB and have my first CRUD operation working within 30 minutes. But I used to use Windows, and now I’ve switched to an ARM Mac with an M3 chip—none of the tutorials I’ve found work."
He tried three approaches, all of which failed:
| Solution | Problem |
|---|---|
| ❌ brew install mongodb | M3 ARM architecture has no homebrew/core official formula |
| ❌ Download the .dmg installer | Message: "Cannot open because the developer cannot be verified" |
| ❌ From the MongoDB download page | No macOS ARM version found |
(2) A Solution Using MongoDB and Docker
Use Docker to bypass all local compilation issues.
# 1. Installation Docker Desktop for Mac (Apple Silicon)
# Download from https://www.docker.com/products/docker-desktop/
# 2. Pull MongoDB image
docker pull mongo:7.0
# 3. Start MongoDB Container(Port Forwarding + Data Volume)
docker run -d \
--name mongodb-dev \
-p 27017:27017 \
-v ~/mongodb-data:/data/db \
mongo:7.0
# 4. Use mongosh to connect
mongosh "mongodb://localhost:27017/admin"
# 5. Test Connection
db.runCommand({ ping: 1 })
# { ok: 1 }
(3) Revenue
| Dimension | Native Installation | Docker Installation |
|---|---|---|
| Cross-platform | ❌ Varies by platform | ✅ Build once, run anywhere |
| Multiple Versions Coexisting | ❌ Difficult | ✅ Launching Multiple Containers |
| Complete Uninstallation | ❌ Residual Configuration | ✅ Just delete the container |
| Team Consensus | ⚠️ Depends on OS version | ✅ Image version locked |
| Startup Time | 1–3 minutes | 5–10 seconds |
3. Comparison of Installation Methods
Concept Overview: MongoDB offers four installation methods—Docker containers, Atlas cloud service, native installation (brew/apt/msi), and package managers. The method you choose depends on your use case: Docker is recommended for development environments (cross-platform, isolated, fast); Atlas is recommended for team collaboration (zero-maintenance, global deployment); and native installation is recommended for production environments (best performance).
How It Works: Docker containers isolate the MongoDB process using Linux namespaces, and data is persisted to the host machine via volume mounting. The Atlas cloud service automatically deploys replica sets on AWS, Azure, and GCP, providing automatic backups and monitoring. A native installation runs the mongod process directly, offering optimal performance but requiring manual management.
graph TB
A[MongoDB Installation Methods] --> B[Native Installation<br/>brew/apt/dmg/exe]
A --> C[Docker Container<br/>Recommended for Rapid Development]
A --> D[Atlas Cloud Services<br/>Zero Local Configuration]
A --> E[Package Manager<br/>Homebrew/Chocolatey]
style C fill:#d4edda
style D fill:#d4edda
| Method | Applicability | Difficulty | Recommended Scenarios | Performance |
|---|---|---|---|---|
| Docker | Cross-platform | ⭐ | ⭐⭐⭐ Rapid development | ⚠️ Slight overhead |
| Atlas | Cloud Services | ⭐⭐ | ⭐⭐⭐ Team Collaboration | ✅ Managed Optimization |
| brew/apt Native | Single platform | ⭐⭐ | ⭐⭐ Production environment | ✅ Best |
| Official .dmg/.exe | Graphical | ⭐⭐⭐ | ⭐ One-time use | ✅ Best |
(1) Four Installation Methods
graph TB
A[MongoDB Installation Methods] --> B[Native Installation<br/>brew/apt/dmg/exe]
A --> C[Docker Container<br/>Recommended for Rapid Development]
A --> D[Atlas Cloud Services<br/>Zero Local Configuration]
A --> E[Package Manager<br/>Homebrew/Chocolatey]
style C fill:#d4edda
style D fill:#d4edda
| Method | Applicability | Difficulty | Recommended Scenarios |
|---|---|---|---|
| Docker | Cross-platform | ⭐ | ⭐⭐⭐ Rapid development |
| Atlas | Cloud Services | ⭐⭐ | ⭐⭐⭐ Team Collaboration |
| brew/apt Native | Single platform | ⭐⭐ | ⭐⭐ Production environment |
| Official .dmg/.exe | Graphical | ⭐⭐⭐ | ⭐ One-time use |
(2) Choosing a MongoDB Version
Concept Explanation: MongoDB follows an LTS (Long-Term Support) release strategy, with each major version supported for 3–5 years. When selecting a version, you should prioritize LTS versions over the latest version—LTS versions have been thoroughly tested and come with a long-term guarantee of security updates.
| Version | Release Date | Status | Recommended Use Cases |
|---|---|---|---|
| MongoDB 8.0 | 2024 | Latest LTS Candidate | New Project |
| MongoDB 7.0 | 2023 | Current LTS | Used in this tutorial |
| MongoDB 6.0 | 2022 | Previous LTS | Compatibility-first |
| MongoDB 5.0 | 2021 | Approaching EOL | Not recommended |
▶ Example 1: Version check command
# Inspection mongosh Version
mongosh --version
# mongosh 2.1.0
# Inspection mongod Server Version
mongod --version
# db version v7.0.5
# Through mongosh Check the server version
mongosh "mongodb://localhost:27017" --eval "db.version()"
# 7.0.5
4. Installation via Docker (Recommended)
Concept Overview: Docker is the most recommended way to set up a MongoDB development environment. Docker packages MongoDB and its dependencies into a container, isolating them from the host machine’s file system and network, thereby enabling “build once, run anywhere.” Compared to a native installation, Docker offers the following advantages: cross-platform consistency, support for multiple versions, clean uninstallation, and extremely fast startup (5–10 seconds).
How It Works: A Docker container is essentially an isolated runtime environment for Linux processes. The MongoDB container uses the official image (mongo:7.0), which runs the mongod process internally. Port mapping (-p 27017:27017) exposes the container’s ports to the host machine, and volume mounting (-v ~/mongodb-data:/data/db) persists data to the host machine—ensuring that data is not lost when the container is deleted.
graph LR
A[Host Machine] --> B[Docker Engine]
B --> C[mongodb-dev Container]
C --> D[mongod Process<br/>Port 27017]
A --> E[~/mongodb-data<br/>Mounting Data Volumes]
E --> D
A --> F[mongosh Client<br/>Connect localhost:27017]
F --> D
style C fill:#d4edda
(1) 4.1 Prerequisites
# Installation Docker Desktop
# macOS: Download https://www.docker.com/products/docker-desktop/
# Windows: Download + Enable WSL 2 Backend
# Linux: sudo apt install docker.io docker-compose
# Verification Docker Installation
docker --version
# Docker version 24.0.7, build afdd53b
(2) 4.2 Pull the MongoDB image
# Get the latest stable version
docker pull mongo:7.0
# Pull a specific version(Recommendations)
docker pull mongo:7.0.5
# Pull an image with authentication(Recommended Production Environments)
docker pull mongo:7.0-auth
(3) 4.3 Starting the MongoDB Container
# Standalone Development Mode(Not certified)
docker run -d \
--name mongodb-dev \
-p 27017:27017 \
-v ~/mongodb-data:/data/db \
--restart unless-stopped \
mongo:7.0
# Certified Production Model
docker run -d \
--name mongodb-prod \
-p 27017:27017 \
-v ~/mongodb-data:/data/db \
-e MONGO_INITDB_ROOT_USERNAME=admin \
-e MONGO_INITDB_ROOT_PASSWORD=YourSecurePass123 \
--restart unless-stopped \
mongo:7.0
# Verify the container's running status
docker ps
# CONTAINER ID IMAGE STATUS PORTS
# a1b2c3d4e5f6 mongo:7.0 Up 2 minutes 0.0.0.0:27017->27017/tcp
(4) 4.4 Verifying the Connection
# Use mongosh to connect
mongosh "mongodb://localhost:27017"
# In mongosh
db.runCommand({ ping: 1 })
# { ok: 1 }
(5) 4.5 Common Docker Commands
# View container logs
docker logs mongodb-dev
# Stop the container
docker stop mongodb-dev
# Start the container
docker start mongodb-dev
# Restart the container
docker restart mongodb-dev
# Enter the container
docker exec -it mongodb-dev mongosh
# Delete Container(Data Volume Retention)
docker rm mongodb-dev
# Delete Containers and Data Volumes(Use with caution! Data Loss)
docker rm -v mongodb-dev
5. Native macOS Installation
(1) 5.1 Installing Homebrew
# Add MongoDB Official Tap
brew tap mongodb/brew
# Install the latest stable version
brew install mongodb-community@7.0
# Start MongoDB Services
brew services start mongodb-community@7.0
# Verification
mongosh --version
mongosh "mongodb://localhost:27017" --eval "db.runCommand({ ping: 1 })"
(2) 5.2 Manual Startup (Without Using brew services)
# Start mongod(Specify the data directory and log files)
mongod --dbpath ~/mongodb-data --logpath ~/mongodb.log --fork
# Verification
ps aux | grep mongod
# mongodb 12345 ... mongod --dbpath /Users/.../mongodb-data
▶ Example 2: Complete macOS Installation Process
# === 1. Installation Xcode Command Line Tools ===
xcode-select --install
# === 2. Installation Homebrew(If not yet) ===
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
# === 3. Add MongoDB Tap ===
brew tap mongodb/brew
# === 4. Installation MongoDB ===
brew install mongodb-community@7.0
# === 5. Start the service ===
brew services start mongodb-community@7.0
# === 6. Connection Test ===
mongosh "mongodb://localhost:27017"
# === 7. The First Command ===
db.runCommand({ ping: 1 })
# { ok: 1 }
6. Linux Installation
Ubuntu / Debian
# 1. Import MongoDB GPG key
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
# 2. Add MongoDB repository
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
# 3. Update Package Index
sudo apt update
# 4. Installation MongoDB
sudo apt install -y mongodb-org
# 5. Start the service
sudo systemctl start mongod
sudo systemctl enable mongod
# 6. Verification
sudo systemctl status mongod
mongosh --eval "db.runCommand({ ping: 1 })"
CentOS / RHEL / Fedora
# 1. Add MongoDB Yum repository
sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo << 'EOF'
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
EOF
# 2. Installation
sudo yum install -y mongodb-org
# 3. Start
sudo systemctl start mongod
sudo systemctl enable mongod
7. Windows Installation
(1) 7.1 MSI Installer (Graphical)
1. Visit https://www.mongodb.com/try/download/community
2. Select "Windows" + "msi" + Version 7.0
3. Download MongoDB-windows-x86_64-7.0.x-signed.msi
4. Double-click to install:
✅ Complete Installation Type
✅ Install MongoDB as a Service
✅ Install MongoDB Compass(GUI Tools)
5. After installation is complete,MongoDB Automatic Action Windows Service Start
(2) 7.2 Installing Chocolatey
# 1. Installation Chocolatey(If not yet)
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://community.chocolatey.org/install.ps1'))
# 2. Installation MongoDB
choco install mongodb
# 3. Start
mongod --dbpath C:\data\db
# 4. Connect
mongosh "mongodb://localhost:27017"
▶ Example 3: Complete Windows Installation Process
# === 1. Create a data directory ===
mkdir C:\data\db
# === 2. Start MongoDB ===
mongod --dbpath C:\data\db
# === 3. Connecting Another Device ===
mongosh "mongodb://localhost:27017"
# === 4. Test ===
db.runCommand({ ping: 1 })
# { ok: 1 }
8. Configuring the MongoDB Atlas Cloud Service
Concept Overview: MongoDB Atlas is an official, fully managed cloud database service available on the three major cloud platforms: AWS, Azure, and GCP. Atlas is the best choice for team collaboration and cross-border deployment scenarios—it requires no maintenance, offers automatic backups, supports global deployment, and includes built-in monitoring. Atlas provides a 512 MB permanently free tier (M0 Sandbox), which is sufficient for learning and small projects.
How It Works: Atlas automatically deploys a 3-node replica set on the cloud platform. The Primary node handles write requests, while the two Secondary nodes provide read redundancy and automatic failover. Users manage the cluster, configure network whitelists, and create database users through the Atlas Web console. Connection strings support the mongodb+srv:// format, and cluster nodes are automatically discovered via DNS SRV records.
graph LR
A[Your App] --> B[Atlas Global Clusters<br/>3 Node Replica Set]
B --> C[Primary<br/>Reading and Writing]
B --> D[Secondary 1<br/>Read Redundancy]
B --> E[Secondary 2<br/>Read Redundancy]
B --> F[Automatic Backup<br/>PITR]
B --> G[Monitoring Alerts<br/>Performance Recommendations]
style B fill:#d4edda
(1) 8.1 Creating a Free Cluster
1. Visit https://www.mongodb.com/cloud/atlas/register
2. Sign Up(Google / GitHub OAuth Fastest)
3. Select "Build a Cluster" → "Shared" → "M0 Sandbox"(Free)
4. Cloud Provider:AWS(Recommendations)
5. Region:
- Users in the Middle East:me-central-1 (UAE)
- Users in Brazil:sa-east-1 (São Paulo)
- Japanese users:ap-northeast-1 (Tokyo)
6. Cluster Name:Cluster0
7. Click "Create Cluster"(Waiting 1-3 minutes)
(2) 8.2 Configuring Access Permissions
Steps 1:Create a Database User
- Database Access → Add New Database User
- Username: alice
- Password: YourSecurePass123
- Database User Privileges: Read and write to any database
Steps 2:Configure the Network Whitelist
- Network Access → Add IP Address
- Select "Allow Access from Anywhere"(0.0.0.0/0)
⚠️ For development use only,The production environment should be limited to application servers. IP
(3) 8.3 Retrieving the Connection String
1. Database → Connect → Connect your application
2. Driver: Node.js
3. Version: 5.5 or later
4. Concatenate Strings:
mongodb+srv://alice:YourSecurePass123@cluster0.mongodb.net/mydb?retryWrites=true&w=majority
▶ Example 4: Connecting to an Atlas Cluster
# Use mongosh to connect Atlas
mongosh "mongodb+srv://cluster0.mongodb.net/mydb" --username alice
# Password: ****
# In mongosh
db.runCommand({ ping: 1 })
# { ok: 1 }
# Insert the first document
db.users.insertOne({ name: "Alice", email: "alice@example.com" })
# Search
db.users.find()
# { _id: ObjectId('...'), name: 'Alice', email: 'alice@example.com' }
9. The mongosh Command-Line Client
Concept Overview: mongosh is the official MongoDB command-line client (which replaced the older mongo shell after 2020). It runs on Node.js and supports modern JavaScript syntax, syntax highlighting, auto-completion, and error stack traces. mongosh is the most direct tool for interacting with MongoDB—all database operations can be performed using mongosh.
How It Works: mongosh communicates with the mongod server via the MongoDB Wire Protocol. By default, it connects to port 27017 on the local machine, but it also supports Atlas connection strings and TLS-encrypted connections. mongosh includes the db object (the current database) and global methods (show dbs, use, etc.); all operations are executed using JavaScript syntax.
graph LR
A[mongosh Client] --> B[Wire Protocol]
B --> C[mongod Server-side]
C --> D[WiredTiger Engine]
A --> A1[JavaScript Runtime]
A --> A2[Auto-Complete]
A --> A3[Syntax Highlighting]
style A fill:#cce5ff
| Command Category | Common Commands | Description |
|---|---|---|
| Database | show dbs / use db / db.dropDatabase() |
View, Switch, Delete |
| Collection | show collections / db.createCollection() / db.col.drop() |
Create |
| Document | insertOne/find/updateOne/deleteOne |
CRUD Operations |
| Help | help / db.help() / db.col.help() |
Built-in Documentation |
(1) Start mongosh
# Connect to the default local port
mongosh
# Connect to a specified host and port
mongosh "mongodb://localhost:27017"
# Connect Atlas
mongosh "mongodb+srv://cluster0.mongodb.net/mydb" --username alice
# Connect and execute a single command
mongosh "mongodb://localhost:27017" --eval "db.runCommand({ ping: 1 })"
# Enable verbose Pattern(View the time taken by each command)
mongosh --verbose
(2) Basic mongosh Commands
// === Database Operations ===
show dbs // List all databases
use shopdb // Switch to shopdb Database(If it doesn't exist, create it implicitly)
db // Display the current database
db.dropDatabase() // Delete the current database
// === Set Operations ===
show collections // List all collections in the current database
db.createCollection("products") // Explicitly Creating Sets
db.products.drop() // Delete Set
// === Document Operations ===
db.products.insertOne({ sku: "PHONE-001", price: 599.99 })
db.products.find() // Search All Documents
db.products.find().pretty() // Formatted Output
db.products.countDocuments() // Count the number of documents
// === Help Command ===
help // mongosh Built-in Help
db.help() // Database Command Help
db.products.help() // Set Operations Help
(3) mongosh Keyboard Shortcuts
| Shortcut Key | Function |
|---|---|
↑ / ↓ |
View Command History |
Tab |
Auto-complete |
Ctrl + A |
Jump to top |
Ctrl + E |
Skip to the end of the line |
Ctrl + U |
Delete entire line |
Ctrl + L Clear screen |
|
Ctrl + C |
Cancel the current command |
Ctrl + D / exit |
Exit mongosh |
▶ Example 5: mongosh script file
# === Writing Scripts(setup-mongosh.js) ===
cat > setup-mongosh.js << 'EOF'
// Switch to shopdb
use shopdb;
// Create a User Set
db.users.insertMany([
{ name: "Alice", email: "alice@example.com", age: 28 },
{ name: "Bob", email: "bob@example.com", age: 32 },
{ name: "Charlie", email: "charlie@example.com", age: 25 }
]);
// Create a Product Collection
db.products.insertMany([
{ sku: "PHONE-001", title: "Phone X", price: 599.99, stock: 50 },
{ sku: "LAPTOP-001", title: "Laptop Y", price: 1299.99, stock: 20 }
]);
// Search All Users
print("Users:");
db.users.find().forEach(printjson);
// Search All Products
print("Products:");
db.products.find().forEach(printjson);
EOF
# === Run the script ===
mongosh "mongodb://localhost:27017" setup-mongosh.js
10. VSCode MongoDB Plugin
(1) 10.1 Installing Plugins
1. Open VSCode
2. Extensions (Ctrl+Shift+X)
3. Search "MongoDB for VS Code"
4. Click Install(Official Plug-in,provided by MongoDB Inc.)
(2) 10.2 Connecting to the Database
1. Click the sidebar MongoDB Icon
2. Click "Add Connection"
3. Enter the connection string:
- Local:mongodb://localhost:27017
- Atlas:mongodb+srv://cluster0.mongodb.net/mydb
4. Enter your username and password
5. Select a Database,Browse Collections
(3) 10.3 Common Operations
- Right-Click Menu → "View Documents":Browsing Data
- Right-Click Menu → "Insert Document":Insert Document
- Right-click the document → "Edit Document":Edit
- Right-click the document → "Delete Document":Delete
- Top Toolbar → "Playgrounds":Run mongosh Screenplay
▶ Example 6: Running Queries in VSCode Playgrounds
// VSCode MongoDB Playground
use('shopdb');
db.users.aggregate([
{ $group: { _id: '$age', count: { $sum: 1 } } },
{ $sort: { _id: 1 } }
]);
11. The First Ping Test
Concept Explanation: db.runCommand({ ping: 1 }) is MongoDB’s “heartbeat” command, used to verify that the connection between the client and the server is working properly. A ping test is the first step in establishing a connection to MongoDB—before writing any business logic, you should first use a ping to confirm that the connection is successful. This is a fundamental principle of database debugging.
How It Works: The ping command sends a ping command to the server via the MongoDB Wire Protocol. The server returns { ok: 1 } to indicate a successful connection. The ping response time equals the network round-trip delay plus the server processing time, and can be used to monitor network quality. In Node.js, the ping command is used for endpoint health checks (/healthz) and CI/CD pre-connection tests.
sequenceDiagram
participant App as Client
participant Mongo as MongoDB
App->>Mongo: db.runCommand({ ping: 1 })
Mongo-->>App: { ok: 1 }
Note over App,Mongo: Response Time = Network Latency
App->>Mongo: db.runCommand({ ping: 1 })
Mongo-->>App: { ok: 1, operationTime: ... }
| ping Purpose | Description |
|---|---|
| Connection Verification | Confirm service availability after the first connection |
| Latency Monitoring | Measure network round-trip time |
| Health Check | /healthz Periodic Endpoint Check |
| CI/CD Pre-deployment Checks | Verify database availability before deployment |
(1) 11.1 Why is ping important?
db.runCommand({ ping: 1 }) is MongoDB's "heartbeat" command:
- ✅ Verify that the database connection was successful
- ✅ Measure response time (monitor network latency)
- ✅ For health check endpoints (
/healthz) - ✅ For pre-connection testing in CI/CD
(2) 11.2 Executing in Mongosh
// In mongosh
db.runCommand({ ping: 1 });
// Output:
// { ok: 1 }
// Timestamped ping
const start = Date.now();
const result = db.runCommand({ ping: 1 });
const duration = Date.now() - start;
print(`Ping successful in ${duration}ms`);
printjson(result);
(3) 11.3 Testing Connections in Node.js
// ping-test.js
const { MongoClient } = require('mongodb');
async function testConnection() {
const client = new MongoClient('mongodb://localhost:27017');
try {
const start = Date.now();
await client.connect();
const result = await client.db('admin').command({ ping: 1 });
const duration = Date.now() - start;
console.log(`✅ Connected in ${duration}ms`);
console.log('Ping result:', result);
if (result.ok === 1) {
console.log('🎉 MongoDB connection is healthy!');
} else {
console.error('❌ Ping failed:', result);
}
} catch (err) {
console.error('❌ Connection error:', err.message);
process.exit(1);
} finally {
await client.close();
}
}
testConnection();
▶ Example 7: Complete Health Check Script
// health-check.js
const { MongoClient } = require('mongodb');
const mongoose = require('mongoose');
async function healthCheck() {
const results = {
native_driver: false,
mongoose: false,
timestamp: new Date().toISOString()
};
// 1. Testing Native Drivers
try {
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const ping = await client.db('admin').command({ ping: 1 });
results.native_driver = ping.ok === 1;
await client.close();
console.log('✅ Native driver ping:', ping.ok === 1);
} catch (err) {
console.error('❌ Native driver ping failed:', err.message);
}
// 2. Test mongoose
try {
await mongoose.connect('mongodb://localhost:27017/test');
const adminDb = mongoose.connection.db.admin();
const ping = await adminDb.command({ ping: 1 });
results.mongoose = ping.ok === 1;
await mongoose.disconnect();
console.log('✅ Mongoose ping:', ping.ok === 1);
} catch (err) {
console.error('❌ Mongoose ping failed:', err.message);
}
console.log('\nHealth check results:', JSON.stringify(results, null, 2));
return results;
}
healthCheck();
12. Troubleshooting Common Installation Issues
(1) 12.1 Connection Failure Issues
| Error Message | Cause | Solution |
|---|---|---|
ECONNREFUSED 127.0.0.1:27017 |
mongod not running | brew services start mongodb-community@7.0 |
MongoServerSelectionError: connection timeout |
Network issue or Atlas whitelist not configured | Add IP in Atlas Network Access |
Authentication failed |
Incorrect username or password | Reset password or create a new account |
getaddrinfo ENOTFOUND cluster0.mongodb.net |
DNS resolution failed | Check your network connection or use the IP address |
Operation timed out |
Firewall Blocked | Open Port 27017 |
(2) 12.2 Docker Container Fails to Start
# Check the container logs to find the cause
docker logs mongodb-dev
# Common Mistakes:Port is in use
# Error: bind: address already in use
# Solutions 1:Processes that are occupying ports
lsof -i :27017
kill -9 <PID>
# Solutions 2:Switch to a different port
docker run -d --name mongodb-dev -p 27018:27017 mongo:7.0
mongosh "mongodb://localhost:27018"
(3) 12.3 Insufficient Disk Space
# Check Disk Space
df -h
# MongoDB Default disk space used by the data directory
du -sh ~/mongodb-data
# Cleanup Plan:Settings oplogSize Restrictions(Raid Mode)
mongod --oplogSize 1024
# or use WiredTiger Compression(Enabled by default)
mongod --wiredTigerCollectionConfig blockCompressor=zstd
▶ Example 8: The Complete Troubleshooting Process
# === Steps 1:Inspection mongod Is it running? ===
ps aux | grep mongod | grep -v grep
# === Steps 2:Check Port Listening ===
lsof -iTCP:27017 -sTCP:LISTEN
# === Steps 3:Try connecting ===
mongosh "mongodb://localhost:27017"
# === Steps 4:View mongod Log ===
tail -50 /usr/local/var/log/mongodb/mongo.log
# === Steps 5:Restart the service ===
brew services restart mongodb-community@7.0
# === Steps 6:Test Again ===
mongosh "mongodb://localhost:27017" --eval "db.runCommand({ ping: 1 })"
❓ FAQ
--memory --cpus); (4) Kubernetes + StatefulSet is recommended for production environments.+srv mean in the connection string?mongodb+srv:// is a DNS SRV record format used for MongoDB Atlas to automatically discover cluster nodes. mongodb:// is the traditional format, which requires you to manually specify the host and port.📖 Summary
- MongoDB Installation Methods: Docker (Recommended) / Atlas (Cloud Service) / Native Installation
- Starting Docker:
docker run -d --name mongodb-dev -p 27017:27017 mongo:7.0 - Atlas offers a 512 MB M0 cluster that is free forever
- mongosh is the official MongoDB command-line client (replacing the old mongo shell)
db.runCommand({ ping: 1 })is the standard command for verifying a connection- The VSCode MongoDB plugin supports graphical browsing and running scripts in Playgrounds
- Common installation issues: port conflicts, disk space, firewalls, and whitelist configuration
📝 Exercises
-
Basic Exercise (⭐): Start a MongoDB 7.0 container using Docker, map port 27017, and successfully connect using mongosh to execute
db.runCommand({ ping: 1 }). -
Basic Exercise (⭐): Create a free M0 cluster in MongoDB Atlas, configure an IP whitelist (0.0.0.0/0) and a database user, and connect to Atlas using mongosh.
-
Advanced Exercise (⭐⭐): Execute
use shopdb,db.products.insertOne({...}), anddb.products.find().pretty()in mongosh to understand the implicit creation mechanism for databases and collections. -
Advanced Problem (⭐⭐): Write a Node.js script
ping-test.jsthat uses themongodbnative driver to connect to a local MongoDB instance, executes the ping command, and outputs the response time. -
Advanced Exercise (⭐⭐): Install the MongoDB plugin in VS Code, connect to an Atlas cluster, and run an aggregation query in Playgrounds
db.users.aggregate([{$group: {_id: '$age', count: {$sum: 1}}}]). -
Challenge (⭐⭐⭐): Use Docker Compose to start a 3-node MongoDB replica set (see the official documentation), configure an init script to automatically create users and initialize data, and verify the replica set’s status
rs.status().



