Episode 3 — NodeJS MongoDB Backend Architecture / 3.8 — Database Basics MongoDB
3.8.c — Setting Up MongoDB
Before writing any database code, you need MongoDB running somewhere. This guide covers local installation (macOS, Windows, Linux), MongoDB Compass GUI, the mongosh shell, and MongoDB Atlas cloud setup.
< 3.8.b -- Introduction to MongoDB | 3.8.d -- Data Types and Documents >
Table of Contents
- Installing MongoDB Community (Local)
- MongoDB Compass -- GUI Client
- mongosh -- MongoDB Shell
- Basic Shell Commands
- MongoDB Atlas -- Cloud Setup
- Connection Strings
- Creating Databases and Collections
- Basic CRUD in the Shell
- Verifying Your Setup
- Key Takeaways
- Explain-It Challenge
1. Installing MongoDB Community (Local)
1.1 macOS (Homebrew)
# Step 1: Tap the MongoDB Homebrew formulae
brew tap mongodb/brew
# Step 2: Install MongoDB Community Edition
brew install mongodb-community@7.0
# Step 3: Start MongoDB as a background service
brew services start mongodb-community@7.0
# Step 4: Verify MongoDB is running
brew services list
# Should show: mongodb-community started
# Step 5: Connect with the shell
mongosh
File locations on macOS (Intel):
| Item | Path |
|---|---|
| Config file | /usr/local/etc/mongod.conf |
| Data directory | /usr/local/var/mongodb |
| Log file | /usr/local/var/log/mongodb/mongo.log |
File locations on macOS (Apple Silicon):
| Item | Path |
|---|---|
| Config file | /opt/homebrew/etc/mongod.conf |
| Data directory | /opt/homebrew/var/mongodb |
| Log file | /opt/homebrew/var/log/mongodb/mongo.log |
Useful macOS Commands
# Start MongoDB
brew services start mongodb-community@7.0
# Stop MongoDB
brew services stop mongodb-community@7.0
# Restart MongoDB
brew services restart mongodb-community@7.0
# Check if MongoDB process is running
ps aux | grep mongod
1.2 Windows
Step 1: Download the MSI installer from:
https://www.mongodb.com/try/download/community
Step 2: Run the installer
- Choose "Complete" setup type
- Check "Install MongoDB as a Service"
- Check "Install MongoDB Compass" (GUI)
Step 3: Add MongoDB to PATH (if not automatic):
Add C:\Program Files\MongoDB\Server\7.0\bin to System PATH
Step 4: Verify installation:
Open Command Prompt or PowerShell:
> mongosh
1.3 Linux (Ubuntu/Debian)
# Step 1: Import the MongoDB 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
# Step 2: Add the MongoDB repository
echo "deb [ 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
# Step 3: Update and install
sudo apt-get update
sudo apt-get install -y mongodb-org
# Step 4: Start MongoDB
sudo systemctl start mongod
# Step 5: Enable auto-start on boot
sudo systemctl enable mongod
# Step 6: Verify
sudo systemctl status mongod
mongosh
2. MongoDB Compass -- GUI Client
MongoDB Compass is the official graphical interface for MongoDB. It lets you visually explore databases, run queries, build aggregations, and manage indexes.
Installing Compass
Option 1: Download from https://www.mongodb.com/products/compass
Option 2: Installed automatically with MongoDB on Windows
Option 3: brew install --cask mongodb-compass (macOS)
Connecting with Compass
1. Open MongoDB Compass
2. In the connection string field, enter:
- Local: mongodb://localhost:27017
- Atlas: mongodb+srv://username:password@cluster.xxxxx.mongodb.net/
3. Click "Connect"
What You Can Do in Compass
| Feature | Description |
|---|---|
| Browse databases | See all databases and their sizes |
| Browse collections | View documents in a collection |
| Visual query builder | Build find queries with a GUI |
| Aggregation pipeline | Build complex aggregations step by step |
| Schema analysis | Analyze the shape of your documents |
| Index management | Create, view, and drop indexes |
| Performance | View real-time performance metrics |
| Validation | Set JSON schema validation rules |
| Import / Export | Import CSV/JSON or export data |
Compass Screenshot Layout
+--------------------------------------------------+
| MongoDB Compass |
+--------------------------------------------------+
| Connection: mongodb://localhost:27017 |
+--------+-----------------------------------------+
| DBs | Collection: users |
|--------| |
| myapp | Filter: { age: { $gt: 20 } } |
| users | |
| posts | Documents: |
| orders| { _id: ..., name: "Alice", age: 25 } |
| | { _id: ..., name: "Bob", age: 30 } |
| admin | |
| local | Showing 2 of 2 documents |
+--------+-----------------------------------------+
3. mongosh -- MongoDB Shell
mongosh (MongoDB Shell) is the modern command-line interface for MongoDB. It replaced the legacy mongo shell.
Starting the Shell
# Connect to local MongoDB
mongosh
# Connect to a specific database
mongosh mongodb://localhost:27017/myapp
# Connect to Atlas
mongosh "mongodb+srv://cluster.xxxxx.mongodb.net/myapp" --username myuser
# Connect with authentication (local)
mongosh --username admin --password secret --authenticationDatabase admin
Shell Output
$ mongosh
Current Mongosh Log ID: 64a1b2c3d4e5f6a7b8c9d0e1
Connecting to: mongodb://127.0.0.1:27017/
Using MongoDB: 7.0.4
Using Mongosh: 2.1.1
test>
The prompt shows the current database name (e.g., test>).
4. Basic Shell Commands
Database Commands
// Show all databases
show dbs
// Output:
// admin 40.00 KiB
// config 72.00 KiB
// local 40.00 KiB
// Switch to a database (creates it if it does not exist)
use myapp
// Output: switched to db myapp
// Show the current database
db
// Output: myapp
// Drop the current database
db.dropDatabase()
// Output: { ok: 1, dropped: 'myapp' }
Collection Commands
// Show all collections in current database
show collections
// Create a collection explicitly
db.createCollection('users')
// Output: { ok: 1 }
// Create a capped collection (fixed size, circular buffer)
db.createCollection('logs', { capped: true, size: 1048576, max: 1000 })
// Drop a collection
db.users.drop()
// Output: true
// Get collection stats
db.users.stats()
Quick Reference Table
| Command | Description |
|---|---|
show dbs | List all databases |
use <name> | Switch to (or create) a database |
db | Show current database name |
show collections | List collections in current database |
db.createCollection('name') | Create a collection |
db.<collection>.drop() | Drop a collection |
db.dropDatabase() | Drop the current database |
db.stats() | Database statistics |
db.<collection>.countDocuments() | Count documents in a collection |
exit or quit | Exit the shell |
cls or Ctrl+L | Clear the screen |
5. MongoDB Atlas -- Cloud Setup
MongoDB Atlas is the official cloud-hosted MongoDB service. It handles replication, scaling, backups, and monitoring for you.
Step-by-Step Atlas Setup
Step 1: Create an Account
- Go to https://www.mongodb.com/cloud/atlas
- Sign up with email or Google account
Step 2: Create a Free Cluster
- Click "Build a Database"
- Select "M0 FREE" tier
- Choose a cloud provider (AWS, Google Cloud, or Azure)
- Choose a region close to you
- Name your cluster (e.g., "Cluster0")
- Click "Create Cluster"
Step 3: Create a Database User
- Go to "Database Access" in the sidebar
- Click "Add New Database User"
- Choose "Password" authentication
- Enter username and password
- Set role to "Read and write to any database"
- Click "Add User"
Step 4: Configure Network Access
- Go to "Network Access" in the sidebar
- Click "Add IP Address"
- For development: "Allow Access from Anywhere" (0.0.0.0/0)
- For production: add only your server's IP
- Click "Confirm"
Step 5: Get Your Connection String
- Go to "Database" in the sidebar
- Click "Connect" on your cluster
- Choose "Connect your application"
- Select "Node.js" and your version
- Copy the connection string
Your Atlas Connection String
mongodb+srv://username:<password>@cluster0.abc123.mongodb.net/myapp?retryWrites=true&w=majority
| | | |
username password cluster URL database name
Important: Replace
<password>with your actual password and add your database name after the/.
6. Connection Strings
Local Connection
mongodb://localhost:27017/myapp
| | | |
protocol host port database
Atlas Connection
mongodb+srv://user:pass@cluster0.abc123.mongodb.net/myapp?retryWrites=true&w=majority
| | | | | |
protocol user pass cluster host database options
Common Connection Options
| Option | Description | Example |
|---|---|---|
retryWrites | Retry failed writes automatically | retryWrites=true |
w | Write concern (majority = acknowledged by majority of nodes) | w=majority |
authSource | Database for authentication | authSource=admin |
ssl | Use SSL/TLS encryption | ssl=true |
connectTimeoutMS | Connection timeout in milliseconds | connectTimeoutMS=10000 |
maxPoolSize | Maximum number of connections in the pool | maxPoolSize=50 |
Using Environment Variables (Best Practice)
# .env file (NEVER commit this to git)
MONGODB_URI=mongodb+srv://user:pass@cluster0.abc123.mongodb.net/myapp?retryWrites=true&w=majority
// In your Node.js app
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI);
# .gitignore -- always include this
.env
node_modules/
7. Creating Databases and Collections
Through the Shell (mongosh)
// Switch to a new database (created on first data insert)
use ecommerce
// Create a collection explicitly
db.createCollection('products')
// Or just insert data -- collection is created automatically
db.customers.insertOne({
name: "Alice",
email: "alice@example.com",
joinedAt: new Date()
})
// Verify
show dbs // ecommerce should now appear
show collections // products, customers
Through Compass
1. Click "Create Database" (green button)
2. Enter database name: "ecommerce"
3. Enter collection name: "products"
4. Click "Create Database"
5. Click "+" next to the database name to add more collections
Through Code (Mongoose)
const mongoose = require('mongoose');
// Connecting creates the database if it does not exist
mongoose.connect('mongodb://localhost:27017/ecommerce');
// Defining a model creates the collection on first use
const Product = mongoose.model('Product', new mongoose.Schema({
name: String,
price: Number
}));
// This creates the "products" collection and inserts a document
await Product.create({ name: 'Widget', price: 9.99 });
8. Basic CRUD in the Shell
Insert Documents
// Insert one document
db.users.insertOne({
name: "Alice",
email: "alice@example.com",
age: 25,
hobbies: ["reading", "hiking"]
})
// Output: { acknowledged: true, insertedId: ObjectId("...") }
// Insert many documents
db.users.insertMany([
{ name: "Bob", email: "bob@example.com", age: 30 },
{ name: "Charlie", email: "charlie@example.com", age: 28 },
{ name: "Diana", email: "diana@example.com", age: 22 }
])
// Output: { acknowledged: true, insertedIds: { '0': ..., '1': ..., '2': ... } }
Find Documents
// Find all documents
db.users.find()
// Find with a filter
db.users.find({ age: { $gt: 25 } })
// Find one document
db.users.findOne({ name: "Alice" })
// Pretty print results
db.users.find().pretty()
// Find with projection (select specific fields)
db.users.find({}, { name: 1, email: 1, _id: 0 })
// Count documents
db.users.countDocuments({ age: { $gte: 25 } })
// Output: 2
Update Documents
// Update one document
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 26, city: "San Francisco" } }
)
// Update many documents
db.users.updateMany(
{ age: { $lt: 25 } },
{ $set: { status: "young" } }
)
// Replace an entire document
db.users.replaceOne(
{ name: "Bob" },
{ name: "Bob", email: "bob_new@example.com", age: 31 }
)
Delete Documents
// Delete one document
db.users.deleteOne({ name: "Diana" })
// Delete many documents
db.users.deleteMany({ age: { $lt: 25 } })
// Delete ALL documents in a collection
db.users.deleteMany({})
Shell CRUD Summary
| Operation | Command | Description |
|---|---|---|
| Create one | db.col.insertOne({...}) | Insert a single document |
| Create many | db.col.insertMany([...]) | Insert multiple documents |
| Read all | db.col.find() | Get all documents |
| Read filtered | db.col.find({filter}) | Get matching documents |
| Read one | db.col.findOne({filter}) | Get first matching document |
| Update one | db.col.updateOne({filter}, {$set: {...}}) | Update first match |
| Update many | db.col.updateMany({filter}, {$set: {...}}) | Update all matches |
| Delete one | db.col.deleteOne({filter}) | Delete first match |
| Delete many | db.col.deleteMany({filter}) | Delete all matches |
9. Verifying Your Setup
Run this checklist to confirm everything works.
Local Setup Verification
# 1. Is MongoDB running?
brew services list | grep mongodb # macOS
sudo systemctl status mongod # Linux
# 2. Can you connect with the shell?
mongosh
# 3. Inside the shell:
show dbs # Should list admin, config, local
use test_verify # Switch to test database
db.test.insertOne({ hello: "world" }) # Insert a document
db.test.find() # Should show your document
db.test.drop() # Clean up
Atlas Verification
# 1. Connect to Atlas from mongosh
mongosh "mongodb+srv://cluster0.abc123.mongodb.net/test" --username youruser
# 2. Inside the shell:
show dbs
use test_verify
db.test.insertOne({ hello: "atlas" })
db.test.find()
db.test.drop()
Node.js Verification
// test-connection.js
const mongoose = require('mongoose');
async function testConnection() {
try {
await mongoose.connect('mongodb://localhost:27017/test_verify');
console.log('Connected to MongoDB successfully!');
const TestModel = mongoose.model('Test', new mongoose.Schema({
message: String
}));
const doc = await TestModel.create({ message: 'Hello MongoDB!' });
console.log('Document created:', doc);
const found = await TestModel.findOne({ message: 'Hello MongoDB!' });
console.log('Document found:', found);
await TestModel.deleteMany({});
console.log('Cleanup complete');
await mongoose.connection.close();
console.log('Connection closed');
} catch (error) {
console.error('Connection failed:', error.message);
}
}
testConnection();
node test-connection.js
# Expected output:
# Connected to MongoDB successfully!
# Document created: { message: 'Hello MongoDB!', _id: ..., __v: 0 }
# Document found: { message: 'Hello MongoDB!', _id: ..., __v: 0 }
# Cleanup complete
# Connection closed
10. Key Takeaways
- Install MongoDB Community locally with Homebrew (macOS), MSI (Windows), or apt (Linux).
- MongoDB Compass is the official GUI for browsing, querying, and managing data visually.
- mongosh is the modern command-line shell for interacting with MongoDB.
- MongoDB Atlas provides a free cloud tier (M0) -- perfect for learning and small projects.
- Connection strings follow the format
mongodb://host:port/db(local) ormongodb+srv://...(Atlas). - Databases and collections are created automatically when you first insert data.
- Always store connection strings in environment variables, never hardcode credentials.
- Verify your setup by inserting, finding, and deleting a test document.
11. Explain-It Challenge
Walk through the complete process of setting up MongoDB for a new project: from installing MongoDB locally, creating a database and collection, inserting a test document through the shell, then connecting from a Node.js script. What are the key differences between using a local database versus MongoDB Atlas? When would you choose one over the other?
< 3.8.b -- Introduction to MongoDB | 3.8.d -- Data Types and Documents >