| Type | Databases | Data Model | Best For | Example Use Case |
|---|---|---|---|---|
| Document | MongoDB, DynamoDB (partial), Cosmos DB (Core) | Nested JSON/BSON documents | Flexible/evolving schema, hierarchical data, catalogs | Product catalog with variable attributes per category |
| Key-Value | Redis, DynamoDB, Riak | Opaque value behind a key | Sessions, caching, leaderboards, feature flags | Session store, distributed cache, rate-limit counters |
| Wide-Column / Column-Family | Cassandra, HBase, Bigtable | Rows with dynamic, sparse columns grouped into column families | Write-heavy, globally distributed, time-ordered data | IoT sensor ingestion, write-heavy event logging at global scale |
| Graph | Neo4j, Amazon Neptune, ArangoDB | Nodes + edges with properties | Highly connected data, traversal-heavy queries | Social graphs, fraud ring detection, recommendation engines |
| Time-Series | InfluxDB, TimescaleDB, Amazon Timestream | Time-indexed measurements, often with downsampling/retention policies built in | Metrics, IoT telemetry, monitoring | Infrastructure metrics, sensor readings, financial tick data |
| Search | Elasticsearch, OpenSearch | Inverted index over documents | Full-text search, log analytics, faceted search | Product search, centralized application log search |
When to Choose Each
✅ Document (MongoDB): flexible schema, rapid prototyping, "read one entity
with all its related data in one round trip" access pattern.
❌ Bad fit: complex multi-entity joins, strict multi-document ACID needs
(supported in MongoDB now, but not its sweet spot), financial ledgers.
✅ Key-Value (Redis): sub-millisecond access, TTL-based expiry, atomic
counters/operations, pub-sub.
❌ Bad fit: complex queries beyond key lookup, anything needing secondary
indexes as a first-class feature.
✅ Wide-Column (Cassandra): must sustain extremely high write throughput
across multiple data centers with no single point of failure (AP system).
❌ Bad fit: ad-hoc queries not aligned to the partition key design — Cassandra
requires you to model tables around your query patterns up front.
✅ Graph (Neo4j): "find all paths/relationships N hops away" is a core query —
these are painful and slow as recursive SQL joins but natural in Cypher.
❌ Bad fit: simple lookups/aggregations — a relational or document store is
simpler and often faster for non-traversal queries.
✅ Time-Series (InfluxDB/TimescaleDB): huge volumes of timestamped
measurements with retention/downsampling policies and time-range queries.
❌ Bad fit: highly relational, non-time-oriented data.
Schema Design Patterns (Document DB)
// Pattern 1: Embedding — for 1:few relationships, atomic single-document reads/writes
{
_id: ObjectId("..."),
name: "John Doe",
addresses: [
{ type: "home", city: "New York", zip: "10001" },
{ type: "work", city: "San Francisco", zip: "94102" }
]
}
// Pattern 2: Referencing — for 1:many / many:many, avoids unbounded array growth
{
_id: ObjectId("..."),
customer_id: ObjectId("..."),
items: [{ product_id: ObjectId("..."), quantity: 2, price: 29.99 }],
total: 59.98
}
// Pattern 3: Bucket pattern — for time-series / IoT data
{
sensor_id: "temp-001",
date: ISODate("2024-01-15"),
readings: [{ time: "08:00", value: 22.5 }, { time: "08:05", value: 22.7 }],
count: 200,
avg: 22.6
}
// ESR rule for compound indexes: Equality, Sort, Range — in that column order
db.orders.createIndex({ status: 1, createdAt: -1, total: 1 });
// Supports: WHERE status = 'active' ORDER BY createdAt DESC
db.products.createIndex({ name: "text", description: "text" });
db.products.find({ $text: { $search: "wireless headphone" } });
db.sessions.createIndex({ lastAccess: 1 }, { expireAfterSeconds: 3600 }); // TTL index
# PyMongo — embedding vs referencing example
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
db = client["ecommerce"]
# Embedding: read the customer and their addresses in one round trip
db.customers.insert_one({
"name": "John Doe",
"addresses": [{"type": "home", "city": "New York"}],
})
# Referencing: order references customer_id, keeps order documents small and independent
db.orders.insert_one({
"customer_id": customer_id,
"items": [{"product_id": pid, "quantity": 2, "price": 29.99}],
"total": 59.98,
})
Interview Q&A
Q1: How do you decide between SQL and NoSQL for a new feature?
| Choose SQL When | Choose NoSQL When |
|---|---|
| Complex relationships and JOINs | Flexible/evolving schema |
| ACID transactions are critical | Very high write throughput required |
| Complex aggregation/reporting | Hierarchical/document-shaped data |
| Team already knows SQL well | Global distribution / multi-region active-active needed |
| Data fits a known, stable schema | Rapid prototyping, schema still unclear |
My default is SQL (PostgreSQL) for transactional data. I add a NoSQL store for a specific, justified use case — MongoDB/Cosmos for an event store or a catalog with highly variable attributes, Redis for caching and session state, Elasticsearch when full-text/faceted search is a first-class requirement. I don’t pick NoSQL as a default “for scale” — PostgreSQL scales further than most people assume before a different data model is actually needed.
Q2: When would you reach for a graph database over a relational one?
When the relationships between entities are the primary thing being queried, not just the entities themselves — “find everyone within 3 hops of this fraud suspect who shares a device fingerprint” is a natural, fast Cypher traversal in Neo4j, but becomes a series of expensive recursive self-joins in SQL that degrade badly as hop count grows. I’d reach for a graph database for fraud ring detection, social/recommendation graphs, and knowledge graphs — but keep the system of record for simple entity data in a relational or document store, since graph databases aren’t usually the best fit for high-volume simple CRUD or aggregation queries.