Section 2: NoSQL Foundations

🎯 When to Use MongoDB?

Making the Right Database Choice: Understanding When MongoDB Excels and When Traditional Databases Are Better

📖 The Wrong Database Choice That Cost $1 Million

Meet Alex, CTO of a social media startup. In 2018, they chose PostgreSQL for their application because "it's what we know." Their platform allowed users to share posts with photos, videos, comments, likes, tags, and nested comments.

Year 1: Everything worked with 10,000 users. Database had 50 tables with complex joins. Adding a new feature like "stories" required changing 15 tables and took 2 weeks.

Year 2: 500,000 users. Database performance degraded. Queries with 8-table joins took 5 seconds. They hired 3 DBAs, added read replicas, implemented complex caching - spent $500,000.

Year 3: 2 million users. The breaking point came when they wanted to add "user preferences" (notification settings, privacy controls, theme preferences). This required adding 20+ columns across multiple tables, migrating millions of rows, and 4 weeks of downtime planning.

The Switch: They migrated to MongoDB. Each user became a single document with all their data, posts, preferences, settings. New features took days instead of weeks. Query performance improved 10x. Development velocity increased 5x.

The Cost: The migration cost $500,000 and 6 months. Total wasted: $1 million and 2 years of slow development. If only they had chosen the right database from the start!

MongoDB vs SQL: Decision Framework

Decision Flowchart: Should You Use MongoDB?
START Is your data structure flexible/changing OR document-oriented? YES Do you need complex multi-table JOINs frequently? NO YES Do you need ACID transactions across many tables? NO YES ❌ USE SQL (PostgreSQL, MySQL) NO Do you need horizontal scaling OR rapid development OR flexible schema? YES ✅ USE MONGODB Perfect for your use case! NO ⚠️ EITHER Both work - choose based on team expertise

✅ Perfect Use Cases for MongoDB

📱

1. Mobile & Web Apps

Why Perfect: User profiles with varying attributes, fast iteration

Example: Social media, dating apps, fitness trackers

Key Benefit: Add new user fields without schema migration

Real Company: LinkedIn uses MongoDB for profile data

📊

2. Real-Time Analytics

Why Perfect: High write throughput, flexible data formats

Example: IoT sensors, user behavior tracking, server logs

Key Benefit: Aggregation pipeline for real-time insights

Real Company: Uber uses MongoDB for real-time pricing

🛒

3. E-Commerce Catalogs

Why Perfect: Products have vastly different attributes

Example: Books (ISBN, pages) vs Shoes (size, color) vs Electronics (specs)

Key Benefit: No need for EAV or JSON columns

Real Company: eBay uses MongoDB for product catalog

📰

4. Content Management

Why Perfect: Articles, blogs, comments - all document-oriented

Example: CMS, blogging platforms, news sites

Key Benefit: Store entire article + comments in one document

Real Company: The Guardian uses MongoDB for CMS

🎮

5. Gaming Platforms

Why Perfect: Player profiles, game states, leaderboards

Example: MMO games, mobile games, esports platforms

Key Benefit: Horizontal scaling for millions of concurrent players

Real Company: EA uses MongoDB for gaming backend

📡

6. IoT & Sensor Data

Why Perfect: High-volume time-series data, varying sensor types

Example: Smart homes, industrial IoT, weather stations

Key Benefit: Time-series collections optimized for IoT

Real Company: Bosch uses MongoDB for IoT platform

🎯

7. Personalization Engines

Why Perfect: User preferences, recommendations, behavior tracking

Example: Netflix recommendations, Amazon suggestions

Key Benefit: Flexible schema for evolving recommendation models

Real Company: Spotify uses MongoDB for user preferences

💬

8. Chat & Messaging Apps

Why Perfect: Messages, threads, attachments, read receipts

Example: Slack-like apps, customer support chat

Key Benefit: Store conversation threads as nested documents

Real Company: Snapchat uses MongoDB for messaging

✅ Common Patterns That Indicate MongoDB is Perfect

  • Rapid development cycles - Features released weekly/bi-weekly
  • Flexible data models - Different entities have different attributes
  • Nested data structures - Arrays, embedded documents natural fit
  • Horizontal scaling requirements - Need to scale to millions of users
  • High read/write throughput - Thousands of operations per second
  • Document-centric operations - Usually work with entire documents
  • Schema evolution - Requirements change frequently
  • Unstructured or semi-structured data - JSON-like data from APIs

👍 Good (But Not Perfect) Use Cases

💡 MongoDB Works, But Alternatives May Be Better

These scenarios work with MongoDB, but you should consider other specialized databases or SQL depending on your specific needs.

💰

Financial Transactions

MongoDB Works: With multi-document ACID transactions (4.0+)

Better Alternative: PostgreSQL for complex financial rules

Use MongoDB If: Need flexible transaction data + horizontal scaling

Caution: Cross-shard transactions have performance overhead

🏥

Healthcare Records

MongoDB Works: Patient records are document-oriented

Better Alternative: Specialized healthcare DBs (FHIR servers)

Use MongoDB If: Need flexible EHR with varying data structures

Caution: Compliance requires careful schema design

📈

Business Intelligence

MongoDB Works: Aggregation pipeline is powerful

Better Alternative: Columnar DBs (ClickHouse, BigQuery)

Use MongoDB If: BI on operational data, not data warehouse

Caution: Not optimized for OLAP-style queries

🔍

Full-Text Search

MongoDB Works: Has text search and Atlas Search

Better Alternative: Elasticsearch, Algolia

Use MongoDB If: Search is secondary feature, not core

Caution: Search capabilities limited vs specialized engines

❌ When to Avoid MongoDB

🚫 Scenarios Where MongoDB is NOT Recommended

  • Complex multi-entity relationships - Heavy use of JOINs across many tables (ERPs, complex inventory systems)
  • Reporting with complex aggregations - Data warehouse scenarios, business intelligence with star schemas
  • Strict ACID across entire database - Banking core systems, stock trading platforms
  • Graph-heavy applications - Social networks with friend-of-friend queries, recommendation engines based on graph traversal
  • Small datasets with complex logic - Internal tools with <10GB data but complex business rules
  • Heavy reliance on database-level constraints - Systems requiring foreign key enforcement, check constraints
  • Legacy systems integration - Existing SQL-heavy infrastructure, BI tools designed for SQL
  • Team has zero MongoDB experience - And no time/budget for learning curve
Why SQL Beats MongoDB in These Scenarios
Complex Multi-Table JOINs Orders → Customers → Products → Categories → Suppliers → Warehouses MongoDB: Multiple lookups, slow & complex SQL: Single query with JOINs, optimized Multi-Table ACID Transfer money: Debit Account A Credit Account B Update Transaction Log MongoDB: Possible but performance hit SQL: Native, fast, reliable ACID Complex Analytics Monthly sales by region, category, customer segment with year-over-year growth MongoDB: Complex pipeline, harder to optimize SQL: Window functions, CTEs, optimized
💡 Rule of Thumb

If your application could be modeled as a traditional ERP with many interconnected tables and complex business rules, stick with SQL.

MongoDB shines when data is naturally document-oriented, schema is flexible, and you need horizontal scalability.

MongoDB vs SQL: Feature Comparison

Feature MongoDB SQL (PostgreSQL/MySQL)
Data Model ✅ Document-oriented (JSON/BSON)
Flexible, nested structures
⚠️ Table-based (rows/columns)
Fixed schema
Schema ✅ Flexible, dynamic
Add fields without migration
⚠️ Rigid, predefined
ALTER TABLE for changes
Relationships ⚠️ Embedded docs or manual refs
$lookup for joins (slower)
✅ Foreign keys, JOINs
Optimized for relational data
ACID Transactions ✅ Multi-document (4.0+)
Performance hit on sharded
✅ Native, mature
Excellent performance
Horizontal Scaling ✅ Built-in sharding
Scale to petabytes easily
⚠️ Complex, application-level
Requires custom solutions
Query Language ⚠️ MongoDB Query Language
Learning curve for SQL devs
✅ Standard SQL
Universal, well-known
Performance (Read) ✅ Very fast for single docs
All related data in one place
⚠️ Fast with proper indexes
Slower with complex JOINs
Performance (Write) ✅ Excellent high-volume writes
No foreign key overhead
⚠️ Good, but FK checks slow
Development Speed ✅ Rapid prototyping
Schema-less agility
⚠️ Slower, need migrations
Data Integrity ⚠️ Application-level
No referential integrity
✅ Database-level
Foreign keys, constraints
Use Case ✅ Apps, IoT, catalogs, CMS
Flexible, evolving schemas
✅ ERP, finance, complex rules
Well-defined relationships

Real-World Migration Stories

📱 Craigslist → MongoDB

From: MySQL with 100+ tables

Why Switch: Schema changes took weeks, performance issues at scale

Result: 10x faster queries, deploy new features in days

Lesson: MongoDB perfect for classified ads with varying attributes

📰 The Guardian → MongoDB

From: Relational CMS

Why Switch: Articles + comments + tags required 12 tables, complex queries

Result: Single document stores everything, 60% faster page loads

Lesson: Content naturally fits document model

🎮 EA Sports → MongoDB

From: MySQL for player profiles

Why Switch: 300M players, each with different game stats/achievements

Result: Horizontal scaling handled growth, flexible schema for new games

Lesson: Gaming data varies greatly, needs flexibility

💳 Stripe → Stayed with PostgreSQL

Considered: MongoDB for flexibility

Why NOT Switch: Financial transactions need strict ACID, complex rules

Decision: PostgreSQL better for their compliance/audit needs

Lesson: Not every modern app needs MongoDB

Decision Checklist: Should You Use MongoDB?

✅ Answer YES to MongoDB If:

  • Your data is naturally document-oriented (users, products, articles)
  • Different entities have wildly different attributes
  • You need to scale horizontally (millions of users)
  • Schema changes frequently (rapid feature development)
  • Most operations fetch/update entire documents
  • You rarely need complex multi-entity JOINs
  • Team comfortable with JavaScript/JSON
  • High write throughput required (IoT, logging, analytics)

❌ Answer NO to MongoDB (Use SQL) If:

  • Your data is highly relational with many interconnections
  • You need database-level referential integrity
  • Complex reporting with multi-table aggregations is core feature
  • ACID transactions across many entities are critical
  • Team has strong SQL expertise, zero NoSQL experience
  • Existing infrastructure heavily SQL-based
  • Strict compliance requirements need database constraints
  • Your application could be modeled as traditional ERP
💡 The Hybrid Approach

Many companies use BOTH! Example: PostgreSQL for core transactions + MongoDB for product catalog + Redis for caching + Elasticsearch for search.

Don't feel locked into one database technology. Use the right tool for each job!

💼 Interview Questions & Answers

Q1 When would you choose MongoDB over a relational database? ▼

Answer:

I would choose MongoDB when:

  • Data is document-oriented: Users, products, articles naturally fit JSON structure
  • Flexible schema needed: Requirements change frequently, different entities have different fields
  • Horizontal scaling required: Need to scale to millions of users/documents
  • Rapid development: Want to iterate fast without schema migrations
  • Nested data common: Arrays, embedded documents natural (e.g., user with addresses array)

Example: E-commerce product catalog where Books have ISBN/pages, Shoes have size/color, Electronics have specs - MongoDB allows each product type to have different fields naturally.

Q2 When should you NOT use MongoDB? ▼

Answer - Avoid MongoDB when:

  • Complex multi-table JOINs are frequent: ERP systems, complex inventory management
  • Strict ACID across entire DB: Banking core systems, stock trading
  • Need referential integrity: Database must enforce foreign key constraints
  • Complex reporting/BI: Data warehouse with star schemas, OLAP queries
  • Small dataset, complex rules: Internal tools with strict business logic

Example: Accounting software with General Ledger, Accounts Payable/Receivable, Invoices, Payments - highly interconnected with complex rules - PostgreSQL would be better.

Q3 Can you give a real-world example where MongoDB replaced SQL successfully? ▼

Answer - Craigslist Migration:

Before (MySQL):

  • 100+ tables for different listing categories
  • Adding new category required weeks (create tables, migrate data, update code)
  • Complex queries joined 8-10 tables
  • Performance degraded with scale

After (MongoDB):

  • Single "listings" collection with flexible schema
  • New category = just add documents with new fields (minutes)
  • Queries fetch entire listing in one operation (10x faster)
  • Horizontal sharding handled growth

Why it worked: Classified ads are naturally document-oriented - each listing has different attributes based on category.

Q4 What are the main trade-offs when choosing MongoDB over SQL? ▼

Answer - Key Trade-offs:

MongoDB Advantages:

  • Flexible schema - rapid development
  • Horizontal scaling built-in
  • Document model matches application objects
  • High write throughput

MongoDB Trade-offs:

  • No database-level referential integrity (application must handle)
  • JOINs (lookups) less efficient than SQL
  • Data duplication common (denormalization)
  • Team learning curve if SQL-focused

Decision: Choose based on your specific use case, not trends. If data is highly relational with complex integrity rules, SQL is better.

Q5 How do you decide between MongoDB and PostgreSQL for a new project? ▼

Answer - My Decision Framework:

1. Analyze Data Model:

  • Document-oriented with flexible schema → MongoDB
  • Highly relational with many connections → PostgreSQL

2. Consider Operations:

  • Mostly fetch entire documents → MongoDB
  • Frequent complex JOINs → PostgreSQL

3. Evaluate Requirements:

  • Need horizontal scaling → MongoDB
  • Need strict ACID across many tables → PostgreSQL

4. Assess Team:

  • JavaScript/JSON expertise → MongoDB
  • Strong SQL skills, no time to learn → PostgreSQL

5. Consider Growth:

  • Rapid feature changes → MongoDB flexibility helps
  • Stable schema, complex rules → PostgreSQL constraints help

Remember: Both are excellent databases. The "best" choice depends on your specific needs, not industry hype.

Q6 Can you use MongoDB for applications that require ACID transactions? ▼

Answer:

Yes, since MongoDB 4.0 (released 2018) supports multi-document ACID transactions.

How it works:

  • Use sessions with startTransaction()
  • Perform operations within transaction
  • commitTransaction() or abortTransaction()
  • Supports snapshot isolation

Performance Considerations:

  • Single-document operations are still atomic (no transaction overhead)
  • Multi-document transactions have performance cost
  • Cross-shard transactions even more expensive

Recommendation: If your app heavily relies on multi-document transactions across many collections, PostgreSQL is likely better. MongoDB transactions work but are not as optimized as SQL databases built from ground up for ACID.

Best Practice: Design schema to minimize need for transactions (embed related data in single document when possible).