Model for your queries
Relational design starts from the data; NoSQL design starts from the queries. Explain the access pattern first, then the database and schema that fit it — and what you give up.
- ChoosingSQL vs NoSQL and the four NoSQL families.
- MongoDBSchema design, aggregation and indexes.
- ScalingCAP, replication and sharding.
Most companies run both relational and NoSQL databases, so interviewers ask when you would choose each. The best answers are about access patterns and consistency needs, not hype. MongoDB examples below use the mongosh syntax.
1. SQL vs NoSQL — how do you choose?
Choose SQL when data is relational, you need joins, strong consistency and multi-row transactions — orders, payments, inventory. Choose NoSQL when the shape varies, you read whole documents by key, or you need easy horizontal scaling — catalogues, user activity, sessions, IoT events. Many systems use both.
2. What are the main types of NoSQL databases?
- Document (MongoDB, Firestore): JSON-like documents.
- Key-value (Redis, DynamoDB): fastest lookups by key; caches and sessions.
- Wide-column (Cassandra): huge write volumes, time series.
- Graph (Neo4j): relationships first — social networks, recommendations.
3. Explain the CAP theorem.
When a network partition happens in a distributed database, you must choose between consistency (every read sees the latest write, or errors) and availability (every request gets an answer, possibly stale). Since partitions will happen, the real choice is CP or AP. PACELC adds: even without partitions, you trade latency for consistency.
4. Embed or reference — how do you design a MongoDB schema?
Design for how the data is read. Embed data that is read together and bounded in size (an order and its line items). Reference data that is shared, large or grows without limit (a user's millions of activity events). A single document has a 16 MB limit.
// Embedded: one read returns the whole order
db.orders.insertOne({
_id: 1001, customerId: 7, status: "PAID",
items: [ { sku: "PEN-01", qty: 2, price: 40 }, { sku: "NB-05", qty: 1, price: 120 } ]
});5. Write an aggregation pipeline: revenue by city for paid orders.
The pipeline is a list of stages, each transforming the stream of documents — similar to WHERE → GROUP BY → ORDER BY in SQL.
db.orders.aggregate([
{ $match: { status: "PAID" } },
{ $unwind: "$items" },
{ $group: { _id: "$city", revenue: { $sum: { $multiply: ["$items.qty", "$items.price"] } } } },
{ $sort: { revenue: -1 } },
{ $limit: 5 }
]);6. How do indexes work in MongoDB?
Like relational databases, MongoDB uses B-tree indexes, including compound indexes (the ESR rule: Equality, Sort, Range for field order), multikey indexes on arrays, text and geospatial indexes, and TTL indexes that delete old documents automatically. Check usage with explain("executionStats").
db.orders.createIndex({ customerId: 1, createdAt: -1 });
db.sessions.createIndex({ lastSeen: 1 }, { expireAfterSeconds: 3600 }); // TTL7. Replication vs sharding?
Replication copies the same data to several nodes (a replica set) for high availability and read scaling; if the primary fails, a secondary is elected. Sharding splits data across nodes by a shard key so each holds part of it, for write and storage scaling. Production clusters use both. A bad shard key (low cardinality or always increasing) creates hot spots.
8. Does MongoDB support transactions?
Yes. Single-document operations have always been atomic, and multi-document ACID transactions exist since MongoDB 4.0 (4.2 for sharded clusters). They cost more than single-document writes, so a good schema keeps most updates within one document.
Remember
Key points
- Embed what you read together
Reference what grows without limit.
- CAP is about partitions
Choose consistency or availability when the network splits.
- ESR rule for indexes
Equality, then Sort, then Range fields.
- Shard key is permanent-ish
Pick high cardinality and even distribution.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 What is eventual consistency? Basic
Replicas may briefly disagree, but if no new writes happen they converge to the same value. Fine for likes counters; not for bank balances.
-
2 How would you model a many-to-many relationship in MongoDB? Intermediate
Store arrays of references on one or both sides (students → courseIds) if bounded; otherwise use a separate collection of link documents.
-
3 What is $lookup and when should you avoid it? Intermediate
It is a left outer join between collections in an aggregation. Heavy use usually means the data is relational and might belong in SQL or need a different schema.
-
4 How does Redis persist data if it is in memory? Advanced
With RDB snapshots at intervals, an append-only file (AOF) of every write, or both. Many teams use Redis only as a cache and accept losing it.
-
5 What makes a bad shard key? Advanced
Low cardinality (country) or monotonically increasing values (timestamps, auto ids), which send all new writes to one shard. Hashed or compound keys spread load.