Complete Developer Handbook

Master MongoDB
From Basics to Advanced

Your comprehensive guide to NoSQL document databases. Learn CRUD operations, aggregation pipelines, indexing strategies, and cloud deployment with MongoDB Atlas.

mongosh
// Connect to your cluster
mongoose.connect('mongodb+srv://...');
// Insert a document
db.products.insertOne({
name: "Wireless Mouse",
price: 799,
category: "Electronics",
stock: 120
});
// Query with aggregation
db.orders.aggregate([
  { $match: { status: "Delivered" } },
  { $group: { _id: "$user", total: { $sum: "$total" } } }
]);

Learning Path

Fundamentals

Understanding MongoDB architecture and components

What is MongoDB?

MongoDB is a powerful NoSQL document-oriented database that stores data in JSON-like documents (actually BSON - Binary JSON). Unlike traditional SQL databases, MongoDB offers flexible schemas and horizontal scalability.

E-commerce Example: We'll use an online store with Products, Orders, and Contacts collections throughout this guide.

mongod

The database server daemon handling connections and storage

mongosh

Command-line interface for interactive database operations

Compass

GUI tool for visual data exploration and query building

shell_commands.js
// Database Operations
show dbs                    // List all databases
use ecommerce              // Switch/create database
show collections           // List collections
db.dropDatabase()          // Delete current database

// 💡 Pro Tip: 'use' creates DB only after first insert

MongoDB Atlas (Cloud)

  1. 1 Sign up at cloud.mongodb.com
  2. 2 Create a free serverless cluster
  3. 3 Whitelist IP & create database user
  4. 4 Connect using provided URI string

CRUD Operations

Create, Read, Update, and Delete documents

Create (Insert)

Insert documents into collections. MongoDB automatically creates collections if they don't exist.

insertOne()
insertMany()
insert_operations.js
// Insert Products
db.products.insertMany([
  {
    name: "Wireless Mouse",
    price: 799,
    category: "Electronics",
    stock: 120,
    ratings: 4.5,
    tags: ["computer", "accessory"],
    createdAt: new Date()
  },
  {
    name: "Mechanical Keyboard",
    price: 2499,
    category: "Electronics",
    stock: 80,
    ratings: 4.8,
    tags: ["keyboard", "mechanical"],
    createdAt: new Date()
  }
])

// Insert Orders
db.orders.insertMany([
  {
    orderId: "ORD001",
    user: "John Doe",
    products: [
      { name: "Wireless Mouse", qty: 1, price: 799 }
    ],
    total: 3298,
    status: "Delivered",
    createdAt: new Date()
  }
])

Read (Find)

query_operations.js
// Basic Find
db.products.find()
db.products.find().pretty()

// Filter by Field
db.products.find({ category: "Electronics" })

// Comparison Operators
db.products.find({ price: { $gt: 1000 } })
db.products.find({ 
  price: { $gte: 1000, $lte: 50000 } 
})

// Logical Operators
db.products.find({
  $or: [
    { category: "Electronics" },
    { stock: { $lt: 50 } }
  ]
})

// Projection (Select Fields)
db.products.find(
  {}, 
  { name: 1, price: 1, _id: 0 }
)

// Sort & Limit
db.products.find()
  .sort({ price: -1 })
  .limit(2)

Query documents using various operators and options. Use projection to limit returned fields.

Query Operators

$eq Equals
$gt/$gte Greater than
$lt/$lte Less than
$in Match array
$or/$and Logical
$regex Pattern match

Update

Modify existing documents using update operators. Always use specific filters to avoid unintended updates.

$set

Set field value

$inc

Increment/decrement numbers

$push/$pull

Add/remove from arrays

$unset

Remove field

update_operations.js
// Update One Document
db.products.updateOne(
  { name: "Wireless Mouse" },
  { $set: { price: 899 } }
)

// Update Many Documents
db.products.updateMany(
  { category: "Electronics" },
  { $inc: { stock: 10 } }
)

// Add to Array
db.products.updateOne(
  { name: "Wireless Mouse" },
  { $push: { tags: "wireless" } }
)

// Remove from Array
db.products.updateOne(
  { name: "Wireless Mouse" },
  { $pull: { tags: "old" } }
)

// Remove Field
db.products.updateOne(
  { name: "Wireless Mouse" },
  { $unset: { temporaryField: "" } }
)

Delete

Warning

Delete operations are permanent! Always test your query with find() before using deleteMany().

delete_operations.js
// Delete One
db.contacts.deleteOne({ name: "Alice" })

// Delete Many
db.orders.deleteMany({ status: "Delivered" })

// ⚠️ Danger: Delete All (Use with caution!)
db.collection.deleteMany({})

Aggregation Framework

Powerful data processing pipelines

Aggregation pipelines analyze and transform data through stages. Each stage performs an operation, passing results to the next stage like an assembly line. MongoDB supports over 25 aggregation stages!

revenue_analysis.js Pipeline Example
// Total Revenue Calculation
db.orders.aggregate([
  {
    $group: {
      _id: null,
      totalRevenue: { $sum: "$total" },
      avgOrder: { $avg: "$total" },
      count: { $sum: 1 }
    }
  }
])

// Group by Status
db.orders.aggregate([
  {
    $group: {
      _id: "$status",
      totalOrders: { $sum: 1 },
      revenue: { $sum: "$total" }
    }
  },
  { $sort: { revenue: -1 } }
])

// Lookup (Join) Example
db.orders.aggregate([
  {
    $lookup: {
      from: "products",
      localField: "products.name",
      foreignField: "name",
      as: "productDetails"
    }
  }
])

Common Pipeline Stages

$match

Filter documents (like find() query)

$group

Group by field and calculate aggregates (sum, avg, etc.)

$project

Select fields, create computed fields

$sort/$limit

Sort results and limit output

Practical Example: Sales Analysis

db.sales.aggregate([
  // Stage 1: Filter for specific category
  { $match: { category: "Electronics" } },
  
  // Stage 2: Calculate total per item
  { 
    $project: {
      item: 1,
      totalRevenue: { $multiply: ["$price", "$quantity"] }
    }
  },
  
  // Stage 3: Group by category and sum
  {
    $group: {
      _id: "$category",
      totalSales: { $sum: "$totalRevenue" },
      avgPrice: { $avg: "$price" },
      count: { $sum: 1 }
    }
  },
  
  // Stage 4: Sort by revenue descending
  { $sort: { totalSales: -1 } },
  
  // Stage 5: Limit to top 3
  { $limit: 3 }
])

Advanced Topics

Performance, indexing, and administration

Indexing & Performance

Indexes improve read operation speed by allowing MongoDB to locate data without scanning every document. However, they slow down writes.

// Create Index
db.products.createIndex({ name: 1 })  // 1 = ascending, -1 = descending

// Compound Index
db.products.createIndex({ category: 1, price: -1 })

// View Indexes
db.products.getIndexes()

// Analyze Query Performance
db.products.find({ price: { $gt: 5000 } })
  .explain("executionStats")

Trade-off: While indexes improve read performance, they slow down write operations (inserts, updates, deletes) because the index must also be updated.

Admin Commands

db.stats()

Database statistics

db.serverStatus()

Server metrics

db.collection.count()

Document count

db.collection.drop()

Delete collection

Best Practices & Tips

Schema Design

Design schemas based on query patterns, not just structure. Embed data accessed together.

Indexing Strategy

Index frequently queried fields. Use explain() before adding indexes.

Query Optimization

Use projection to return only needed fields. Limit results when possible.

Common Pitfalls to Avoid

  • Not using indexes on frequently queried fields
  • Creating too many indexes (slows writes)
  • Using find() without limits on large collections
  • Storing large unbounded arrays
  • Ignoring explain() output for slow queries

Quick Reference

Essential commands at a glance

CRUD Operations

insertOne() Create single
insertMany() Create multiple
find() Read multiple
findOne() Read single
updateOne() Update single
updateMany() Update multiple
deleteOne() Delete single
deleteMany() Delete multiple

Query Operators

$eq Equal to
$gt / $gte Greater than
$lt / $lte Less than
$in Match any in array
$or / $and Logical operators
$regex Pattern matching
$set Update field
$inc Increment

Aggregation Stages

$match Filter documents
$group Group & aggregate
$project Shape output
$sort Order results
$limit Restrict output
$lookup Join collections
$unwind Deconstruct array
$facet Multi-stage pipelines