# MongoDB

> 🚀 **Quick Start**: Document-oriented NoSQL database dengan flexible schema, powerful querying, dan horizontal scalability

## 📋 Table of Contents

* [Overview](#overview)
* [Why Choose MongoDB](#why-choose-mongodb)
* [Getting Started](#getting-started)
* [Core Concepts](#core-concepts)
* [Data Modeling](#data-modeling)
* [Advanced Topics](#advanced-topics)
* [Best Practices](#best-practices)
* [Ecosystem](#ecosystem)
* [Community](#community)
* [References](#references)

## 🎯 Overview

**MongoDB** adalah document-oriented NoSQL database yang dirancang untuk modern applications. MongoDB menyimpan data dalam flexible, JSON-like documents yang memungkinkan hierarchical data structures dengan optional schema. Database ini menawarkan powerful querying capabilities, indexing, dan horizontal scaling yang membuatnya ideal untuk big data applications, content management, dan real-time analytics.

### Key Features

* ⚡ **Document-Oriented**: Data stored dalam BSON documents (Binary JSON)
* 🔒 **Flexible Schema**: Dynamic schema untuk rapid development
* 📱 **Horizontal Scaling**: Sharding untuk massive data distribution
* 🚀 **Rich Querying**: Powerful query language dengan aggregation framework
* 🛠️ **Indexing**: Multiple index types untuk optimal performance

### Common Use Cases

* **Content Management**: CMS, blogs, media platforms
* **E-commerce**: Product catalogs, inventory management
* **IoT Applications**: Real-time data collection dan analytics
* **Mobile Applications**: User profiles, session data
* **Analytics Platforms**: Big data processing dan reporting

## 🏆 Why Choose MongoDB

### Advantages

✅ **Flexibility**: Dynamic schema memungkinkan rapid development ✅ **Scalability**: Horizontal scaling dengan sharding ✅ **Performance**: In-memory computing dan optimization ✅ **Rich Features**: Aggregation framework, full-text search ✅ **Developer Friendly**: Document model yang intuitive

### Comparison with SQL Databases

| Feature            | MongoDB | PostgreSQL | MySQL | Redis |
| ------------------ | ------- | ---------- | ----- | ----- |
| Schema Flexibility | ⭐⭐⭐⭐⭐   | ⭐⭐         | ⭐⭐    | ⭐⭐⭐   |
| Horizontal Scaling | ⭐⭐⭐⭐⭐   | ⭐⭐         | ⭐⭐    | ⭐⭐⭐   |
| Query Complexity   | ⭐⭐⭐⭐    | ⭐⭐⭐⭐⭐      | ⭐⭐⭐⭐  | ⭐⭐    |
| Performance        | ⭐⭐⭐⭐    | ⭐⭐⭐⭐       | ⭐⭐⭐⭐  | ⭐⭐⭐⭐⭐ |
| Consistency        | ⭐⭐⭐⭐    | ⭐⭐⭐⭐⭐      | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐  |
| Ecosystem          | ⭐⭐⭐⭐⭐   | ⭐⭐⭐⭐       | ⭐⭐⭐⭐  | ⭐⭐⭐⭐  |

## 🚀 Getting Started

### Installation Options

#### Option 1: MongoDB Atlas (Cloud)

```bash
# Sign up untuk MongoDB Atlas
# 1. Visit https://www.mongodb.com/atlas
# 2. Create free cluster
# 3. Get connection string
# 4. Connect dengan MongoDB Compass atau driver

# Connection string example:
# mongodb+srv://username:password@cluster.mongodb.net/myFirstDatabase
```

#### Option 2: Local Installation

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

# macOS (Homebrew)
brew tap mongodb/brew
brew install mongodb-community@6.0
brew services start mongodb/brew/mongodb-community

# Windows
# Download MongoDB installer dari https://www.mongodb.com/try/download/community
```

#### Option 3: Docker

```bash
# Pull MongoDB image
docker pull mongo:6.0

# Run MongoDB container
docker run --name mongodb -p 27017:27017 -d mongo:6.0

# Run with authentication
docker run --name mongodb -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  -d mongo:6.0
```

### Basic Operations

```javascript
// Connect ke MongoDB
// MongoDB Shell
mongosh "mongodb://localhost:27017"

// Switch ke database
use myapp

// Insert document
db.users.insertOne({
  name: "John Doe",
  email: "john@example.com",
  age: 30,
  createdAt: new Date(),
  roles: ["user"]
});

// Insert multiple documents
db.users.insertMany([
  {
    name: "Jane Smith",
    email: "jane@example.com",
    age: 25,
    createdAt: new Date(),
    roles: ["user", "editor"]
  },
  {
    name: "Bob Johnson",
    email: "bob@example.com",
    age: 35,
    createdAt: new Date(),
    roles: ["admin"]
  }
]);

// Query documents
db.users.find();

// Query dengan filter
db.users.find({ age: { $gt: 25 } });

// Query dengan projection
db.users.find({ roles: "admin" }, { name: 1, email: 1 });

// Update document
db.users.updateOne(
  { name: "John Doe" },
  { $set: { age: 31, updatedAt: new Date() } }
);

// Delete document
db.users.deleteOne({ name: "Bob Johnson" });
```

## 🧠 Core Concepts

### Concept 1: Documents & Collections

**Documents** adalah basic unit data dalam MongoDB, similar JSON objects. **Collections** adalah groups dari documents.

```javascript
// Document example (BSON)
{
  "_id": ObjectId("60f1b2e3c4d5e6f7g8h9i0j1"),
  "name": "Product A",
  "price": 299.99,
  "description": "High-quality product",
  "tags": ["electronics", "premium"],
  "inventory": {
    "available": 150,
    "reserved": 25
  },
  "reviews": [
    {
      "userId": ObjectId("60f1b2e3c4d5e6f7g8h9i0j2"),
      "rating": 5,
      "comment": "Excellent product!",
      "createdAt": ISODate("2023-07-15T10:30:00Z")
    }
  ],
  "createdAt": ISODate("2023-07-01T09:00:00Z"),
  "updatedAt": ISODate("2023-07-15T14:20:00Z")
}

// Collection operations
// Create collection dengan validation rules
db.createCollection("products", {
  validator: {
    $jsonSchema: {
      bsonType: "object",
      required: ["name", "price"],
      properties: {
        name: {
          bsonType: "string",
          description: "Product name (required)"
        },
        price: {
          bsonType: "number",
          minimum: 0,
          description: "Product price (required, non-negative)"
        },
        tags: {
          bsonType: "array",
          items: {
            bsonType: "string"
          }
        }
      }
    }
  }
});

// Insert document dengan validation
db.products.insertOne({
  name: "Smartphone XYZ",
  price: 699.99,
  tags: ["electronics", "mobile"]
});

// Query documents
db.products.find({
  price: { $lt: 1000 },
  tags: "electronics"
});

// Update embedded document
db.products.updateOne(
  { name: "Smartphone XYZ" },
  {
    $push: {
      reviews: {
        userId: ObjectId("60f1b2e3c4d5e6f7g8h9i0j3"),
        rating: 4,
        comment: "Good value for money",
        createdAt: new Date()
      }
    },
    $inc: { "inventory.available": -1 }
  }
);
```

### Concept 2: Indexing

**Indexing** meningkatkan query performance dengan creating efficient data structures.

```javascript
// Create single field index
db.users.createIndex({ email: 1 }, { unique: true });

// Create compound index
db.products.createIndex({ category: 1, price: -1 });

// Create text index untuk full-text search
db.products.createIndex({
  name: "text",
  description: "text"
});

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

// Create TTL (Time-To-Live) index
db.sessions.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });

// Query dengan text search
db.products.find({
  $text: { $search: "premium electronics" }
});

// Geospatial query
db.locations.find({
  coordinates: {
    $near: {
      $geometry: { type: "Point", coordinates: [-73.9667, 40.78] },
      $maxDistance: 1000
    }
  }
});

// Explain query execution
db.users.find({ age: { $gt: 25 } }).explain("executionStats");
```

### Concept 3: Aggregation Framework

**Aggregation Framework** memungkinkan data processing dan analysis dengan multi-stage pipelines.

```javascript
// Basic aggregation pipeline
db.orders.aggregate([
  // Stage 1: Filter orders
  {
    $match: {
      status: "completed",
      orderDate: {
        $gte: ISODate("2023-01-01"),
        $lt: ISODate("2023-12-31")
      }
    }
  },

  // Stage 2: Group dan calculate totals
  {
    $group: {
      _id: "$customerId",
      totalOrders: { $sum: 1 },
      totalAmount: { $sum: "$amount" },
      avgOrderValue: { $avg: "$amount" }
    }
  },

  // Stage 3: Sort by total amount
  {
    $sort: { totalAmount: -1 }
  },

  // Stage 4: Limit top 10 customers
  {
    $limit: 10
  },

  // Stage 5: Lookup customer details
  {
    $lookup: {
      from: "customers",
      localField: "_id",
      foreignField: "_id",
      as: "customer"
    }
  },

  // Stage 6: Reshape output
  {
    $project: {
      customerName: { $arrayElemAt: ["$customer.name", 0] },
      customerEmail: { $arrayElemAt: ["$customer.email", 0] },
      totalOrders: 1,
      totalAmount: 1,
      avgOrderValue: 1
    }
  }
]);

// Complex aggregation untuk analytics
db.sales.aggregate([
  // Monthly sales by category
  {
    $group: {
      _id: {
        year: { $year: "$saleDate" },
        month: { $month: "$saleDate" },
        category: "$product.category"
      },
      totalSales: { $sum: "$amount" },
      totalQuantity: { $sum: "$quantity" },
      avgPrice: { $avg: "$price" }
    }
  },

  // Calculate month-over-month growth
  {
    $group: {
      _id: "$_id.category",
      monthlyData: {
        $push: {
          year: "$_id.year",
          month: "$_id.month",
          totalSales: "$totalSales"
        }
      }
    }
  },

  // Add growth calculation
  {
    $project: {
      category: "$_id",
      monthlyData: {
        $map: {
          input: "$monthlyData",
          as: "month",
          in: {
            $mergeObjects: [
              "$$this",
              {
                previousMonthSales: {
                  $let: {
                    vars: {
                      currentIndex: { $indexOfArray: ["$$monthlyData", "$$this"] }
                    },
                    in: {
                      $cond: {
                        if: { $eq: ["$$currentIndex", 0] },
                        then: null,
                        else: { $arrayElemAt: ["$$monthlyData", { $subtract: ["$$currentIndex", 1] }, "totalSales"] }
                      }
                    }
                  }
                },
                growthPercentage: {
                  $cond: {
                    if: { $eq: ["$$this.previousMonthSales", null] },
                    then: null,
                    else: {
                      $multiply: [
                        {
                          $divide: [
                            { $subtract: ["$$this.totalSales", "$$this.previousMonthSales"] },
                            "$$this.previousMonthSales"
                          ]
                        },
                        100
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      }
    }
  }
]);
```

## ⚡ Advanced Topics

### Advanced Topic 1: Replication & High Availability

**Replication** provides data redundancy dan high availability dengan multiple copies of data.

```javascript
// Replica Set Configuration
// mongod.conf file untuk secondary nodes
net:
  port: 27017
  bindIp: 0.0.0.0

replication:
  replSetName: "myReplicaSet"

security:
  keyFile: /etc/mongodb-keyfile
  authorization: enabled

# Initialize replica set
// Connect ke primary node
rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "mongodb1.example.com:27017", priority: 2 },
    { _id: 1, host: "mongodb2.example.com:27017", priority: 1 },
    { _id: 2, host: "mongodb3.example.com:27017", priority: 1 }
  ]
});

// Add secondary to replica set
rs.add("mongodb2.example.com:27017");
rs.add("mongodb3.example.com:27017");

// Check replica set status
rs.status();

// Configure read preferences
// Primary read preference (default)
db.collection.find().readPref("primary");

// Secondary read preference
db.collection.find().readPref("secondary");

// Nearest read preference
db.collection.find().readPref("nearest");

// Write concern levels
// Unacknowledged (w: 0)
db.collection.insertOne({ name: "test" }, { writeConcern: { w: 0 } });

// Acknowledged (w: 1)
db.collection.insertOne({ name: "test" }, { writeConcern: { w: 1 } });

// Majority (w: "majority")
db.collection.insertOne({ name: "test" }, { writeConcern: { w: "majority" } });

// Journal enabled (j: true)
db.collection.insertOne({ name: "test" }, { writeConcern: { j: true } });
```

### Advanced Topic 2: Sharding & Horizontal Scaling

**Sharding** distributes data across multiple machines untuk horizontal scaling.

```javascript
// Shard key selection considerations
// Good shard keys:
// - High cardinality (many unique values)
// - Low frequency (even distribution)
// - Non-increasing values
// - Commonly queried fields

// Enable sharding
// Connect to mongos router
sh.enableSharding("myapp");

// Shard collections
sh.shardCollection("myapp.users", { "email": "hashed" });
sh.shardCollection("myapp.orders", { "customerId": 1, "orderDate": 1 });

// Check shard status
sh.status();

// Chunk configuration
// Configure chunk size untuk collections
db.settings.save({
  _id: "chunksize",
  value: 64 // 64MB chunks
});

// Configure balancer
sh.startBalancer();
sh.getBalancerState();

// Monitor shard distribution
db.runCommand({ listShards: 1 });

// Check key distribution
db.users.getShardDistribution();

// Data migration strategies
// Move chunk to specific shard
sh.moveChunk("myapp.users", { minKey: { email: MinKey }, maxKey: { email: "z" } }, "shard1");

// Split chunk
sh.splitChunk("myapp.users", { splitKey: { email: "mid" }, middle: { email: "mid" } });
```

### Advanced Topic 3: Performance Optimization

**Performance optimization** dengan proper indexing, query optimization, dan schema design.

```javascript
// Performance monitoring
// Enable profiler
db.setProfilingLevel(2); // Profile slow queries
db.setProfilingLevel(0); // Disable profiling

// View slow queries
db.system.profile.find().sort({ ts: -1 }).limit(5);

// Check index usage
db.users.getIndexes();
db.users.aggregate([{ $indexStats: {} }]);

// Query optimization examples
// Bad query (collection scan)
db.users.find({ "address.city": "New York" });

// Good query (with index)
db.users.createIndex({ "address.city": 1 });
db.users.find({ "address.city": "New York" });

// Covered queries
// Create covered query index
db.products.createIndex({ category: 1, price: 1, name: 1 });

// Query that uses covered index
db.products.find(
  { category: "electronics", price: { $lt: 1000 } },
  { name: 1, price: 1, _id: 0 }
);

// Query execution stats
db.users.find({ age: { $gt: 25 } }).explain("executionStats");

// Connection pooling configuration
// MongoDB URI dengan connection pooling
mongodb://host1:27017,host2:27017,host3:27017/mydb?replicaSet=myReplicaSet&maxPoolSize=100&minPoolSize=10&maxIdleTimeMS=30000

// Caching strategies
// Application-level caching
const cache = new Map();

function getProduct(productId) {
  // Check cache first
  if (cache.has(productId)) {
    return cache.get(productId);
  }

  // Query database
  const product = db.products.findOne({ _id: productId });

  // Cache result
  cache.set(productId, product);

  return product;
}

// TTL cache implementation
const productCache = new Map();
const CACHE_TTL = 300000; // 5 minutes

function getProductWithTTL(productId) {
  const cached = productCache.get(productId);

  if (cached && (Date.now() - cached.timestamp < CACHE_TTL)) {
    return cached.data;
  }

  const product = db.products.findOne({ _id: productId });

  productCache.set(productId, {
    data: product,
    timestamp: Date.now()
  });

  return product;
}
```

## 🎯 Best Practices

### Schema Design

* **Document Structure**: Embed related data dalam single document
* **Normalization**: Normalize untuk data yang sering diubah
* **Index Strategy**: Create indexes based pada query patterns
* **Data Types**: Use appropriate BSON types untuk optimal storage

### Performance

* **Indexing**: Index fields yang sering digunakan dalam queries
* **Query Optimization**: Use covered queries dan avoid collection scans
* **Connection Pooling**: Configure connection pooling appropriately
* **Memory Management**: Use appropriate working set size

### Security

* **Authentication**: Enable authentication dan authorization
* **Encryption**: Use TLS untuk data in transit
* **Access Control**: Implement role-based access control
* **Auditing**: Monitor dan audit database operations

### Backup & Recovery

* **Regular Backups**: Schedule regular backups
* **Point-in-Time Recovery**: Enable journaling untuk recovery
* **Testing**: Test backup restore procedures
* **Monitoring**: Monitor backup success/failure

## 🌐 Ecosystem

### MongoDB Tools

* **MongoDB Compass**: Official GUI untuk MongoDB
* **MongoDB Atlas**: Cloud-managed MongoDB service
* **MongoDB Charts**: Data visualization
* **MongoDB Atlas Search**: Full-text search capability

### Drivers & Libraries

* **Node.js**: mongodb package
* **Python**: PyMongo, Motor
* **Java**: MongoDB Java Driver
* **Go**: mongo-go-driver

### Integration Services

* **MongoDB Realm**: Mobile synchronization
* **MongoDB Stitch**: Serverless platform
* **MongoDB Atlas Data Lake**: Data lake integration
* **MongoDB Charts**: Visualization service

### Monitoring & Analytics

* **MongoDB Ops Manager**: Enterprise monitoring
* **MongoDB Atlas Monitoring**: Cloud monitoring
* **Third-party Tools**: Various monitoring solutions
* **Performance Metrics**: Comprehensive metrics collection

## 👥 Community

### Official Channels

* **Website**: [mongodb.com](https://www.mongodb.com)
* **Documentation**: [docs.mongodb.com](https://docs.mongodb.com)
* **University**: [university.mongodb.com](https://university.mongodb.com)
* **Blog**: [mongodb.com/blog](https://www.mongodb.com/blog)

### Community Forums

* **MongoDB Community**: [community.mongodb.com](https://community.mongodb.com)
* **Stack Overflow**: [MongoDB Tag](https://stackoverflow.com/questions/tagged/mongodb)
* **Reddit**: [r/mongodb](https://reddit.com/r/mongodb)
* **Discord**: MongoDB Discord server

### Events & Conferences

* **MongoDB World**: Annual MongoDB conference
* **MongoDB Local**: Local MongoDB events
* **Meetups**: MongoDB user groups worldwide
* **Webinars**: Online learning sessions

### Learning Resources

* **MongoDB University**: Free online courses
* **MongoDB Developer Center**: Development resources
* **Tutorials**: Step-by-step tutorials
* **Certification**: MongoDB certification programs

## 📚 References

### Official Documentation

* [MongoDB Manual](https://docs.mongodb.com/manual) - Complete manual
* [MongoDB CRUD Operations](https://docs.mongodb.com/manual/crud) - CRUD guide
* [Aggregation Framework](https://docs.mongodb.com/manual/aggregation) - Aggregation guide
* [Indexing Strategies](https://docs.mongodb.com/manual/indexing) - Indexing guide

### Books & Articles

* **"MongoDB: The Definitive Guide"** by Kristina Chodorow
* **"MongoDB in Action"** by Kyle Banker
* **"50 Tips and Tricks for MongoDB Developers"** - Various authors
* **MongoDB Blog** - Technical articles dan best practices

### Video Resources

* [MongoDB University Videos](https://university.mongodb.com/courses) - Free courses
* [MongoDB YouTube](https://www.youtube.com/c/mongodb) - Official videos
* [Conference Talks](https://www.youtube.com/results?search_query=mongodb+world) - Conference presentations
* [Tutorials](https://www.youtube.com/results?search_query=mongodb+tutorial) - Video tutorials

### Community Resources

* [MongoDB Cookbook](https://cookbook.mongodb.org) - Common recipes
* [Awesome MongoDB](https://github.com/ramnes/awesome-mongodb) - Kumpulan resources
* [MongoDB Tools](https://www.mongodb.com/try/download/tools) - Development tools

## 🔗 Related Technologies

* [NoSQL Databases](https://mahbubzulkarnain.gitbook.io/catatan-seekor-the-series/database/database) - Other NoSQL databases
* [PostgreSQL](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/database/catatan-seekor-postgresql/README.md) - Relational database
* [Redis](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/database/catatan-seekor-redis/README.md) - In-memory database
* [Big Data](https://github.com/mahbubzulkarnain/catatan-seekor-the-series/blob/master/catatan-seekor-bigdata/README.md) - Big data technologies

## 📝 Summary

### What We Covered

* ✅ **Overview**: Konsep dasar MongoDB dan document database
* ✅ **Getting Started**: Installation dan basic operations
* ✅ **Core Concepts**: Documents, collections, indexing, aggregation
* ✅ **Data Modeling**: Schema design best practices
* ✅ **Advanced Topics**: Replication, sharding, performance optimization
* ✅ **Best Practices**: Security, backup, monitoring strategies

### Next Steps

1. **Practice**: Build applications dengan MongoDB
2. **Explore**: Advanced features seperti Atlas Search
3. **Master**: Performance tuning dan optimization
4. **Specialize**: Focus pada specific use cases

### Key Takeaways

* **Document Model**: Flexible schema untuk rapid development
* **Scalability**: Horizontal scaling dengan sharding
* **Performance**: Rich indexing dan optimization options
* **Ecosystem**: Comprehensive tooling dan services

***

## 🤝 Need Help?

Jika Anda mengalami kesulitan atau memiliki pertanyaan:

* **MongoDB Community**: [community.mongodb.com](https://community.mongodb.com)
* **Stack Overflow**: [MongoDB Tag](https://stackoverflow.com/questions/tagged/mongodb)
* **Reddit**: [r/mongodb](https://reddit.com/r/mongodb)
* **Email**: \[<mahbub.zulkarnain@example.com>]

***

**💡 Pro Tip**: Start dengan proper schema design. Use appropriate indexing strategies. Monitor performance regularly. Leverage aggregation framework untuk complex queries.

**⭐ Jika dokumentasi ini bermanfaat, jangan lupa berikan star di repository ini!**
