mongodb

  1. Chapter 1: What is MongoDB?
    1. 1.1 Definition and Simple Explanation
    2. 1.2 History and Evolution of MongoDB
    3. 1.3 NoSQL vs SQL Databases
    4. 1.4 Where MongoDB is Used
    5. 1.5 Why MongoDB Matters
  2. Chapter 2: MongoDB Core Concepts
    1. 2.1 Database Concepts and Terminology
    2. 2.2 BSON Format (Binary JSON)
    3. 2.3 JSON vs BSON
    4. 2.4 MongoDB Architecture Overview
    5. 2.5 Documents and Collections
    6. 2.6 Databases and Namespaces
    7. 2.7 Data Types in MongoDB
    8. 2.8 ObjectId Structure
  3. Chapter 3: How to Install MongoDB on Windows, macOS, and Linux
    1. 3.1 Windows Setup (Step by Step)
      1. Method 1: Using Windows Package Manager (Easiest)
      2. Method 2: Using MongoDB Compass (GUI – No command line)
      3. Troubleshooting Windows
    2. 3.2 macOS Setup (Step by Step)
      1. Method 1: Using Homebrew (Easiest)
      2. Method 2: Manual Installation (Without Homebrew)
      3. Troubleshooting macOS
    3. 3.3 Linux (Ubuntu) Setup (Step by Step)
      1. Step-by-Step for Ubuntu 20.04 / 22.04
      2. Alternative: Install Latest MongoDB (Official method)
      3. Troubleshooting Linux
    4. 3.4 Verifying Your Installation
    5. 3.5 Environment Setup
      1. What you need for professional development:
  4. Chapter 4: MongoDB Shell and GUI Tools
    1. 4.1 MongoDB Shell (mongosh)
    2. 4.2 GUI Tools (MongoDB Compass)
    3. 4.3 Connecting to MongoDB Server
  5. Chapter 5: Basic CRUD Operations
    1. 5.1 Insert Operations (Create)
    2. 5.2 Find Operations (Read)
    3. 5.3 Update Operations
    4. 5.4 Delete Operations
  6. Chapter 6: Query Operators
    1. 6.1 Comparison Operators
    2. 6.2 Logical Operators
    3. 6.3 Element Operators
    4. 6.4 Evaluation Operators
  7. Chapter 7: Working with Data
    1. 7.1 Projection in Queries
    2. 7.2 Sorting and Limiting Results
    3. 7.3 Cursor Behavior
    4. 7.4 Basic Indexing
  8. Chapter 8: Aggregation Framework
    1. 8.1 Introduction to Aggregation
    2. 8.2 Aggregation Pipeline Stages
      1. $match (Filter)
      2. $group (Group by)
      3. $project (Shape documents)
      4. $sort (Sort)
      5. $limit and $skip
      6. $lookup (Join between collections)
      7. $unwind (Flatten arrays)
    3. 8.3 Faceted Aggregation
  9. Chapter 9: Intermediate Topics
    1. 9.1 Data Modeling Principles
    2. 9.2 Embedded vs Referenced Documents
    3. 9.3 Schema Design Patterns
    4. 9.4 Relationships
    5. 9.5 Transactions Basics
    6. 9.6 Bulk Operations
  10. Chapter 10: Advanced Topics
    1. 10.1 Replication (Replica Sets)
    2. 10.2 Sharding (Horizontal Scaling)
    3. 10.3 Performance Optimization
    4. 10.4 Monitoring Tools
    5. 10.5 Security Fundamentals
  11. Chapter 11: Expert & Professional Topics
    1. 11.1 System Design with MongoDB
    2. 11.2 Change Streams
    3. 11.3 Atlas Search (Full-text search)
    4. 11.4 Dockerizing MongoDB
    5. 11.5 Kubernetes Deployment
  12. Chapter 12: Internal Working of MongoDB
    1. 12.1 Client-Server Architecture
    2. 12.2 BSON and Memory Flow
    3. 12.3 Module System and Drivers
    4. 12.4 Execution Flow (Step by Step)
    5. 12.5 Full Pipeline
  13. Chapter 13: Your First Program – Hello MongoDB
    1. 13.1 Step-by-Step Code Explanation
    2. 13.2 Running Your First Query
  14. Chapter 14: Conclusion and Final Skill Stack
    1. After completing this roadmap, you will be able to:
    2. Final Thoughts

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

YearEvent
2007Company “10gen” started working on a cloud platform
200910gen open-sourced MongoDB (name comes from “humongous”)
2010MongoDB gained popularity with developers
2013MongoDB Inc. was formed (10gen renamed)
2015MongoDB went public on NASDAQ
2016MongoDB Atlas (cloud version) launched
2019MongoDB 4.2 added distributed transactions
2020–PresentMongoDB 5.0+ with time series collections and live resharding

1.3 NoSQL vs SQL Databases

FeatureSQL Database (like MySQL, PostgreSQL)NoSQL Database (like MongoDB)
Data storageTables with rows and columnsDocuments (JSON-like)
SchemaFixed (must define structure first)Flexible (can change anytime)
ScalingVertical (bigger server)Horizontal (many servers)
Best forComplex queries, strict dataRapid growth, changing data
Example useBanking, accountingSocial 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

IndustryExample
Web applicationseBay, Craigslist
Mobile appsWeather apps, fitness trackers
Real-time analyticsStock market dashboards
Content managementBlog platforms, CMS
E-commerceProduct catalogs, shopping carts
IoT (Internet of Things)Sensor data storage
MicroservicesEach service has its own database

Companies using MongoDB: Adobe, Google, eBay, Forbes, Toyota, Verizon, Uber (early days).

1.5 Why MongoDB Matters

Benefits:

  1. Flexible schema – Change your data structure without downtime
  2. Scalability – Add more servers easily (horizontal scaling)
  3. Speed – Fast read and write operations
  4. Developer friendly – Uses JSON, which matches how developers think
  5. Rich queries – Powerful aggregation framework
  6. Cloud ready – MongoDB Atlas (managed cloud database)

Chapter 2: MongoDB Core Concepts

2.1 Database Concepts and Terminology

TermSimple Explanation
DatabaseA container for collections (like a folder)
CollectionA group of documents (like a folder inside the database)
DocumentA single record (like a row in SQL, but flexible)
FieldA key-value pair inside a document (like a column)
_idA 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

FeatureJSONBSON
FormatTextBinary
Readable by humansYesNo (need a tool)
SizeSmallerLarger (includes type info)
Speed (scanning)SlowFast
Data typesString, 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

TypeExampleWhen to use
String"Hello"Text
Integer42Whole numbers
Double3.14Decimal numbers
Booleantrue / falseTrue/false values
Array["a", "b"]Lists
Object{key: value}Nested documents
ObjectIdObjectId("...")Unique IDs
DateISODate("2024-01-01")Dates and times
NullnullNo value
BinaryBinData(...)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

ProblemSolution
'mongod' is not recognizedRestart your computer, then try again
Data directory not foundRun mkdir C:\data\db
Port 27017 already in useAnother 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

ProblemSolution
brew: command not foundInstall Homebrew first (see Step 1)
Permission deniedUse sudo before the command
mongosh: command not foundMongoDB 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 + T on 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 mongosh is 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

ProblemSolution
Unable to locate package mongodbRun sudo apt update first
Failed to start mongodb.serviceCheck logs: sudo journalctl -u mongodb
Address already in useAnother 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:

  1. Open MongoDB Compass
  2. Click “Connect” (default connection string is mongodb://localhost:27017)
  3. You will see:
  • Left sidebar: List of databases
  • Main area: Collections and documents
  1. 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:// – Protocol
  • localhost – 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

OperatorMeaningExample
$eqEqual to{ age: { $eq: 25 } }
$neNot equal to{ age: { $ne: 25 } }
$gtGreater than{ age: { $gt: 25 } }
$gteGreater than or equal{ age: { $gte: 25 } }
$ltLess than{ age: { $lt: 25 } }
$lteLess than or equal{ age: { $lte: 25 } }
$inIn an array{ age: { $in: [25, 30, 35] } }
$ninNot 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

OperatorMeaningExample
$andAll conditions true{ $and: [{age: 25}, {name: "Alice"}] }
$orAt least one condition true{ $or: [{age: 25}, {name: "Alice"}] }
$notNegate a condition{ age: { $not: { $gt: 25 } } }
$norNone 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

OperatorMeaningExample
$existsField exists or not{ email: { $exists: true } }
$typeField 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

OperatorMeaningExample
$regexPattern matching{ name: { $regex: /^A/ } } (names starting with A)
$exprUse 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:

  1. Data that is accessed together should be stored together
  2. Consider your application’s query patterns
  3. Avoid unbounded document growth (arrays that grow forever)
  4. 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

PatternUse when
EmbeddingOne-to-one, one-to-few
ReferencingOne-to-many, many-to-many
Subset patternOnly frequently accessed fields in main doc
Computed patternPre-calculate values (e.g., total price)
Bucket patternGroup 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:

  1. Create indexes on fields you query frequently
  2. Use covered queries (index returns all needed data)
  3. Limit result size
  4. Use projection to return only needed fields
  5. Avoid $where and $regex with 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)

  1. User sends HTTP request to web server
  2. Route handler receives request
  3. Controller processes input (validation, parsing)
  4. Service layer interacts with MongoDB via driver
  5. Driver converts query to BSON
  6. Query sent to MongoDB server over TCP
  7. MongoDB parses the query
  8. Query optimizer creates an execution plan
  9. Storage engine (WiredTiger) reads from cache or disk
  10. Results are returned as BSON
  11. Driver converts BSON to native objects (JSON in Node.js, dict in Python)
  12. Controller formats the response
  13. 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:

PartMeaning
dbThe current database reference
usersThe 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:

  1. Receives the insert command
  2. Generates a unique _id (ObjectId)
  3. Converts the document to BSON format
  4. Writes to the storage engine (WiredTiger)
  5. 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.

Scroll to Top