Data Systems
MongoDB Deep Dive
MongoDB is the leading document database. Master its flexible document model, powerful aggregation pipeline, indexing strategies, and horizontal scaling through sharding.
- Flexible Schema — Evolve your data model without migrations
- Aggregation Pipeline — Server-side data processing with composable stages
- Horizontal Scaling — Automatic sharding across clusters
MongoDB's flexibility is its strength—and its danger. Use it wisely.
MongoDB Architecture
Document Model
Aggregation Pipeline
| Stage | Purpose | SQL Equivalent |
|---|---|---|
| $match | Filter documents | WHERE |
| $group | Group by field(s) | GROUP BY |
| $project | Select/reshape fields | SELECT |
| $sort | Sort results | ORDER BY |
| $limit | Limit results | LIMIT |
| $lookup | Join with another collection | JOIN |
| $unwind | Deconstruct arrays | LATERAL VIEW |
| $bucket | Group into ranges | GROUP BY RANGE |
| $facet | Multiple pipelines in parallel | Subqueries |
Indexing Strategies
| Index Type | Use Case | Example |
|---|---|---|
| Single field | Simple equality/range | db.users.createIndex({email: 1}) |
| Compound | Multi-field queries | db.users.createIndex({city: 1, age: -1}) |
| Multikey | Array field queries | db.users.createIndex({tags: 1}) |
| Text | Full-text search | db.articles.createIndex({content: "text"}) |
| Hashed | Equality only (sharding) | db.users.createIndex({email: "hashed"}) |
| TTL | Auto-expire documents | db.sessions.createIndex({created_at: 1}, {expireAfterSeconds: 3600}) |
Sharding
| Shard Key Strategy | Description | Best For |
|---|---|---|
| Hashed | Hash of shard key | Even distribution, equality queries |
| Ranged | Range-based distribution | Range queries, time-series |
| Zone | Geographic distribution | Data residency requirements |
Replica Sets
Common Anti-Patterns
| Anti-Pattern | Problem | Solution |
|---|---|---|
| Unbounded arrays | Document growth, poor performance | Limit array size, normalize |
| Massive documents | Slow queries, memory pressure | Keep documents small |
| Missing indexes | Collection scans | Add appropriate indexes |
| Wrong shard key | Hot partitions, scatter-gather | Choose high-cardinality key |
| Over-normalization | Excessive $lookup | Denormalize for read patterns |
Practice Exercises
-
Document Design: Design the MongoDB document schema for a blogging platform with users, posts, comments, tags, and categories. Decide what to embed vs reference.
-
Aggregation Pipeline: Write an aggregation pipeline to find the top 5 most popular products in the last 7 days, including average rating and total sales.
-
Sharding Design: Design the sharding strategy for a social media app with 100M users. What shard key would you choose? How do you handle hot users?
-
Index Optimization: Given a MongoDB collection with 50M documents and these query patterns, design the optimal indexes:
- Find users by email (unique)
- Find users by city and age range
- Search users by name (partial match)
- Get recent users by creation date
What to Learn Next
-> NoSQL Deep Dive Document, key-value, column-family, and graph databases overview.
-> SQL Deep Dive PostgreSQL, MySQL, indexing strategies, and query optimization.
-> PostgreSQL Deep Dive Advanced PostgreSQL features, extensions, and optimization.
-> Redis Deep Dive Redis data structures, persistence, clustering, and use cases.
-> Data Partitioning Sharding strategies, consistent hashing, and partition keys.
-> Choosing the Right Database Systematic framework for database selection.