mongodb
MongoDB explores a NoSQL, document-oriented database designed to store data in flexible, JSON-like documents rather than rigid rows and tables, making it well-suited for handling unstructured or rapidly evolving data. It covers core concepts like collections, schema flexibility, indexing, and horizontal scaling, examining how this structure allows developers to adapt data models quickly without the constraints of traditional relational databases. This technology blends performance with flexibility, showing how modern applications — from real-time analytics to content management systems — rely on MongoDB’s scalability and adaptability. At its core, MongoDB asks how we can store and manage data in a way that mirrors the natural, often unstructured shape of real-world information. Where flexible data meets scalable performance.

Introduction To Mongodb
- Chapter 1: What is MongoDB?
- Chapter 2: MongoDB Core Concepts
- Chapter 3: How to Install MongoDB on Windows, macOS, and Linux
- Chapter 4: MongoDB Shell and GUI Tools
- Chapter 5: Basic CRUD Operations
- Chapter 6: Query Operators
- Chapter 7: Working with Data
- Chapter 8: Aggregation Framework
- Chapter 9: Intermediate Topics
- Chapter 10: Advanced Topics
- Chapter 11: Expert & Professional Topics
- Chapter 12: Internal Working of MongoDB
- Chapter 13: Your First Program – Hello MongoDB
- Chapter 14: Conclusion and Final Skill Stack
Chapter 1: What is MongoDB?
1.1 Definition and Simple Explanation
MongoDB is a database that stores information in a very flexible way. Unlike traditional databases that use tables and rows (like a spreadsheet), MongoDB uses documents that look like JSON (JavaScript Object Notation).
A simple analogy for a child:
Imagine you have a backpack. In a traditional database (like SQL), every backpack must have the same pockets in the same places. If you want to add a new pocket, you have to change every backpack.
In MongoDB, each backpack can be different. One backpack can have a water bottle pocket. Another backpack can have a laptop sleeve. A third backpack can have both. You don’t need to change all backpacks when you add something new. That is MongoDB – flexible and easy to change.
Formal definition:
MongoDB is a NoSQL, document-oriented database designed for high scalability, flexibility, and performance. Unlike traditional relational databases that store data in tables and rows, MongoDB stores data as flexible JSON-like documents (internally BSON), allowing dynamic schemas.
1.2 History and Evolution of MongoDB
| Year | Event |
|---|---|
| 2007 | Company “10gen” started working on a cloud platform |
| 2009 | 10gen open-sourced MongoDB (name comes from “humongous”) |
| 2010 | MongoDB gained popularity with developers |
| 2013 | MongoDB Inc. was formed (10gen renamed) |
| 2015 | MongoDB went public on NASDAQ |
| 2016 | MongoDB Atlas (cloud version) launched |
| 2019 | MongoDB 4.2 added distributed transactions |
| 2020–Present | MongoDB 5.0+ with time series collections and live resharding |
1.3 NoSQL vs SQL Databases
| Feature | SQL Database (like MySQL, PostgreSQL) | NoSQL Database (like MongoDB) |
|---|---|---|
| Data storage | Tables with rows and columns | Documents (JSON-like) |
| Schema | Fixed (must define structure first) | Flexible (can change anytime) |
| Scaling | Vertical (bigger server) | Horizontal (many servers) |
| Best for | Complex queries, strict data | Rapid growth, changing data |
| Example use | Banking, accounting | Social media, catalogs |
Simple comparison:
- SQL is like a parking lot with painted spots. Every car must fit exactly in its spot.
- MongoDB is like an open field. You can park any car anywhere, and you can rearrange anytime.
1.4 Where MongoDB is Used
| Industry | Example |
|---|---|
| Web applications | eBay, Craigslist |
| Mobile apps | Weather apps, fitness trackers |
| Real-time analytics | Stock market dashboards |
| Content management | Blog platforms, CMS |
| E-commerce | Product catalogs, shopping carts |
| IoT (Internet of Things) | Sensor data storage |
| Microservices | Each service has its own database |
Companies using MongoDB: Adobe, Google, eBay, Forbes, Toyota, Verizon, Uber (early days).
1.5 Why MongoDB Matters
Benefits:
- Flexible schema – Change your data structure without downtime
- Scalability – Add more servers easily (horizontal scaling)
- Speed – Fast read and write operations
- Developer friendly – Uses JSON, which matches how developers think
- Rich queries – Powerful aggregation framework
- Cloud ready – MongoDB Atlas (managed cloud database)
Chapter 2: MongoDB Core Concepts
2.1 Database Concepts and Terminology
| Term | Simple Explanation |
|---|---|
| Database | A container for collections (like a folder) |
| Collection | A group of documents (like a folder inside the database) |
| Document | A single record (like a row in SQL, but flexible) |
| Field | A key-value pair inside a document (like a column) |
| _id | A unique identifier for each document |
Hierarchy:Database → Collection → Document → Field
2.2 BSON Format (Binary JSON)
BSON stands for Binary JSON. MongoDB stores data in BSON format, not plain JSON.
Why BSON?
- JSON is text (human readable but slow for computers)
- BSON is binary (fast for computers to read and write)
- BSON supports more data types (dates, ObjectId, binary data)
2.3 JSON vs BSON
| Feature | JSON | BSON |
|---|---|---|
| Format | Text | Binary |
| Readable by humans | Yes | No (need a tool) |
| Size | Smaller | Larger (includes type info) |
| Speed (scanning) | Slow | Fast |
| Data types | String, number, boolean, null, array, object | + Date, ObjectId, Binary, Decimal128 |
2.4 MongoDB Architecture Overview
MongoDB uses a client-server architecture:
Application (Client) → Driver → MongoDB Server (mongod) → Storage Engine (WiredTiger) → Disk
Components:
- mongod – The main database server process
- mongos – Router for sharded clusters
- mongosh – Command-line shell
- MongoDB Compass – GUI tool
2.5 Documents and Collections
Document example (JSON-like):
{
"_id": ObjectId("507f1f77bcf86cd799439011"),
"name": "Alice",
"age": 25,
"email": "alice@example.com",
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "cycling"]
}
Collection: A group of documents. Documents in the same collection can have different fields (flexible schema).
2.6 Databases and Namespaces
A namespace is the full name of a collection: database_name.collection_name
Example: myblog.users means the “users” collection inside the “myblog” database.
2.7 Data Types in MongoDB
| Type | Example | When to use |
|---|---|---|
| String | "Hello" | Text |
| Integer | 42 | Whole numbers |
| Double | 3.14 | Decimal numbers |
| Boolean | true / false | True/false values |
| Array | ["a", "b"] | Lists |
| Object | {key: value} | Nested documents |
| ObjectId | ObjectId("...") | Unique IDs |
| Date | ISODate("2024-01-01") | Dates and times |
| Null | null | No value |
| Binary | BinData(...) | Images, files |
2.8 ObjectId Structure
An ObjectId is a 12-byte unique identifier:
4 bytes | 3 bytes | 2 bytes | 3 bytes
---------|-----------|----------|----------
Timestamp| Machine ID| Process ID| Counter
Example: ObjectId("507f1f77bcf86cd799439011")
- First 4 bytes = timestamp (when created)
- Next 3 bytes = machine identifier
- Next 2 bytes = process ID
- Last 3 bytes = random counter
Why this matters: You can extract the creation time from an ObjectId without storing a separate date field!
Chapter 3: How to Install MongoDB on Windows, macOS, and Linux
This section is written so even a child can follow along. Each step is numbered and explained in plain English.
3.1 Windows Setup (Step by Step)
Method 1: Using Windows Package Manager (Easiest)
Step 1: Open Command Prompt as Administrator
- Click the Start button (Windows icon)
- Type “Command Prompt”
- Right-click on it and choose “Run as administrator”
- Click “Yes” when the popup asks for permission
Step 2: Install MongoDB
winget install MongoDB.Server
- Wait for the installation to finish (may take 2–3 minutes)
- You will see a message like “Successfully installed”
Step 3: Create the data folder (required for MongoDB to run)
mkdir C:\data\db
- This creates a folder where MongoDB will store your information
Step 4: Verify the installation
mongod --version
- You should see version information printed on the screen
Step 5: Start MongoDB server
mongod
- You will see many lines of text. The last line should say “Waiting for connections”
- Keep this window open! Do not close it.
Step 6: Open a NEW Command Prompt window (keep the first one running)
- Click Start, type “Command Prompt”, open it normally (not as administrator)
Step 7: Connect to MongoDB
mongosh
- You should see “Connecting to mongodb://127.0.0.1:27017”
- Then you will see a prompt like
test>
Congratulations! You have MongoDB running on Windows.
Method 2: Using MongoDB Compass (GUI – No command line)
Step 1: Go to https://www.mongodb.com/try/download/compass
Step 2: Click “Download” for your Windows version
Step 3: Run the downloaded .exe file
Step 4: Follow the installation wizard (click “Next” several times)
Step 5: Open MongoDB Compass
Step 6: Click “Connect” (default connection string is already filled)
You are now connected! You can create databases and collections by clicking buttons.
Troubleshooting Windows
| Problem | Solution |
|---|---|
'mongod' is not recognized | Restart your computer, then try again |
Data directory not found | Run mkdir C:\data\db |
Port 27017 already in use | Another MongoDB is running. Close other terminals. |
3.2 macOS Setup (Step by Step)
Method 1: Using Homebrew (Easiest)
Step 1: Install Homebrew (if you don’t have it)
- Open Terminal (Finder → Applications → Utilities → Terminal)
- Paste this command and press Enter:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
- Follow the instructions (may take 5 minutes)
Step 2: Add MongoDB tap to Homebrew
brew tap mongodb/brew
Step 3: Install MongoDB
brew install mongodb-community
- Wait for installation to complete
Step 4: Start MongoDB as a background service
brew services start mongodb-community
- You should see “Successfully started”
Step 5: Verify MongoDB is running
mongod --version
Step 6: Connect to MongoDB
mongosh
- You will see a prompt like
test>
Congratulations! You have MongoDB running on macOS.
Method 2: Manual Installation (Without Homebrew)
Step 1: Go to https://www.mongodb.com/try/download/community
Step 2: Select macOS and download the .tgz file
Step 3: Extract the file (double-click it)
Step 4: Move the extracted folder to /usr/local/mongodb
Step 5: Add MongoDB to your PATH:
echo 'export PATH="/usr/local/mongodb/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc
Step 6: Create data directory:
sudo mkdir -p /data/db
sudo chown `id -u` /data/db
Step 7: Start MongoDB:
mongod
Step 8: Open another terminal and run:
mongosh
Troubleshooting macOS
| Problem | Solution |
|---|---|
brew: command not found | Install Homebrew first (see Step 1) |
Permission denied | Use sudo before the command |
mongosh: command not found | MongoDB not fully installed. Try brew reinstall mongodb-community |
3.3 Linux (Ubuntu) Setup (Step by Step)
Step-by-Step for Ubuntu 20.04 / 22.04
Step 1: Open Terminal
- Press
Ctrl + Alt + Ton your keyboard
Step 2: Update your package list
sudo apt update
- Enter your password when asked
Step 3: Install MongoDB
sudo apt install -y mongodb
Step 4: Check that MongoDB installed correctly
mongod --version
Step 5: Start MongoDB service
sudo systemctl start mongodb
Step 6: Enable MongoDB to start automatically when your computer boots
sudo systemctl enable mongodb
Step 7: Check that MongoDB is running
sudo systemctl status mongodb
- You should see “active (running)” in green text
Step 8: Connect to MongoDB
mongosh
- If
mongoshis not found, install it separately:
sudo apt install -y mongodb-mongosh
Congratulations! You have MongoDB running on Ubuntu Linux.
Alternative: Install Latest MongoDB (Official method)
Step 1: Import MongoDB public GPG key
curl -fsSL https://pgp.mongodb.com/server-7.0.asc | sudo gpg -o /usr/share/keyrings/mongodb-server-7.0.gpg --dearmor
Step 2: Add 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
Step 3: Update and install
sudo apt update
sudo apt install -y mongodb-org
Step 4: Start MongoDB
sudo systemctl start mongod
sudo systemctl enable mongod
Step 5: Connect
mongosh
Troubleshooting Linux
| Problem | Solution |
|---|---|
Unable to locate package mongodb | Run sudo apt update first |
Failed to start mongodb.service | Check logs: sudo journalctl -u mongodb |
Address already in use | Another process using port 27017. Run sudo lsof -i :27017 to see what |
3.4 Verifying Your Installation
After installation, run these tests to make sure everything works:
Test 1: Check MongoDB version
mongod --version
Expected output: Shows version number (e.g., v7.0.x)
Test 2: Check MongoDB shell
mongosh --version
Expected output: Shows shell version
Test 3: Connect and run a simple command
mongosh
# Once inside the shell, type:
db.runCommand({ping: 1})
Expected output: { ok: 1 }
Test 4: Create a test database and insert data
mongosh
use test
db.animals.insertOne({name: "cat", age: 3})
db.animals.find()
Expected output: Shows the document you just inserted.
3.5 Environment Setup
What you need for professional development:
1. Code Editor: VS Code (free)
- Download from https://code.visualstudio.com/
- Install MongoDB extension (search for “MongoDB” in extensions)
2. Node.js (if using JavaScript)
- Download from https://nodejs.org/
- Verify:
node --version
3. Python (if using Python)
- Download from https://python.org/
- Verify:
python --version
4. MongoDB Compass (GUI)
- Download from https://www.mongodb.com/products/compass
5. MongoDB Atlas (Cloud – free tier)
- Go to https://www.mongodb.com/atlas
- Sign up for free account
- Create a free cluster (no credit card needed)
Chapter 4: MongoDB Shell and GUI Tools
4.1 MongoDB Shell (mongosh)
What is mongosh?
It is a command-line tool to interact with MongoDB. You type commands, and MongoDB responds.
Basic commands to learn:
// Show all databases
show dbs
// Switch to a database (creates it if it doesn't exist)
use mydb
// Show collections in current database
show collections
// Create a collection (optional – MongoDB creates it automatically)
db.createCollection("users")
// Drop (delete) a collection
db.users.drop()
// Drop the current database
db.dropDatabase()
4.2 GUI Tools (MongoDB Compass)
What is Compass?
It is a graphical interface for MongoDB. Instead of typing commands, you click buttons.
How to use Compass:
- Open MongoDB Compass
- Click “Connect” (default connection string is
mongodb://localhost:27017) - You will see:
- Left sidebar: List of databases
- Main area: Collections and documents
- You can:
- Create databases by clicking “Create Database”
- Insert documents by clicking “Add Data” → “Insert Document”
- View, edit, delete documents visually
4.3 Connecting to MongoDB Server
Default connection string: mongodb://localhost:27017
Parts of the connection string:
mongodb://– Protocollocalhost– Server address (use IP address for remote servers)27017– Default port (can change)
Connect from Node.js:
const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);
await client.connect();
Connect from Python:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
Connect from command line:
mongosh "mongodb://localhost:27017"
Chapter 5: Basic CRUD Operations
CRUD stands for Create, Read, Update, Delete – the four basic operations on any database.
5.1 Insert Operations (Create)
Insert one document:
db.users.insertOne({
name: "Alice",
age: 25,
email: "alice@example.com"
})
Output:
{
"acknowledged": true,
"insertedId": ObjectId("507f1f77bcf86cd799439011")
}
Insert multiple documents:
db.users.insertMany([
{ name: "Bob", age: 30, email: "bob@example.com" },
{ name: "Charlie", age: 35, email: "charlie@example.com" }
])
5.2 Find Operations (Read)
Find all documents:
db.users.find()
Find with condition:
db.users.find({ name: "Alice" })
Find first matching document:
db.users.findOne({ name: "Alice" })
Find with multiple conditions:
db.users.find({ age: 25, name: "Alice" })
5.3 Update Operations
Update one document:
db.users.updateOne(
{ name: "Alice" }, // Filter (which document)
{ $set: { age: 26 } } // Update (what to change)
)
Update multiple documents:
db.users.updateMany(
{ age: { $lt: 30 } }, // All users under 30
{ $set: { status: "young" } } // Add a status field
)
Replace a whole document:
db.users.replaceOne(
{ name: "Alice" },
{ name: "Alice", age: 26, email: "alice_new@example.com", city: "Boston" }
)
5.4 Delete Operations
Delete one document:
db.users.deleteOne({ name: "Bob" })
Delete multiple documents:
db.users.deleteMany({ age: { $lt: 18 } }) // Delete all minors
Delete all documents in a collection:
db.users.deleteMany({})
Chapter 6: Query Operators
6.1 Comparison Operators
| Operator | Meaning | Example |
|---|---|---|
$eq | Equal to | { age: { $eq: 25 } } |
$ne | Not equal to | { age: { $ne: 25 } } |
$gt | Greater than | { age: { $gt: 25 } } |
$gte | Greater than or equal | { age: { $gte: 25 } } |
$lt | Less than | { age: { $lt: 25 } } |
$lte | Less than or equal | { age: { $lte: 25 } } |
$in | In an array | { age: { $in: [25, 30, 35] } } |
$nin | Not in an array | { age: { $nin: [25, 30] } } |
Examples:
// Find users older than 25
db.users.find({ age: { $gt: 25 } })
// Find users age 25, 30, or 35
db.users.find({ age: { $in: [25, 30, 35] } })
6.2 Logical Operators
| Operator | Meaning | Example |
|---|---|---|
$and | All conditions true | { $and: [{age: 25}, {name: "Alice"}] } |
$or | At least one condition true | { $or: [{age: 25}, {name: "Alice"}] } |
$not | Negate a condition | { age: { $not: { $gt: 25 } } } |
$nor | None of the conditions true | { $nor: [{age: 25}, {name: "Alice"}] } |
Examples:
// Find users who are 25 OR named Alice
db.users.find({ $or: [{ age: 25 }, { name: "Alice" }] })
// Find users who are NOT 25 AND NOT named Alice
db.users.find({ $nor: [{ age: 25 }, { name: "Alice" }] })
6.3 Element Operators
| Operator | Meaning | Example |
|---|---|---|
$exists | Field exists or not | { email: { $exists: true } } |
$type | Field is a specific type | { age: { $type: "int" } } |
Examples:
// Find users who have an email field
db.users.find({ email: { $exists: true } })
// Find documents where age is an integer
db.users.find({ age: { $type: "int" } })
6.4 Evaluation Operators
| Operator | Meaning | Example |
|---|---|---|
$regex | Pattern matching | { name: { $regex: /^A/ } } (names starting with A) |
$expr | Use aggregation expressions | { $expr: { $gt: ["$age", "$minAge"] } } |
Example:
// Find names that start with "A"
db.users.find({ name: { $regex: /^A/ } })
Chapter 7: Working with Data
7.1 Projection in Queries
Projection means choosing which fields to return. 1 = include, 0 = exclude.
// Return only name and age (not email)
db.users.find({}, { name: 1, age: 1, _id: 0 })
7.2 Sorting and Limiting Results
// Sort by age ascending (1) or descending (-1)
db.users.find().sort({ age: 1 })
// Limit to 5 results
db.users.find().limit(5)
// Skip first 10 results (pagination)
db.users.find().skip(10).limit(5)
7.3 Cursor Behavior
A cursor is a pointer to query results. You can iterate through it.
const cursor = db.users.find()
cursor.forEach(doc => {
print(doc.name)
})
7.4 Basic Indexing
Indexes make queries faster, like the index in a book.
// Create a single field index
db.users.createIndex({ name: 1 })
// Create a compound index (two fields)
db.users.createIndex({ name: 1, age: -1 })
// See existing indexes
db.users.getIndexes()
// Drop an index
db.users.dropIndex("name_1")
Chapter 8: Aggregation Framework
8.1 Introduction to Aggregation
Aggregation is like SQL’s GROUP BY – it processes data and returns computed results.
Basic structure:
db.collection.aggregate([
{ $stage1: { ... } },
{ $stage2: { ... } },
{ $stage3: { ... } }
])
8.2 Aggregation Pipeline Stages
$match (Filter)
db.orders.aggregate([
{ $match: { status: "completed" } }
])
$group (Group by)
db.orders.aggregate([
{ $group: { _id: "$customerId", total: { $sum: "$amount" } } }
])
$project (Shape documents)
db.users.aggregate([
{ $project: { fullName: { $concat: ["$firstName", " ", "$lastName"] }, age: 1 } }
])
$sort (Sort)
db.orders.aggregate([
{ $sort: { date: -1 } }
])
$limit and $skip
db.orders.aggregate([
{ $sort: { date: -1 } },
{ $skip: 10 },
{ $limit: 5 }
])
$lookup (Join between collections)
db.orders.aggregate([
{
$lookup: {
from: "customers",
localField: "customerId",
foreignField: "_id",
as: "customer"
}
}
])
$unwind (Flatten arrays)
db.orders.aggregate([
{ $unwind: "$items" },
{ $group: { _id: "$items.product", count: { $sum: 1 } } }
])
8.3 Faceted Aggregation
db.products.aggregate([
{
$facet: {
"byCategory": [{ $group: { _id: "$category", count: { $sum: 1 } } }],
"byPrice": [
{ $bucket: { groupBy: "$price", boundaries: [0, 50, 100, 500], default: "Other" } }
]
}
}
])
Chapter 9: Intermediate Topics
9.1 Data Modeling Principles
Golden rules:
- Data that is accessed together should be stored together
- Consider your application’s query patterns
- Avoid unbounded document growth (arrays that grow forever)
- Embed by default, reference when needed
9.2 Embedded vs Referenced Documents
Embedded (store inside):
{
"_id": 1,
"name": "Alice",
"address": {
"street": "123 Main St",
"city": "New York"
}
}
Referenced (store separately):
// users collection
{ "_id": 1, "name": "Alice", "addressId": 100 }
// addresses collection
{ "_id": 100, "street": "123 Main St", "city": "New York" }
9.3 Schema Design Patterns
| Pattern | Use when |
|---|---|
| Embedding | One-to-one, one-to-few |
| Referencing | One-to-many, many-to-many |
| Subset pattern | Only frequently accessed fields in main doc |
| Computed pattern | Pre-calculate values (e.g., total price) |
| Bucket pattern | Group time-series data (e.g., hourly buckets) |
9.4 Relationships
One-to-One (Embed):
{ "_id": 1, "name": "Alice", "passport": { "number": "AB123", "expiry": "2025" } }
One-to-Many (Reference):
// User
{ "_id": 1, "name": "Alice" }
// Posts (each has userId: 1)
Many-to-Many (Two references):
// Students reference courses OR courses reference students
9.5 Transactions Basics
MongoDB supports ACID transactions (multi-document):
const session = client.startSession();
session.startTransaction();
try {
await db.users.updateOne({ _id: 1 }, { $inc: { balance: -100 } }, { session });
await db.users.updateOne({ _id: 2 }, { $inc: { balance: 100 } }, { session });
await session.commitTransaction();
} catch (error) {
await session.abortTransaction();
} finally {
session.endSession();
}
9.6 Bulk Operations
const bulk = db.users.initializeUnorderedBulkOp();
bulk.insert({ name: "Dave" });
bulk.find({ name: "Alice" }).update({ $set: { age: 26 } });
bulk.find({ name: "Bob" }).remove();
bulk.execute();
Chapter 10: Advanced Topics
10.1 Replication (Replica Sets)
A replica set is a group of MongoDB servers that hold the same data.
- Primary – Accepts writes
- Secondaries – Copy data from primary (read-only)
- Arbiter – Votes in elections (no data)
Setup (simplified):
mongod --replSet rs0 --port 27017 --dbpath /data/db1
mongod --replSet rs0 --port 27018 --dbpath /data/db2
mongod --replSet rs0 --port 27019 --dbpath /data/db3
Initialize:
rs.initiate()
rs.add("localhost:27018")
rs.add("localhost:27019")
10.2 Sharding (Horizontal Scaling)
Sharding distributes data across multiple servers.
- Shard – Each server holding part of data
- Shard key – Field used to distribute data
- Mongos – Router
- Config servers – Store metadata
10.3 Performance Optimization
Tips:
- Create indexes on fields you query frequently
- Use covered queries (index returns all needed data)
- Limit result size
- Use projection to return only needed fields
- Avoid
$whereand$regexwith leading wildcard
10.4 Monitoring Tools
// See current operations
db.currentOp()
// Kill a slow operation
db.killOp(opId)
// See database stats
db.stats()
// See collection stats
db.users.stats()
// Enable slow query logging
db.setProfilingLevel(1, { slowms: 100 })
10.5 Security Fundamentals
// Create admin user
use admin
db.createUser({
user: "admin",
pwd: "securePassword",
roles: ["root"]
})
// Enable authentication (mongod --auth)
// Then connect with:
mongosh -u admin -p securePassword --authenticationDatabase admin
// Create read-only user
db.createUser({
user: "reader",
pwd: "readerPass",
roles: [{ role: "read", db: "myapp" }]
})
Chapter 11: Expert & Professional Topics
11.1 System Design with MongoDB
Multi-region deployment:
- Use MongoDB Atlas Global Clusters
- Define zone sharding (users from Europe go to European shard)
11.2 Change Streams
Watch for real-time changes:
const pipeline = [{ $match: { operationType: "insert" } }];
const changeStream = db.users.watch(pipeline);
changeStream.on("change", change => {
console.log("New user:", change.fullDocument);
});
11.3 Atlas Search (Full-text search)
db.collection.aggregate([
{
$search: {
index: "default",
text: { query: "coffee", path: "description" }
}
}
])
11.4 Dockerizing MongoDB
docker-compose.yml:
version: '3.8'
services:
mongodb:
image: mongo:7.0
ports:
- "27017:27017"
environment:
MONGO_INITDB_ROOT_USERNAME: admin
MONGO_INITDB_ROOT_PASSWORD: secret
volumes:
- mongo_data:/data/db
volumes:
mongo_data:
Run:
docker-compose up -d
docker exec -it mongodb mongosh -u admin -p secret
11.5 Kubernetes Deployment
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: mongodb
spec:
serviceName: mongodb
replicas: 3
selector:
matchLabels:
app: mongodb
template:
metadata:
labels:
app: mongodb
spec:
containers:
- name: mongodb
image: mongo:7.0
ports:
- containerPort: 27017
Chapter 12: Internal Working of MongoDB
12.1 Client-Server Architecture
Application (Client) → MongoDB Driver → Network → mongod Process → Storage Engine → Disk
12.2 BSON and Memory Flow
JSON Document → Driver → BSON (binary) → Network → MongoDB Server
↓
WiredTiger Cache (RAM)
↓
Disk (when flushed)
Working Set: The data frequently accessed that lives in RAM. If working set > RAM, performance degrades.
12.3 Module System and Drivers
MongoDB itself does not run application code. Instead:
- Applications use drivers (Node.js, Python, Java, Go, etc.)
- Driver converts app data → BSON
- Sends to MongoDB via TCP protocol (port 27017)
12.4 Execution Flow (Step by Step)
- User sends HTTP request to web server
- Route handler receives request
- Controller processes input (validation, parsing)
- Service layer interacts with MongoDB via driver
- Driver converts query to BSON
- Query sent to MongoDB server over TCP
- MongoDB parses the query
- Query optimizer creates an execution plan
- Storage engine (WiredTiger) reads from cache or disk
- Results are returned as BSON
- Driver converts BSON to native objects (JSON in Node.js, dict in Python)
- Controller formats the response
- Response sent back to client
12.5 Full Pipeline
Code → Driver → BSON Conversion → Network → MongoDB Engine → Storage Engine → Disk/RAM → Result → Driver → Application Output
Chapter 13: Your First Program – Hello MongoDB
13.1 Step-by-Step Code Explanation
Let’s run the classic “Hello World” in MongoDB shell.
Command:
db.users.insertOne({ name: "Hello MongoDB" })
Line-by-line understanding:
| Part | Meaning |
|---|---|
db | The current database reference |
users | The collection name (auto-created if it doesn’t exist) |
insertOne() | A method that inserts a single document |
{ name: "Hello MongoDB" } | The document being inserted (JSON-like) |
What MongoDB does internally:
- Receives the insert command
- Generates a unique
_id(ObjectId) - Converts the document to BSON format
- Writes to the storage engine (WiredTiger)
- Returns acknowledgment and the inserted ID
Output:
{
"acknowledged": true,
"insertedId": ObjectId("507f1f77bcf86cd799439011")
}
13.2 Running Your First Query
Insert Hello World:
use test
db.greetings.insertOne({ message: "Hello MongoDB!" })
Find it:
db.greetings.find()
Expected output:
{ "_id": ObjectId("..."), "message": "Hello MongoDB!" }
Congratulations! You have successfully used MongoDB.
Chapter 14: Conclusion and Final Skill Stack
After completing this roadmap, you will be able to:
✅ Understand NoSQL vs SQL differences
✅ Install MongoDB on Windows, macOS, and Linux
✅ Perform CRUD operations
✅ Write complex queries with operators
✅ Use aggregation pipeline
✅ Design data models (embedded vs referenced)
✅ Create indexes for performance
✅ Set up replication (replica sets)
✅ Scale horizontally with sharding
✅ Secure your database
✅ Monitor performance
✅ Use MongoDB with Node.js/Python
✅ Deploy MongoDB with Docker and Kubernetes
✅ Design large-scale systems with MongoDB
Final Thoughts
To a child starting out:
Imagine you have a giant box of Legos. In a SQL database, every Lego must be the same shape. In MongoDB, you can have different Legos – squares, rectangles, wheels, windows – all in the same box. That flexibility is why developers love MongoDB.
Your journey:
Start with installation. Then learn CRUD. Then aggregation. Then indexing. Then replication and sharding. Each step builds on the last. Use MongoDB Compass to see your data visually. Use the shell to practice commands.
Remember: Every expert was once a beginner. The engineers at Google, eBay, and Adobe started exactly where you are now. Keep practicing, keep building, and you will master MongoDB.
Keep coding. Keep storing. Keep scaling.