Skip to content

Expert: design, speed and engines · Procedures, triggers, SQL engines and NoSQL · topic 55 of 62 · 30 min

NoSQL: documents, key-value, wide-column and graph

Explanation

NoSQL databases store data in shapes other than tables: documents, key-value pairs, wide columns or graphs. They grew out of the need to spread huge, changing data over many cheap servers. The CAP theorem says that during a network split a distributed database must choose between consistency and availability. NoSQL does not mean "no transactions": MongoDB has multi-document ACID transactions since version 4.0.

Why NoSQL appeared

In the 2000s, web companies hit limits of a single relational server: billions of rows, traffic from every country, and data whose shape changed every week. Making one server bigger (scaling up) gets expensive and eventually stops. They needed to spread data across many servers (scaling out), and they wanted to add a field without a migration. New databases were built for that. They were called NoSQL, which today is usually read as "not only SQL".

Two words first. A schema is the agreed structure of the data (tables, columns, types). Flexible schema means each record may have different fields, and the database does not enforce one structure; your application does.

The four families

FamilyHow data looksExamplesGood for
DocumentJSON-like documents with nested fields and arraysMongoDB, Couchbase, FirestoreProduct catalogues, user profiles, content where fields vary
Key-valueA key and an opaque value, looked up by keyRedis, Amazon DynamoDB, etcdCaches, sessions, counters, shopping carts
Wide-columnRows grouped by a partition key, many columns per row, spread over many serversApache Cassandra, ScyllaDB, HBaseHuge write-heavy data: sensor readings, messages, event logs
GraphNodes and relationships (edges) with propertiesNeo4j, Amazon NeptuneFriends-of-friends, fraud rings, recommendations, route finding

DynamoDB is usually called key-value, but it also stores document-style items. Many products blur the lines, so think of the families as shapes, not strict boxes.

Think of it like this: Think of four ways to store information at home. A file folder per person, each with different papers inside, is a document store. A wall of numbered lockers is key-value: you need the number to open one. A huge register book split across many shelves by date is wide-column. A family tree drawn on paper, all about who is linked to whom, is a graph.

The CAP theorem in plain words

When data lives on several servers, the network between them can break: this is a partition. The CAP theorem (Eric Brewer's idea, proven in 2002) says: during a partition, a database must choose. Either it stays Consistent (every read sees the latest write, so some requests must wait or fail) or it stays Available (every request gets an answer, which may be stale).

  • Misreading 1: "pick any two of three". Partitions happen whether you like it or not, so the real choice is C or A while a partition lasts. When the network is healthy, you can have both.
  • Misreading 2: the C in CAP is the C in ACID. It is not. CAP's C means every reader sees the newest value; ACID's C means rules and constraints hold.
  • Misreading 3: "NoSQL is AP, SQL is CP". Many systems let you choose per query, for example Cassandra's consistency levels or MongoDB's read and write concerns.
Tip: An extension called PACELC adds the everyday case: Else (no partition), a system still trades Latency against Consistency. Waiting for every copy is safer but slower.

BASE vs ACID

Module 8 taught ACID: Atomic, Consistent, Isolated, Durable. Many early NoSQL systems chose BASE instead: Basically Available, Soft state, Eventually consistent. Eventually consistent means copies may disagree for a short time, but if writes stop, they all end up with the same value. A "like" count that is a second late is fine; a bank balance is not.

The line has blurred. MongoDB supports multi-document ACID transactions since version 4.0 (and across shards since 4.2). DynamoDB has transactions too. And distributed SQL databases such as CockroachDB, YugabyteDB and Google Spanner scale out while keeping SQL and ACID.

Common mistakes

  • Choosing NoSQL "because it scales" for an app with ten thousand users. Fix: a single PostgreSQL or MySQL server handles a lot; choose by data shape and access pattern.
  • Thinking "schemaless" means "no design". Fix: in document stores you design around the queries you will run; the schema simply lives in your code.
  • Assuming NoSQL has no transactions, or that every NoSQL query is eventually consistent. Fix: read the current docs of the product.
  • Using a graph database for simple lookups, or a key-value store for reports. Fix: match the family to the questions you ask.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

NoSQL: documents, key-value, wide-column and graph · 1/7

NoSQL: not only SQL

NoSQL databases store data in shapes other than tables. Let us see why they appeared and what kinds exist.

Prefer a video by a teacher? Find free videos on “nosql database types document key value wide column graph cap theorem explained” on YouTube ↗

In real life: One food-delivery app, several data shapes

A food-delivery app like Swiggy or Zomato has very different kinds of data. Orders and payments need transactions, so a relational database is a natural fit. Restaurant menus vary a lot from place to place, so some teams store them as documents. The rider's live location and the "is this restaurant open" flag change every few seconds and are read constantly, which suits a fast key-value store. A "people who ordered this also ordered" feature is a graph question. This is typical of how such systems are described publicly, not the design of any particular company.

Practice (0/3 done)

Task 1 · Question

A ride-hailing app wants to show "drivers within 2 km" and store each driver's latest location, updated every 3 seconds, with very fast reads. Which family fits the latest-location store best?

Task 2 · Code · SQL

See the key-value idea inside SQL. Create a table kv(key TEXT PRIMARY KEY, value INTEGER NOT NULL). Then count page views like Redis INCR, using an upsert: INSERT INTO kv VALUES ('views:home', 1) ON CONFLICT(key) DO UPDATE SET value = value + 1; Run it for 'views:home' three times and for 'views:cart' once. Finally return key and value from kv.

Task 3 · Practice

Match each need to a database family and give a one-line reason: (1) user login sessions that expire after 30 minutes, (2) a product catalogue where phones, sarees and rice have very different attributes, (3) 50,000 smart electricity meters sending a reading every minute, (4) finding mutual friends and "people you may know", (5) bank account balances and transfers.

Quick quiz

Question 1

1.Which database is a graph database?

Question 2

2.What does the CAP theorem actually say?

Question 3

3.Since which version does MongoDB support multi-document ACID transactions (on replica sets)?

Question 4

4.What does "eventually consistent" mean?

Question 5

5.Which need is the best fit for a wide-column store such as Cassandra?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which database is a graph database?

Answer: Neo4j

Neo4j stores nodes and relationships and is queried with Cypher.

What does the CAP theorem actually say?

Answer: During a network partition, a distributed database must choose between consistency and availability

The choice is forced only while a partition lasts. Partition tolerance is not optional for a distributed system.

Since which version does MongoDB support multi-document ACID transactions (on replica sets)?

Answer: 4.0

MongoDB 4.0 added multi-document transactions on replica sets, and 4.2 extended them to sharded clusters.

What does "eventually consistent" mean?

Answer: Copies may differ for a short time, but agree once writes stop

Replicas catch up over time; a read may briefly return an older value.

Which need is the best fit for a wide-column store such as Cassandra?

Answer: Billions of sensor readings written every second across many servers

Wide-column stores shine at huge, write-heavy, partitioned data.

In MongoDB, what is a collection?Related

Answer: A group of documents, like a table

A collection holds many documents, the way a SQL table holds many rows.

From NoSQL and MongoDB

Why do apps store users in a database and not in an array in the code?Related

Answer: An array is lost when the server restarts

An array lives in memory and disappears on restart. A database keeps data safely on disk.

From What is a database?

Which ACID property means "after the app shows Payment successful, a power cut cannot undo it"?Related

Answer: Durable

Durable: once committed, the change is safely stored and survives crashes.

From Transactions and ACID

Which ACID property promises that a committed booking survives a power cut?Related

Answer: Durability

Durability: once COMMIT returns, the change is safely on disk.

From ACID, isolation and locking

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 2 more topics in “Procedures, triggers, SQL engines and NoSQL” before its exam: MongoDB and Redis in practice, Choosing a database, and keeping it safe.
  2. Module 11 exam: procedures, triggers, engines and NoSQL · 13 questions · 25 min, without help. 6 topics of this module still to finish first.
  3. Then the next module, Interview questions and practice projects. 62 topics left in the course before the final exam.

← Previous: MySQL vs PostgreSQL vs SQLite vs SQL Server