When to use NoSQL: MongoDB, Redis and DynamoDB
NoSQL is several different database designs, not one. Learn what MongoDB, Redis and DynamoDB are good and bad at, and how to choose from your data shape and queries, a common interview question.
A relational database such as PostgreSQL is the right default for most backends: tables, rows, joins and transactions. But sometimes your data or your traffic fits a different shape better. "NoSQL" is a loose name for databases that are not built around tables and SQL. It is not one thing. It covers several very different designs, and choosing between them is a common interview question.
In this lesson you will learn the main NoSQL families, how MongoDB, Redis and DynamoDB each work, and a simple way to decide. You should already know basic SQL (see *SQL and PostgreSQL for backend developers*). Using Redis as a cache is practised in *Caching with Redis*.
The four families
NoSQL is a group of designs, not one
| Family | Stores | Example products | Good at |
|---|---|---|---|
| Document | JSON-like documents, grouped in collections | MongoDB | Records with varied or nested fields, fast-changing shape |
| Key-value | A value looked up by a key | Redis, DynamoDB | Very fast lookups by key, sessions, caches, counters |
| Wide-column | Rows with flexible columns, spread over many machines | Cassandra | Huge write volumes, time-series style data |
| Graph | Nodes and relationships | Neo4j | Friends-of-friends, recommendations, fraud rings |
This lesson focuses on the three you will meet most in job postings: MongoDB (document), Redis (key-value, in memory) and DynamoDB (key-value and document, managed by AWS).
Document databases: MongoDB
Think of a filing cabinet where each folder is a self-contained document. In MongoDB a document is a JSON-like object, and a collection is a group of documents (like a table, but without a fixed set of columns).
A Brew & Bean order fits this well. In SQL you would split it across orders and order_items tables and join them. In MongoDB you can store the whole order, items included, as one document, and read it back in one go.
{
"_id": "ord_1042",
"customer_name": "Asha",
"phone": "9876543210",
"items": [
{"item_id": "cappuccino", "qty": 2, "price": 180},
{"item_id": "banana-bread", "qty": 1, "price": 130}
],
"total": 490,
"status": "received",
"created_at": "2026-10-31T09:15:00Z"
}Items are embedded inside the order. Reading the order needs no join.
# pip install pymongo
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017")
orders = client["brewbean"]["orders"] # database "brewbean", collection "orders"
orders.insert_one({
"_id": "ord_1042",
"customer_name": "Asha",
"items": [{"item_id": "cappuccino", "qty": 2, "price": 180}],
"total": 360,
"status": "received",
})
print(orders.find_one({"_id": "ord_1042"}))
# Move the order to the next status
orders.update_one({"_id": "ord_1042"}, {"$set": {"status": "preparing"}})
# All orders that contain a cold brew
for o in orders.find({"items.item_id": "cold-brew"}):
print(o["_id"])
# Fast lookups need an index, just like SQL
orders.create_index("status")Needs a running MongoDB (local install, Docker, or a free-tier cluster on MongoDB Atlas). $set changes only the named field.
Strengths: flexible shape (two documents in a collection can have different fields), nested data read in one query, easy to start with, scales out across machines.
Weaknesses: joins across collections are awkward, so data that is shared between many records tends to be copied (duplicated), and keeping the copies in sync is your job. MongoDB does support multi-document transactions, but they are not the everyday path they are in PostgreSQL. Because the database does not enforce a schema by default, messy data can creep in unless you validate it in your code.
Embedding has limits
Schemaless does not mean "no design". You still decide what to embed and what to reference. A common mistake is embedding something that grows without limit (for example every comment ever made on a post inside the post document). Documents have a size limit, and huge documents are slow to read and update.
Key-value in memory: Redis
Redis is a database that keeps its data in RAM. That makes it extremely fast (a simple read is usually well under a millisecond), but RAM is small and costly compared with disk, and data held only in RAM can be lost if the server restarts unless you turn on Redis persistence options.
Think of a notice board next to the shop counter: instant to read, small, and you only pin up what is needed right now. Redis is used for caches, login sessions, rate-limit counters, leaderboards, queues and temporary data that can expire by itself.
redis-cli
> SET menu:espresso "120"
OK
> GET menu:espresso
"120"
> SET session:abc123 "user_42" EX 3600 # expires in one hour
OK
> TTL session:abc123
(integer) 3599
> INCR visits:today # atomic counter
(integer) 1
> INCR visits:today
(integer) 2
> HSET order:1042 status preparing total 490 # a hash: like a small object
(integer) 2
> HGETALL order:1042
1) "status"
2) "preparing"
3) "total"
4) "490"
> LPUSH queue:orders 1042 # a list, usable as a simple queue
(integer) 1Lines starting with > are what you type at the redis-cli prompt. Text after # is a comment for you.
Redis values are not only strings. Redis has built-in structures: hashes (field-value pairs), lists, sets, sorted sets (great for leaderboards) and more. Commands like INCR are atomic, so two requests incrementing the same counter at the same moment never lose an update.
Strengths: speed, simple commands, built-in expiry (EX, TTL), useful data structures.
Weaknesses: data must fit in memory, querying is by key (you cannot say "find all orders where status is ready" without building your own index), and it is usually a helper next to your main database, not the only store of important data.
Managed key-value and document: DynamoDB
DynamoDB is a database run by AWS. You do not install or patch servers; you create a table and AWS handles the machines, replication and scaling. You choose a partition key (and optionally a sort key), and every read is fast if you look an item up by that key.
For Brew & Bean you might use a table Orders with partition key customer_phone and sort key created_at. Then "all orders for this customer, newest first" is one fast query. The price of this speed is that you must design the table around your questions before you build it. Asking a new kind of question later (for example "all orders in status ready") may need a secondary index or a different design, and ad-hoc querying is far less flexible than SQL.
# pip install boto3 (also needs AWS credentials configured)
import boto3
from boto3.dynamodb.conditions import Key
dynamodb = boto3.resource("dynamodb", region_name="ap-south-1") # Mumbai
table = dynamodb.Table("Orders")
table.put_item(Item={
"customer_phone": "9876543210",
"created_at": "2026-10-31T09:15:00Z",
"status": "received",
"total": 490, # use int or Decimal, boto3 does not accept float
})
# Fast: query by partition key, newest first
result = table.query(
KeyConditionExpression=Key("customer_phone").eq("9876543210"),
ScanIndexForward=False,
)
for item in result["Items"]:
print(item["created_at"], item["status"])Assumes a table named Orders already exists with partition key customer_phone (string) and sort key created_at (string). boto3 rejects Python floats; use int or decimal.Decimal.
Query, don't scan
Be careful with scan. A scan reads the whole table and you pay for every item it reads. If you find yourself scanning, your table design probably does not match your questions.
DynamoDB has a free tier on AWS at the time of writing (2026), but the details change, so check the AWS pricing page before relying on it. Costs depend on how much you read, write and store, so set a billing alert on any AWS account you use for learning.
How to choose
A starting guide, not a rule
| Question | If yes, lean towards |
|---|---|
| Data has clear relationships, and you need joins, constraints and transactions (orders, payments, bookings)? | PostgreSQL (relational) |
| Records vary a lot in shape, or are naturally nested and read as a whole? | MongoDB |
| Need very fast reads of data you can recompute, expiry, counters, sessions? | Redis alongside your main database |
| Huge scale, simple access by key, and you want AWS to run it? | DynamoDB |
| Need graph traversals (who knows whom)? | A graph database such as Neo4j |
A very common real design uses several together: PostgreSQL for the source of truth (orders, users), Redis to cache the menu and store sessions, and sometimes a document store for logs or flexible content. Using more than one database for different jobs is normal, and it is called polyglot persistence. Do not add one just to look modern: every extra database is one more thing to run, secure, back up and learn.
Common misconceptions
| Myth | Reality |
|---|---|
| NoSQL is faster than SQL | Depends on the workload. A well-indexed PostgreSQL table is fast. NoSQL wins when its model matches your access pattern, or when you must spread data across many machines. |
| NoSQL means no schema | The schema moves into your application code. You still need rules for what a document looks like. |
| NoSQL can't do transactions | Some can (MongoDB and DynamoDB offer transactions, with limits). PostgreSQL's are simpler and more mature for multi-table work. |
| SQL does not scale | Relational databases scale a very long way with indexes, read replicas and caching. Most apps never outgrow them. |
How this comes up in interviews
Interviewers rarely want a product war. They want to see that you pick a database from the access pattern and data shape. A strong answer to "SQL or NoSQL for an e-commerce app?" names what needs transactions (orders, payments), what is flexible (product attributes), and what is just speed (cart, sessions in Redis), and admits that starting with PostgreSQL is a sensible default. Other likely questions: what is the CAP theorem (when the network splits, a distributed system must choose between consistency and availability), what is a TTL, and why use an index.
I am building [describe your app, e.g. a food-delivery app for a college canteen]. Its main data is [list entities] and its main queries are [list the 5 most common reads and writes]. Compare PostgreSQL, MongoDB, Redis and DynamoDB for it. Give a recommendation with reasons tied to my queries, say what I would store where, and name one risk of your recommendation.What to expect: A good answer ties each choice to your queries, picks a primary database, and uses Redis or similar only as a helper. Challenge any claim that sounds absolute.
Try it: Pick the store
For each need, choose PostgreSQL, MongoDB, Redis or DynamoDB and give one reason.
1. Store login sessions that expire after 30 minutes. 2. Store customers, orders, payments and refunds with strict consistency. 3. Store product pages where each category has different attributes (laptops have RAM, shirts have size). 4. A table that must answer "all orders by this phone number, newest first" for millions of customers on AWS.
Try it: Try Redis in 10 minutes
Run Redis locally (for example docker run -p 6379:6379 redis if you have Docker) and open redis-cli. Store a key with a 60-second expiry, watch TTL count down, then run GET after it expires. Then use INCR twice and HSET to make a small hash.
Key takeaways
- NoSQL is a family of designs (document, key-value, wide-column, graph), not one technology.
- MongoDB stores flexible JSON-like documents; embed data that is read together, but avoid unbounded embedding.
- Redis keeps data in memory for speed and expiry; it usually sits beside your main database as a cache or session store.
- DynamoDB is managed by AWS and fast when you read by key; design the table around your queries, and avoid scans.
- Choose by data shape and access pattern. PostgreSQL is a sensible default; add others for specific jobs.
Check yourself
Finishing the quiz marks the lesson as done.
1. A Brew & Bean order has nested items that are always read together with the order. Which feature of a document database helps most?
2. Why is Redis a poor choice as the only store for payment records?
3. In DynamoDB, what should you design first?
4. Which statement about 'schemaless' databases is most accurate?
5. An interviewer asks: SQL or NoSQL for an e-commerce site? Which answer is strongest?
Saved on this device. Create a free account to keep it on every device.
Practise this with Sam
A real mock interview, out loud, with an honest scorecard. Free to start.