🍃 MongoDB Handbook

Complete guide to mastering MongoDB - from basics to advanced operations

1. Introduction to MongoDB

MongoDB is a powerful NoSQL document-oriented database that stores data in JSON-like documents (actually BSON - Binary JSON). This handbook uses an e-commerce website as the primary example with three main collections:

Step 1: Sign Up

Go to https://cloud.mongodb.com and create a free account

Step 2: Create Cluster

Create a free cluster (Serverless recommended for beginners)

Step 3: Security Setup

Whitelist your IP address and create a database user with credentials

Step 4: Connect

Follow the connection string instructions to connect via mongosh or your application

🌐 Why Use Atlas?

  • No infrastructure management required
  • Automatic backups and monitoring
  • Built-in security features
  • Global distribution capabilities
  • Free tier available for learning and small projects

13. Best Practices & Tips

🎯 Schema Design

Design schemas based on how you'll query data, not just how it's structured. Embed related data that's accessed together.

📊 Indexing Strategy

Create indexes on frequently queried fields. Monitor query performance with explain() before adding indexes.

🔍 Query Optimization

Use projection to return only needed fields. Limit results when possible. Use covered queries with indexes.

💾 Data Management

Regularly backup your data. Use updateOne/updateMany instead of save(). Always test delete operations with find() first.

🔐 Security

Enable authentication. Use role-based access control. Keep MongoDB updated with latest security patches.

📈 Monitoring

Use MongoDB Compass or Atlas for performance monitoring. Watch for slow queries and optimize them with indexes.

Common Pitfalls to Avoid

  • ❌ Not using indexes on frequently queried fields
  • ❌ Creating too many indexes (slows down writes)
  • ❌ Using find() without limits on large collections
  • ❌ Storing large arrays that keep growing
  • ❌ Not validating data before insertion
  • ❌ Ignoring the explain() output for slow queries

14. Quick Reference Cheat Sheet

CRUD Operations

Operation Command Example
Create insertOne(), insertMany() db.products.insertOne({name: "Item"})
Read find(), findOne() db.products.find({price: {$gt: 100}})
Update updateOne(), updateMany() db.products.updateOne({}, {$set: {}})
Delete deleteOne(), deleteMany() db.products.deleteMany({status: "old"})

Query Operators

Operator Description Example
$eq Equal to {price: {$eq: 100}}
$gt / $gte Greater than / Greater than or equal {price: {$gte: 100}}
$lt / $lte Less than / Less than or equal {stock: {$lt: 50}}
$in Match any value in array {category: {$in: ["A", "B"]}}
$or Logical OR {$or: [{a: 1}, {b: 2}]}
$and Logical AND {$and: [{a: 1}, {b: 2}]}

Update Operators

Operator Description Example
$set Set field value {$set: {price: 100}}
$inc Increment value {$inc: {stock: 5}}
$push Add to array {$push: {tags: "new"}}
$pull Remove from array {$pull: {tags: "old"}}
$unset Remove field {$unset: {field: ""}}

2. Key Components

mongod

The MongoDB Server Daemon

Handles database connections, storage, and queries. Must be running before using MongoDB locally.

mongosh

MongoDB Shell

Command-line interface for interacting with MongoDB. Run commands, queries, and scripts directly.

MongoDB Compass

GUI Tool

Visual interface for data exploration, query building, and performance analysis. Perfect for beginners.

Installation

Visit the official MongoDB website to download the community edition - it's free and suitable for most use cases.

3. Basic Shell Commands

Database Operations

show dbs                // List all databases
use ecommerce          // Create or switch to a database
show collections       // List all collections in current DB
db.dropDatabase()        // Drop current database

💡 Pro Tip

The use command automatically creates a database if it doesn't exist. However, it won't appear in show dbs until you insert data into it.

4. Creating Collections & Inserting Data

Insert Products

use ecommerce

db.products.insertMany([
  {
    name: "Wireless Mouse",
    price: 799,
    category: "Electronics",
    stock: 120,
    ratings: 4.5,
    tags: ["computer", "accessory", "wireless"],
    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", quantity: 1, price: 799 }
    ],
    total: 3298,
    status: "Delivered",
    createdAt: new Date()
  }
])

Insert Contact Messages

db.contacts.insertMany([
  { 
    name: "Alice", 
    message: "Loved your website!", 
    phone: "9876543210",
    createdAt: new Date() 
  }
])

5. Reading Data (Find Queries)

Basic Find Operations

db.products.find()                    // Find all documents
db.products.find().pretty()           // Pretty print results

Filter by Field

db.products.find({ category: "Electronics" })

Comparison Operators

db.products.find({ price: { $gt: 1000 } })      // Greater than 1000
db.products.find({ price: { $gte: 1000, $lte: 50000 } }) // Between 1000 and 50000

Logical Operators

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

Projection (Select Specific Fields)

db.products.find({}, { name: 1, price: 1, _id: 0 })

Sorting and Limiting

db.products.find().sort({ price: -1 }).limit(2)  // Top 2 most expensive

6. Updating Documents

Update One Document

db.products.updateOne(
  { name: "Wireless Mouse" },
  { $set: { price: 899 } }
)

Update Many Documents

db.products.updateMany(
  { category: "Electronics" },
  { $inc: { stock: 10 } }  // Increment stock by 10
)

Add to Arrays with $push

db.products.updateOne(
  { name: "Wireless Mouse" },
  { $push: { tags: "new" } }
)

Common Update Operators

7. Deleting Documents

Delete One Document

db.contacts.deleteOne({ name: "Alice" })

Delete Many Documents

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

⚠️ Warning

Be careful with delete operations! They are permanent. Always test your query with find() before using deleteMany().

8. Indexing and Performance

Indexes improve the speed of read operations by allowing MongoDB to quickly locate data without scanning every document.

Create an Index

db.products.createIndex({ name: 1 })  // Ascending index on 'name' field

View All Indexes

db.products.getIndexes()

Explain Query Performance

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

Should You Always Create Indexes?

While indexes improve read performance, they can slow down write operations (inserts, updates, deletes) because the index must also be updated. Create indexes thoughtfully based on your query patterns!

9. Aggregation Framework

Aggregation pipelines analyze and transform data through stages. Each stage performs an operation, passing results to the next stage.

Basic Example - Total Revenue

db.orders.aggregate([
  { $group: { 
    _id: null, 
    totalRevenue: { $sum: "$total" } 
  }}
])

Group by Status

db.orders.aggregate([
  { $group: { 
    _id: "$status", 
    totalOrders: { $sum: 1 } 
  }}
])

Lookup (Join Collections)

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

10. Aggregation Pipeline Stages

Stage 1: $match - Filter Documents

db.sales.aggregate([
  { $match: { category: "Fruit" } }
])

Stage 2: $project - Select Fields

db.sales.aggregate([
  { $project: { _id: 0, item: 1, price: 1 } }
])

Stage 3: $group - Calculate Totals

db.sales.aggregate([
  {
    $group: {
      _id: "$category",
      totalSales: { $sum: { $multiply: ["$price", "$quantity"] } }
    }
  }
])

Stage 4: $sort - Sort Results

db.sales.aggregate([
  { $group: { _id: "$category", total: { $sum: 1 } }},
  { $sort: { total: -1 } }  // -1 for descending
])

Aggregation Stages Summary

Stage Description Example Use
$match Filter documents { category: "Fruit" }
$project Show/hide fields or create new ones item, price
$group Group data and calculate sums, averages Total sales per category
$sort Sort results Sort by total sales
$limit Limit number of results Top 3 items

💡 Did You Know?

MongoDB supports over 25 aggregation stages! The ones covered here are the most common and beginner-friendly core stages.

11. Useful Admin Commands

db.stats()                           // Show database statistics
db.serverStatus()                    // Server information
db.products.countDocuments()         // Count documents in collection
db.products.renameCollection("items") // Rename collection
db.products.drop()                   // Drop collection

Collection Management

12. MongoDB Atlas (Cloud)

MongoDB Atlas is the cloud-hosted version of MongoDB. It's fully managed, scalable, and offers a free tier!

Steps to Use Atlas

🛍️ Products

Store products information including name, price, stock, and ratings

📦 Orders

Store order details including customer info, items, and order status

💬 Contacts

Messages from the contact form with customer inquiries

Why MongoDB?

MongoDB provides flexibility with schema-less design, horizontal scalability, and powerful query capabilities. Perfect for modern applications requiring rapid development and evolution.