4.4.24Databases

NoSQL — document (MongoDB), key-value (Redis), column (Cassandra), graph (Neo4j)

2,503 words11 min readdifficulty · medium

WHAT are the four families?

Figure — NoSQL — document (MongoDB), key-value (Redis), column (Cassandra), graph (Neo4j)

HOW each one works (with WHY)

1. Document — MongoDB

// A single document — schema is per-document, not per-table
{
  "_id": ObjectId("..."),
  "name": "Asha",
  "emails": ["asha@x.com"],            // arrays allowed
  "address": { "city": "Pune", "pin": 411001 }  // nested doc
}
db.users.find({ "address.city": "Pune" })   // query into nested fields
  • Indexing: B-tree indexes on any field (incl. nested). Without an index a query is an O(N)O(N) collection scan.
  • Tradeoff: data is often denormalised/duplicated → fast reads, but updates to duplicated data are harder.

2. Key-Value — Redis

SET session:abc  "{...}"  EX 3600     # value with 1-hour TTL
GET session:abc
INCR page:views                       # atomic counter
LPUSH queue task1                     # built-in list/set/sorted-set types
  • Use cases: caching, rate-limiting, leaderboards (sorted sets), pub/sub, queues.
  • Tradeoff: limited query power (you must know the key); data must mostly fit in memory.

3. Wide-Column — Cassandra

CREATE TABLE sensor_data (
  sensor_id text,
  ts        timestamp,
  value     double,
  PRIMARY KEY (sensor_id, ts)   -- partition key = sensor_id, clustering key = ts
);
  • Partition key → which node; clustering key → sort order within a partition.
  • Writes use a log-structured merge (LSM) path (append to commit log + memtable → flush to SSTable), so writes are very fast and append-only.
  • Tradeoff: no joins, no ad-hoc queries — query patterns must be known in advance.

4. Graph — Neo4j

MATCH (a:Person {name:'Asha'})-[:FRIEND]->(b)-[:FRIEND]->(c)
RETURN c.name   // friends-of-friends in two cheap hops
  • Tradeoff: not built for huge bulk aggregations; harder to shard across machines.

The theory glue: CAP & BASE


Worked examples


Common mistakes


Flashcards

What does NoSQL stand for?
"Not Only SQL" — a family of non-relational databases optimised for specific data models/scale.
Name the four NoSQL families with one example each.
Document(MongoDB), Key-Value(Redis), Wide-Column(Cassandra), Graph(Neo4j).
Why does Redis achieve ~O(1)O(1) lookups?
It's an in-memory hash map keyed by exact keys.
What is "index-free adjacency" in graph DBs?
Each node stores direct pointers to its neighbours, so a hop is O(1)O(1) independent of graph size.
In Cassandra, what does the partition key decide vs the clustering key?
Partition key → which node stores the row; clustering key → sort order within that partition.
State the CAP theorem.
During a network partition you can keep only Consistency OR Availability, not both.
Give the quorum condition for strong consistency.
W+R>NW + R > N (read and write replica sets overlap).
With N=3N=3, give a strong-consistency quorum.
W=2,R=2W=2, R=2 (since 4>34>3).
What does BASE stand for?
Basically Available, Soft state, Eventually consistent.
Why must "P" in CAP be assumed in practice?
Network partitions are unavoidable, so the real choice is CP vs AP.
When does MongoDB beat SQL joins?
When you fetch one nested entity — it's a single document read with no joins.
What write path makes Cassandra fast for writes?
LSM: append to commit log + memtable, later flush to immutable SSTables.
Recall Feynman: explain to a 12-year-old

Imagine four ways to keep your stuff. Redis is a row of labelled lockers — you know the locker number, you grab it instantly, super fast, but you must remember the number. MongoDB is a folder where each toy comes in its own complete box, with all its little parts inside — grab one box, you have everything. Cassandra is a giant warehouse with many workers; new boxes get split across workers so they never get overwhelmed, but you must label boxes before you store them. Neo4j is a friendship map: each kid holds a string to each friend, so "find friends of friends" is just following strings — no searching the whole school. And CAP: if the phone lines between two warehouses go dead, you either wait until they reconnect (correct but slow) or answer with possibly-old info (fast but maybe stale). You can't do both.


Connections

  • SQL Relational Databases — ACID, JOINs, normalization (the contrast class)
  • CAP Theorem / BASE vs ACID
  • Database Indexing (B-tree, LSM) — why Mongo reads vs Cassandra writes
  • Hashing and Hash Maps — basis of key-value & partitioning
  • Sharding and Replication
  • Caching Strategies — Redis as a cache layer
  • Graph Traversal Algorithms (BFS/DFS) — what Neo4j optimises

Concept Map

drops guarantees for

match model to

family

family

family

family

stores

gives

tradeoff

is a

gives

hashes

enables

models

optimised for

NoSQL Not Only SQL

Flexible schema and scale

Access pattern

Document MongoDB

Key-Value Redis

Wide-Column Cassandra

Graph Neo4j

Nested JSON BSON docs

One read returns entity

Denormalised duplication

In-memory hash map

Average O 1 lookup

Partition key spreads writes

Write-heavy linear scale

Nodes and edges

Fast traversals

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Dekho, NoSQL ka matlab "Not Only SQL" hai — yeh ek family hai databases ki jahan hum rigid rows-and-columns wali table ko chhod dete hain, aur apne data model ko access pattern ke hisaab se choose karte hain. Char main types hain: Document (MongoDB) jahan poora object ek nested JSON box ki tarah store hota hai — ek hi read mein puri entity mil jaati hai, JOIN ki zarurat nahi. Key-Value (Redis) ek RAM ka hash map hai — agar tumhe key pata hai (jaise session token), toh O(1) mein instantly value milti hai, isliye caching aur counters ke liye best. Wide-Column (Cassandra) write-heavy aur globally distributed kaam ke liye hai — partition key se decide hota hai data kis node pe jaayega, isliye writes evenly spread hote hain. Graph (Neo4j) tab use karo jab relationships hi data hain (social network, recommendations) — har node apne neighbours ke direct pointers rakhta hai, toh "friends of friends" nikalna sasta hota hai.

Sabse important concept hai CAP theorem. Jab network mein partition (do hisson ke beech link toot jaaye) ho jaye, tab tum sirf do cheezein rakh sakte ho: ya toh Consistency (har read latest value de) ya Availability (har request answer de) — dono ek saath nahi. Practical systems mein partition hona to tay hai, isliye asli choice hai CP vs AP. SQL ki ACID ki jagah NoSQL aksar BASE (Basically Available, Soft state, Eventually consistent) follow karta hai — replicas thodi der alag reh sakte hain par baad mein sync hokar converge kar jaate hain.

Freshness control karne ke liye ek simple formula yaad rakho: agar NN replicas hain, WW nodes write pe ack dete hain, aur RR nodes se padhte ho, toh W+R>NW + R > N hone par read aur write sets overlap karte hain, matlab tumhe latest value guarantee milti hai. Jaise N=3N=3 pe W=2,R=2W=2, R=2 -> strong consistency. Last baat — yeh mat sochna ki "NoSQL hamesha fast hai" ya "schema design ki zarurat nahi". NoSQL sirf matching access pattern ke liye fast hai, aur schema design ab tumhare application aur queries mein shift ho jaata hai. Galat access pattern choose kiya toh NoSQL bhi slow ho jayega.

Go deeper — visual, from zero

Test yourself — Databases

Connections