Skip to content

MongoDB - NoSQL Document Database

MongoDB stands as the world's most popular NoSQL document database, revolutionizing how developers think about data storage and retrieval. Created by 10gen (now MongoDB Inc.) in 2007, MongoDB stores data in flexible, JSON-like documents called BSON (Binary JSON), allowing for dynamic schemas and complex nested structures that traditional relational databases struggle to handle efficiently. This document-oriented approach makes MongoDB particularly well-suited for modern applications that deal with varied data types, rapid development cycles, and horizontal scaling requirements. MongoDB's ability to handle unstructured and semi-structured data, combined with its powerful query language and built-in replication and sharding capabilities, has made it the database of choice for countless web applications, mobile backends, IoT platforms, and big data analytics systems.

Installation and Setup

MongoDB Installation

bash
# Ubuntu/Debian installation
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org

# CentOS/RHEL/Fedora installation
sudo tee /etc/yum.repos.d/mongodb-org-7.0.repo <<EOF
[mongodb-org-7.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/7.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-7.0.asc
EOF
sudo dnf install -y mongodb-org

# macOS installation using Homebrew
brew tap mongodb/brew
brew install mongodb-community@7.0

# Windows installation
# Download from https://www.mongodb.com/try/download/community
# Or use Chocolatey: choco install mongodb

# Start MongoDB service
sudo systemctl start mongod
sudo systemctl enable mongod

# Verify installation
mongod --version
mongosh --version

# Connect to MongoDB
mongosh

# Connect to specific database
mongosh "mongodb://localhost:27017/myapp"

# Connect with authentication
mongosh "mongodb://username:password@localhost:27017/myapp"

# Connect to MongoDB Atlas (cloud)
mongosh "mongodb+srv://username:password@cluster.mongodb.net/myapp"

MongoDB Configuration

javascript
// mongod.conf configuration file
// Location: /etc/mongod.conf (Linux) or /usr/local/etc/mongod.conf (macOS)

// Basic configuration
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

net:
  port: 27017
  bindIp: 127.0.0.1

processManagement:
  fork: true
  pidFilePath: /var/run/mongodb/mongod.pid

security:
  authorization: enabled

// Replica set configuration
replication:
  replSetName: "rs0"

// Sharding configuration
sharding:
  clusterRole: shardsvr

// Performance tuning
storage:
  wiredTiger:
    engineConfig:
      cacheSizeGB: 2
    collectionConfig:
      blockCompressor: snappy
    indexConfig:
      prefixCompression: true

// Start MongoDB with configuration file
mongod --config /etc/mongod.conf

// Environment variables
export MONGO_INITDB_ROOT_USERNAME=admin
export MONGO_INITDB_ROOT_PASSWORD=password
export MONGO_INITDB_DATABASE=myapp

MongoDB Shell (mongosh) Basics

javascript
// Connect and basic commands
mongosh

// Show databases
show dbs

// Use/create database
use myapp

// Show collections
show collections

// Show current database
db

// Get database stats
db.stats()

// Get collection stats
db.users.stats()

// Help commands
help
db.help()
db.users.help()

// Exit shell
exit
quit()

// Execute JavaScript file
load("script.js")

// Pretty print results
db.users.find().pretty()

// Limit output
db.users.find().limit(5)

// Count documents
db.users.countDocuments()

// Get collection names
db.getCollectionNames()

// Drop database
db.dropDatabase()

// Drop collection
db.users.drop()

Data Types and Document Structure

BSON Data Types

javascript
// MongoDB BSON data types with examples

// String
{
  name: "John Doe",
  email: "john@example.com"
}

// Number (Integer, Double, Long, Decimal128)
{
  age: 30,                    // Integer
  price: 99.99,              // Double
  views: NumberLong(1000000), // Long
  balance: NumberDecimal("123.45") // Decimal128
}

// Boolean
{
  isActive: true,
  isVerified: false
}

// Date
{
  createdAt: new Date(),
  birthDate: ISODate("1990-01-15T00:00:00Z"),
  updatedAt: new Date("2024-01-15")
}

// ObjectId
{
  _id: ObjectId("507f1f77bcf86cd799439011"),
  userId: ObjectId("507f1f77bcf86cd799439012")
}

// Array
{
  tags: ["javascript", "mongodb", "database"],
  scores: [85, 92, 78, 96],
  friends: [
    ObjectId("507f1f77bcf86cd799439013"),
    ObjectId("507f1f77bcf86cd799439014")
  ]
}

// Embedded Document (Object)
{
  address: {
    street: "123 Main St",
    city: "New York",
    state: "NY",
    zipCode: "10001",
    coordinates: {
      lat: 40.7128,
      lng: -74.0060
    }
  }
}

// Null and Undefined
{
  middleName: null,
  nickname: undefined
}

// Binary Data
{
  profileImage: BinData(0, "base64encodeddata...")
}

// Regular Expression
{
  pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
}

// JavaScript Code
{
  validator: function(doc) { return doc.age >= 18; }
}

// MinKey and MaxKey (special comparison values)
{
  minValue: MinKey(),
  maxValue: MaxKey()
}

Document Structure Best Practices

javascript
// Well-structured user document
{
  _id: ObjectId("507f1f77bcf86cd799439011"),
  username: "johndoe",
  email: "john@example.com",
  profile: {
    firstName: "John",
    lastName: "Doe",
    avatar: "https://example.com/avatars/john.jpg",
    bio: "Software developer passionate about databases",
    socialLinks: {
      twitter: "@johndoe",
      linkedin: "linkedin.com/in/johndoe",
      github: "github.com/johndoe"
    }
  },
  preferences: {
    theme: "dark",
    language: "en",
    notifications: {
      email: true,
      push: false,
      sms: false
    }
  },
  metadata: {
    createdAt: ISODate("2024-01-15T10:30:00Z"),
    updatedAt: ISODate("2024-01-15T10:30:00Z"),
    lastLoginAt: ISODate("2024-01-15T10:30:00Z"),
    loginCount: 42,
    isActive: true,
    roles: ["user", "contributor"],
    tags: ["developer", "javascript", "mongodb"]
  }
}

// Blog post document with references and embedded data
{
  _id: ObjectId("507f1f77bcf86cd799439012"),
  title: "Getting Started with MongoDB",
  slug: "getting-started-with-mongodb",
  content: "MongoDB is a powerful NoSQL database...",
  excerpt: "Learn the basics of MongoDB document database",
  author: {
    _id: ObjectId("507f1f77bcf86cd799439011"),
    username: "johndoe",
    displayName: "John Doe"
  },
  categories: ["database", "tutorial", "mongodb"],
  tags: ["nosql", "javascript", "backend"],
  status: "published",
  publishedAt: ISODate("2024-01-15T12:00:00Z"),
  stats: {
    views: 1250,
    likes: 89,
    shares: 23,
    comments: 15
  },
  seo: {
    metaTitle: "Getting Started with MongoDB - Complete Guide",
    metaDescription: "Learn MongoDB basics with this comprehensive guide",
    keywords: ["mongodb", "nosql", "database", "tutorial"]
  },
  metadata: {
    createdAt: ISODate("2024-01-15T10:00:00Z"),
    updatedAt: ISODate("2024-01-15T11:45:00Z"),
    version: 2
  }
}

// E-commerce order document
{
  _id: ObjectId("507f1f77bcf86cd799439013"),
  orderNumber: "ORD-2024-001234",
  customer: {
    _id: ObjectId("507f1f77bcf86cd799439011"),
    email: "john@example.com",
    name: "John Doe"
  },
  items: [
    {
      productId: ObjectId("507f1f77bcf86cd799439014"),
      name: "MongoDB T-Shirt",
      sku: "MONGO-TSHIRT-L",
      quantity: 2,
      price: 25.99,
      total: 51.98
    },
    {
      productId: ObjectId("507f1f77bcf86cd799439015"),
      name: "Database Handbook",
      sku: "DB-HANDBOOK-2024",
      quantity: 1,
      price: 39.99,
      total: 39.99
    }
  ],
  shipping: {
    address: {
      street: "123 Main St",
      city: "New York",
      state: "NY",
      zipCode: "10001",
      country: "USA"
    },
    method: "standard",
    cost: 9.99,
    estimatedDelivery: ISODate("2024-01-20T00:00:00Z")
  },
  payment: {
    method: "credit_card",
    status: "completed",
    transactionId: "txn_1234567890",
    amount: 101.96
  },
  totals: {
    subtotal: 91.97,
    shipping: 9.99,
    tax: 0.00,
    total: 101.96
  },
  status: "processing",
  timeline: [
    {
      status: "placed",
      timestamp: ISODate("2024-01-15T14:30:00Z")
    },
    {
      status: "paid",
      timestamp: ISODate("2024-01-15T14:31:00Z")
    },
    {
      status: "processing",
      timestamp: ISODate("2024-01-15T15:00:00Z")
    }
  ],
  createdAt: ISODate("2024-01-15T14:30:00Z"),
  updatedAt: ISODate("2024-01-15T15:00:00Z")
}

CRUD Operations

Create Operations (Insert)

javascript
// Insert single document
db.users.insertOne({
  username: "johndoe",
  email: "john@example.com",
  age: 30,
  createdAt: new Date()
})

// Insert multiple documents
db.users.insertMany([
  {
    username: "janedoe",
    email: "jane@example.com",
    age: 28,
    createdAt: new Date()
  },
  {
    username: "bobsmith",
    email: "bob@example.com",
    age: 35,
    createdAt: new Date()
  },
  {
    username: "alicejohnson",
    email: "alice@example.com",
    age: 32,
    createdAt: new Date()
  }
])

// Insert with custom _id
db.users.insertOne({
  _id: "custom-user-id",
  username: "customuser",
  email: "custom@example.com",
  age: 25
})

// Insert with error handling
try {
  const result = db.users.insertOne({
    username: "newuser",
    email: "new@example.com",
    age: 27
  })
  print("Inserted document with _id: " + result.insertedId)
} catch (error) {
  print("Error inserting document: " + error)
}

// Bulk insert with ordered/unordered operations
db.users.bulkWrite([
  {
    insertOne: {
      document: {
        username: "user1",
        email: "user1@example.com",
        age: 25
      }
    }
  },
  {
    insertOne: {
      document: {
        username: "user2",
        email: "user2@example.com",
        age: 30
      }
    }
  }
], { ordered: false })

// Insert with write concern
db.users.insertOne(
  {
    username: "importantuser",
    email: "important@example.com",
    age: 40
  },
  {
    writeConcern: {
      w: "majority",
      j: true,
      wtimeout: 5000
    }
  }
)

Read Operations (Find)

javascript
// Find all documents
db.users.find()

// Find with pretty formatting
db.users.find().pretty()

// Find one document
db.users.findOne()

// Find by exact match
db.users.find({ username: "johndoe" })

// Find by multiple criteria
db.users.find({
  age: 30,
  isActive: true
})

// Find with comparison operators
db.users.find({ age: { $gt: 25 } })          // Greater than
db.users.find({ age: { $gte: 25 } })         // Greater than or equal
db.users.find({ age: { $lt: 35 } })          // Less than
db.users.find({ age: { $lte: 35 } })         // Less than or equal
db.users.find({ age: { $ne: 30 } })          // Not equal
db.users.find({ age: { $in: [25, 30, 35] } }) // In array
db.users.find({ age: { $nin: [25, 30] } })   // Not in array

// Find with logical operators
db.users.find({
  $and: [
    { age: { $gte: 25 } },
    { age: { $lte: 35 } }
  ]
})

db.users.find({
  $or: [
    { username: "johndoe" },
    { email: "john@example.com" }
  ]
})

db.users.find({
  $nor: [
    { age: { $lt: 18 } },
    { isActive: false }
  ]
})

db.users.find({
  age: { $not: { $lt: 18 } }
})

// Find with element operators
db.users.find({ tags: { $exists: true } })   // Field exists
db.users.find({ tags: { $type: "array" } })  // Field type
db.users.find({ tags: { $size: 3 } })        // Array size

// Find with array operators
db.users.find({ tags: "javascript" })        // Array contains value
db.users.find({ tags: { $all: ["javascript", "mongodb"] } }) // Array contains all values
db.users.find({ "scores.0": { $gt: 80 } })   // Array element by index

// Find with regex
db.users.find({ username: /^john/ })          // Starts with "john"
db.users.find({ email: /@example\.com$/ })   // Ends with "@example.com"
db.users.find({ username: { $regex: "doe", $options: "i" } }) // Case insensitive

// Find with projection (select specific fields)
db.users.find({}, { username: 1, email: 1 })           // Include only username and email
db.users.find({}, { password: 0, secretKey: 0 })       // Exclude password and secretKey
db.users.find({}, { "profile.firstName": 1, age: 1 })  // Include nested fields

// Find with sorting
db.users.find().sort({ age: 1 })              // Ascending
db.users.find().sort({ age: -1 })             // Descending
db.users.find().sort({ age: -1, username: 1 }) // Multiple fields

// Find with limit and skip (pagination)
db.users.find().limit(10)                     // First 10 documents
db.users.find().skip(20).limit(10)            // Skip 20, take 10 (page 3)

// Find with cursor methods chaining
db.users.find({ age: { $gte: 25 } })
  .sort({ createdAt: -1 })
  .limit(5)
  .skip(0)

// Find distinct values
db.users.distinct("age")
db.users.distinct("tags")
db.users.distinct("profile.city")

// Count documents
db.users.countDocuments()
db.users.countDocuments({ age: { $gte: 25 } })
db.users.estimatedDocumentCount()  // Faster but less accurate

// Find with explain (query performance)
db.users.find({ username: "johndoe" }).explain("executionStats")

Update Operations

javascript
// Update single document
db.users.updateOne(
  { username: "johndoe" },
  { $set: { age: 31, updatedAt: new Date() } }
)

// Update multiple documents
db.users.updateMany(
  { age: { $lt: 18 } },
  { $set: { isMinor: true } }
)

// Replace entire document
db.users.replaceOne(
  { username: "johndoe" },
  {
    username: "johndoe",
    email: "john.doe@example.com",
    age: 31,
    profile: {
      firstName: "John",
      lastName: "Doe"
    },
    updatedAt: new Date()
  }
)

// Update operators
// $set - Set field value
db.users.updateOne(
  { username: "johndoe" },
  { $set: { "profile.bio": "Updated bio", lastLogin: new Date() } }
)

// $unset - Remove field
db.users.updateOne(
  { username: "johndoe" },
  { $unset: { temporaryField: "" } }
)

// $inc - Increment numeric value
db.users.updateOne(
  { username: "johndoe" },
  { $inc: { loginCount: 1, "stats.views": 10 } }
)

// $mul - Multiply numeric value
db.users.updateOne(
  { username: "johndoe" },
  { $mul: { score: 1.1 } }
)

// $min/$max - Update if new value is smaller/larger
db.users.updateOne(
  { username: "johndoe" },
  { 
    $min: { lowestScore: 85 },
    $max: { highestScore: 95 }
  }
)

// $currentDate - Set to current date
db.users.updateOne(
  { username: "johndoe" },
  { $currentDate: { lastModified: true, "audit.updatedAt": { $type: "date" } } }
)

// Array update operators
// $push - Add element to array
db.users.updateOne(
  { username: "johndoe" },
  { $push: { tags: "newbie" } }
)

// $push with $each (add multiple elements)
db.users.updateOne(
  { username: "johndoe" },
  { $push: { tags: { $each: ["expert", "mentor"] } } }
)

// $push with $sort and $slice (maintain sorted array with size limit)
db.users.updateOne(
  { username: "johndoe" },
  { 
    $push: { 
      scores: { 
        $each: [95, 87], 
        $sort: -1, 
        $slice: 5 
      } 
    } 
  }
)

// $addToSet - Add element to array if not exists
db.users.updateOne(
  { username: "johndoe" },
  { $addToSet: { tags: "javascript" } }
)

// $pull - Remove elements from array
db.users.updateOne(
  { username: "johndoe" },
  { $pull: { tags: "beginner" } }
)

// $pullAll - Remove multiple elements from array
db.users.updateOne(
  { username: "johndoe" },
  { $pullAll: { tags: ["beginner", "newbie"] } }
)

// $pop - Remove first (-1) or last (1) element
db.users.updateOne(
  { username: "johndoe" },
  { $pop: { scores: 1 } }
)

// Positional operators
// $ - Update first matching array element
db.users.updateOne(
  { "scores": { $gte: 90 } },
  { $set: { "scores.$": 100 } }
)

// $[] - Update all array elements
db.users.updateOne(
  { username: "johndoe" },
  { $inc: { "scores.$[]": 5 } }
)

// $[identifier] - Update array elements matching condition
db.users.updateOne(
  { username: "johndoe" },
  { $set: { "scores.$[element]": 100 } },
  { arrayFilters: [{ "element": { $gte: 90 } }] }
)

// Upsert (update or insert)
db.users.updateOne(
  { username: "newuser" },
  { 
    $set: { 
      email: "newuser@example.com",
      age: 25,
      createdAt: new Date()
    }
  },
  { upsert: true }
)

// Update with write concern
db.users.updateOne(
  { username: "johndoe" },
  { $set: { importantField: "value" } },
  { 
    writeConcern: { 
      w: "majority", 
      j: true, 
      wtimeout: 5000 
    } 
  }
)

// Bulk update operations
db.users.bulkWrite([
  {
    updateOne: {
      filter: { username: "johndoe" },
      update: { $set: { status: "active" } }
    }
  },
  {
    updateMany: {
      filter: { age: { $lt: 18 } },
      update: { $set: { category: "minor" } }
    }
  }
])

Delete Operations

javascript
// Delete single document
db.users.deleteOne({ username: "johndoe" })

// Delete multiple documents
db.users.deleteMany({ age: { $lt: 18 } })

// Delete all documents in collection
db.users.deleteMany({})

// Delete with complex criteria
db.users.deleteMany({
  $and: [
    { createdAt: { $lt: new Date("2023-01-01") } },
    { isActive: false }
  ]
})

// Delete with write concern
db.users.deleteOne(
  { username: "johndoe" },
  { 
    writeConcern: { 
      w: "majority", 
      j: true, 
      wtimeout: 5000 
    } 
  }
)

// Find and delete (returns deleted document)
db.users.findOneAndDelete(
  { username: "johndoe" },
  { 
    sort: { createdAt: -1 },
    projection: { password: 0 }
  }
)

// Bulk delete operations
db.users.bulkWrite([
  {
    deleteOne: {
      filter: { username: "user1" }
    }
  },
  {
    deleteMany: {
      filter: { status: "inactive" }
    }
  }
])

// Soft delete (mark as deleted instead of removing)
db.users.updateMany(
  { status: "inactive" },
  { 
    $set: { 
      isDeleted: true, 
      deletedAt: new Date() 
    } 
  }
)

// Remove field from all documents
db.users.updateMany(
  {},
  { $unset: { temporaryField: "" } }
)

Indexing and Performance

Creating and Managing Indexes

javascript
// Create single field index
db.users.createIndex({ username: 1 })        // Ascending
db.users.createIndex({ age: -1 })             // Descending

// Create compound index
db.users.createIndex({ age: 1, username: 1 })

// Create unique index
db.users.createIndex({ email: 1 }, { unique: true })

// Create partial index (with condition)
db.users.createIndex(
  { email: 1 },
  { 
    partialFilterExpression: { 
      email: { $exists: true, $ne: null } 
    } 
  }
)

// Create sparse index (skip null values)
db.users.createIndex({ phone: 1 }, { sparse: true })

// Create TTL index (automatic expiration)
db.sessions.createIndex(
  { createdAt: 1 },
  { expireAfterSeconds: 3600 }  // Expire after 1 hour
)

// Create text index for full-text search
db.posts.createIndex({ 
  title: "text", 
  content: "text" 
})

// Create text index with weights
db.posts.createIndex(
  { 
    title: "text", 
    content: "text",
    tags: "text"
  },
  { 
    weights: { 
      title: 10, 
      content: 5, 
      tags: 1 
    } 
  }
)

// Create 2dsphere index for geospatial queries
db.locations.createIndex({ coordinates: "2dsphere" })

// Create hashed index for sharding
db.users.createIndex({ _id: "hashed" })

// Create index with options
db.users.createIndex(
  { username: 1 },
  {
    name: "username_unique_idx",
    unique: true,
    background: true,
    sparse: true
  }
)

// List indexes
db.users.getIndexes()

// Get index stats
db.users.aggregate([{ $indexStats: {} }])

// Drop index
db.users.dropIndex({ username: 1 })
db.users.dropIndex("username_unique_idx")

// Drop all indexes (except _id)
db.users.dropIndexes()

// Rebuild indexes
db.users.reIndex()

// Hide/unhide index (MongoDB 4.4+)
db.users.hideIndex("username_1")
db.users.unhideIndex("username_1")

Query Optimization

javascript
// Explain query execution
db.users.find({ username: "johndoe" }).explain()
db.users.find({ username: "johndoe" }).explain("executionStats")
db.users.find({ username: "johndoe" }).explain("allPlansExecution")

// Analyze query performance
const explainResult = db.users.find({ 
  age: { $gte: 25, $lte: 35 } 
}).explain("executionStats")

print("Execution time: " + explainResult.executionStats.executionTimeMillis + "ms")
print("Documents examined: " + explainResult.executionStats.totalDocsExamined)
print("Documents returned: " + explainResult.executionStats.totalDocsReturned)

// Hint to use specific index
db.users.find({ age: 30, username: "johndoe" }).hint({ age: 1 })

// Use projection to reduce data transfer
db.users.find(
  { age: { $gte: 25 } },
  { username: 1, email: 1, _id: 0 }
)

// Optimize sorting with indexes
db.users.find({ age: { $gte: 25 } }).sort({ age: 1, username: 1 })

// Use covered queries (all fields in index)
db.users.createIndex({ age: 1, username: 1, email: 1 })
db.users.find(
  { age: 30 },
  { username: 1, email: 1, _id: 0 }
)

// Optimize regex queries
db.users.find({ username: /^john/ })  // Good: anchored at beginning
db.users.find({ username: /john/ })   // Bad: not anchored

// Use $elemMatch for array queries
db.users.find({
  scores: {
    $elemMatch: {
      $gte: 80,
      $lte: 90
    }
  }
})

// Batch size optimization
db.users.find().batchSize(100)

// Read preference for replica sets
db.users.find().readPref("secondary")

Performance Monitoring

javascript
// Database profiler
db.setProfilingLevel(2)  // Profile all operations
db.setProfilingLevel(1, { slowms: 100 })  // Profile slow operations (>100ms)
db.setProfilingLevel(0)  // Disable profiling

// View profiler data
db.system.profile.find().limit(5).sort({ ts: -1 }).pretty()

// Current operations
db.currentOp()

// Kill operation
db.killOp(operationId)

// Database statistics
db.stats()
db.serverStatus()

// Collection statistics
db.users.stats()

// Index usage statistics
db.users.aggregate([{ $indexStats: {} }])

// Connection statistics
db.serverStatus().connections

// Memory usage
db.serverStatus().mem

// Lock statistics
db.serverStatus().locks

// Replication lag (for replica sets)
rs.printSlaveReplicationInfo()

// Sharding statistics (for sharded clusters)
sh.status()

Aggregation Framework

Basic Aggregation Pipeline

javascript
// Simple aggregation pipeline
db.users.aggregate([
  { $match: { age: { $gte: 25 } } },
  { $group: { _id: "$department", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

// $match stage (filtering)
db.users.aggregate([
  { 
    $match: { 
      age: { $gte: 18, $lte: 65 },
      isActive: true 
    } 
  }
])

// $project stage (field selection and transformation)
db.users.aggregate([
  {
    $project: {
      username: 1,
      email: 1,
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      ageGroup: {
        $switch: {
          branches: [
            { case: { $lt: ["$age", 18] }, then: "minor" },
            { case: { $lt: ["$age", 65] }, then: "adult" },
            { case: { $gte: ["$age", 65] }, then: "senior" }
          ],
          default: "unknown"
        }
      }
    }
  }
])

// $group stage (aggregation)
db.orders.aggregate([
  {
    $group: {
      _id: "$customerId",
      totalOrders: { $sum: 1 },
      totalAmount: { $sum: "$amount" },
      avgAmount: { $avg: "$amount" },
      maxAmount: { $max: "$amount" },
      minAmount: { $min: "$amount" },
      firstOrder: { $min: "$createdAt" },
      lastOrder: { $max: "$createdAt" }
    }
  }
])

// $sort stage
db.users.aggregate([
  { $sort: { age: -1, username: 1 } }
])

// $limit and $skip stages
db.users.aggregate([
  { $sort: { createdAt: -1 } },
  { $skip: 20 },
  { $limit: 10 }
])

// $unwind stage (array deconstruction)
db.posts.aggregate([
  { $unwind: "$tags" },
  { $group: { _id: "$tags", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])

// $lookup stage (joins)
db.orders.aggregate([
  {
    $lookup: {
      from: "users",
      localField: "customerId",
      foreignField: "_id",
      as: "customer"
    }
  },
  {
    $unwind: "$customer"
  },
  {
    $project: {
      orderNumber: 1,
      amount: 1,
      "customer.username": 1,
      "customer.email": 1
    }
  }
])

// $addFields stage (add computed fields)
db.users.aggregate([
  {
    $addFields: {
      fullName: { $concat: ["$firstName", " ", "$lastName"] },
      isAdult: { $gte: ["$age", 18] }
    }
  }
])

// $replaceRoot stage (promote embedded document)
db.users.aggregate([
  {
    $replaceRoot: {
      newRoot: {
        $mergeObjects: [
          { _id: "$_id", username: "$username" },
          "$profile"
        ]
      }
    }
  }
])

Advanced Aggregation Operations

javascript
// Complex aggregation with multiple stages
db.orders.aggregate([
  // Match orders from last 30 days
  {
    $match: {
      createdAt: { $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) }
    }
  },
  
  // Lookup customer information
  {
    $lookup: {
      from: "users",
      localField: "customerId",
      foreignField: "_id",
      as: "customer"
    }
  },
  
  // Unwind customer array
  { $unwind: "$customer" },
  
  // Unwind order items
  { $unwind: "$items" },
  
  // Group by product and calculate metrics
  {
    $group: {
      _id: "$items.productId",
      productName: { $first: "$items.name" },
      totalQuantity: { $sum: "$items.quantity" },
      totalRevenue: { $sum: "$items.total" },
      uniqueCustomers: { $addToSet: "$customerId" },
      avgOrderValue: { $avg: "$items.total" }
    }
  },
  
  // Add computed fields
  {
    $addFields: {
      customerCount: { $size: "$uniqueCustomers" }
    }
  },
  
  // Sort by revenue
  { $sort: { totalRevenue: -1 } },
  
  // Limit to top 10
  { $limit: 10 },
  
  // Final projection
  {
    $project: {
      productName: 1,
      totalQuantity: 1,
      totalRevenue: { $round: ["$totalRevenue", 2] },
      customerCount: 1,
      avgOrderValue: { $round: ["$avgOrderValue", 2] }
    }
  }
])

// Faceted search (multiple aggregations)
db.products.aggregate([
  {
    $facet: {
      "categoryCounts": [
        { $group: { _id: "$category", count: { $sum: 1 } } },
        { $sort: { count: -1 } }
      ],
      "priceRanges": [
        {
          $bucket: {
            groupBy: "$price",
            boundaries: [0, 25, 50, 100, 200, 500],
            default: "500+",
            output: { count: { $sum: 1 } }
          }
        }
      ],
      "topRated": [
        { $match: { rating: { $gte: 4.5 } } },
        { $sort: { rating: -1, reviewCount: -1 } },
        { $limit: 5 }
      ]
    }
  }
])

// Time series aggregation
db.sales.aggregate([
  {
    $match: {
      date: {
        $gte: ISODate("2024-01-01"),
        $lt: ISODate("2024-02-01")
      }
    }
  },
  {
    $group: {
      _id: {
        year: { $year: "$date" },
        month: { $month: "$date" },
        day: { $dayOfMonth: "$date" }
      },
      dailySales: { $sum: "$amount" },
      orderCount: { $sum: 1 }
    }
  },
  {
    $sort: { "_id.year": 1, "_id.month": 1, "_id.day": 1 }
  }
])

// Text search aggregation
db.posts.aggregate([
  { $match: { $text: { $search: "mongodb database" } } },
  { $addFields: { score: { $meta: "textScore" } } },
  { $sort: { score: { $meta: "textScore" } } }
])

// Geospatial aggregation
db.locations.aggregate([
  {
    $geoNear: {
      near: { type: "Point", coordinates: [-74.0059, 40.7128] },
      distanceField: "distance",
      maxDistance: 1000,
      spherical: true
    }
  },
  {
    $group: {
      _id: "$category",
      count: { $sum: 1 },
      avgDistance: { $avg: "$distance" }
    }
  }
])

// Window functions (MongoDB 5.0+)
db.sales.aggregate([
  {
    $setWindowFields: {
      partitionBy: "$department",
      sortBy: { date: 1 },
      output: {
        runningTotal: {
          $sum: "$amount",
          window: { documents: ["unbounded", "current"] }
        },
        movingAvg: {
          $avg: "$amount",
          window: { documents: [-2, 0] }
        }
      }
    }
  }
])

Aggregation Operators and Expressions

javascript
// Arithmetic operators
db.orders.aggregate([
  {
    $project: {
      total: { $add: ["$subtotal", "$tax", "$shipping"] },
      discount: { $multiply: ["$subtotal", 0.1] },
      finalAmount: {
        $subtract: [
          { $add: ["$subtotal", "$tax", "$shipping"] },
          { $multiply: ["$subtotal", 0.1] }
        ]
      }
    }
  }
])

// String operators
db.users.aggregate([
  {
    $project: {
      username: { $toLower: "$username" },
      initials: {
        $concat: [
          { $substr: ["$firstName", 0, 1] },
          { $substr: ["$lastName", 0, 1] }
        ]
      },
      emailDomain: {
        $arrayElemAt: [
          { $split: ["$email", "@"] },
          1
        ]
      }
    }
  }
])

// Date operators
db.events.aggregate([
  {
    $project: {
      year: { $year: "$date" },
      month: { $month: "$date" },
      dayOfWeek: { $dayOfWeek: "$date" },
      quarter: {
        $ceil: { $divide: [{ $month: "$date" }, 3] }
      },
      ageInDays: {
        $divide: [
          { $subtract: [new Date(), "$date"] },
          1000 * 60 * 60 * 24
        ]
      }
    }
  }
])

// Array operators
db.posts.aggregate([
  {
    $project: {
      title: 1,
      tagCount: { $size: "$tags" },
      firstTag: { $arrayElemAt: ["$tags", 0] },
      hasJavaScriptTag: { $in: ["javascript", "$tags"] },
      topTags: { $slice: ["$tags", 3] }
    }
  }
])

// Conditional operators
db.users.aggregate([
  {
    $project: {
      username: 1,
      status: {
        $cond: {
          if: { $gte: ["$lastLogin", new Date(Date.now() - 7 * 24 * 60 * 60 * 1000)] },
          then: "active",
          else: "inactive"
        }
      },
      category: {
        $switch: {
          branches: [
            { case: { $lt: ["$age", 18] }, then: "minor" },
            { case: { $lt: ["$age", 65] }, then: "adult" }
          ],
          default: "senior"
        }
      }
    }
  }
])

// Type conversion operators
db.products.aggregate([
  {
    $project: {
      name: 1,
      price: { $toDouble: "$priceString" },
      createdYear: { $toInt: { $year: "$createdAt" } },
      isExpensive: { $toBool: { $gte: ["$price", 100] } }
    }
  }
])

MongoDB's flexible document model, powerful query capabilities, and horizontal scaling features make it an excellent choice for modern applications that require rapid development, complex data relationships, and the ability to handle large volumes of diverse data. Its rich ecosystem of tools, drivers, and cloud services, combined with strong community support, ensures that MongoDB remains a leading database solution for organizations of all sizes.