Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

NoSQL data models

Clear, exam-focused notes on NoSQL data models: definitions, types (key-value, document, wide-column, graph, time-series), modeling rules, when to choose each, examples and typical exam questions.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

NoSQL data models give engineers flexible ways to store and query data that do not fit the strict table-based relational model. Engineers choose a NoSQL model to get scalability, high write/read throughput, flexible schemas, or to represent connected data naturally (for example in web services, logging systems, IoT, and social networks).

Key ideas

Start with simple definitions and build up.

  • NoSQL database — a database system that does not require a fixed relational schema (tables with fixed columns) and often trades some relational features (strict ACID transactions, joins) for horizontal scalability, flexible data models, and simpler distribution. Assume a single logical cluster (may be distributed across nodes).

  • Schema-less — a common phrase meaning records (documents, key-value values, rows) need not share an identical set of fields; the system does not enforce a fixed schema at the server. Note: schema-less does not mean application has no schema; application-level structure is still needed.

  • Eventual consistency — a consistency model where, if no new updates are made, all replicas will converge to the same value after some (unspecified) time. It is weaker than strong consistency (linearizability). Assumption: system has replicas and asynchronous replication.

  • BASE — an informal contrast to ACID: Basically Available, Soft state, Eventual consistency. Use when high availability under partition is critical (see CAP theorem). Refer to the CAP theorem for trade-offs.

  • CAP theorem (reference only) — in a distributed system you can have at most two of: Consistency (all nodes see same data at same time), Availability (every request receives a response), Partition tolerance (system continues to operate despite message loss between nodes). We only mention it here as a guideline when choosing NoSQL systems; details appear elsewhere in the course.

Main NoSQL data models (define each and show how to draw or represent it):

  1. Key–value store — a simple model where each record is a pair (key, value) and the only operations are get, put, delete by key. Values are opaque blobs to the store (could be strings, binary, JSON). Draw: a vertical list of boxes; left column label "Key" with unique keys, right column label "Value" containing blob. Use when you need very fast lookup by key and simple updates. Assumes application organizes values. Systems: Redis, Riak.

  2. Document store — each record is a document (usually JSON, BSON) containing named fields that can be nested and can vary between documents. The database understands document structure (can index fields). Draw: a series of boxes representing documents; inside each put field-name: value pairs, nesting boxes for arrays/objects. Use when you have hierarchical data and want query-by-field without strict schema. Systems: MongoDB, Couchbase.

  3. Wide-column (column-family) store — data model has rows identified by a row key; each row contains column families, and each column family contains many columns. Columns can be added per row. Draw: table with first column "RowKey" and other columns grouped by vertical braces into "FamilyA", "FamilyB"; within each family list column qualifiers and values per row. Systems: Cassandra, HBase. Good for time-series, logs, and denormalized wide rows.

  4. Graph database — stores nodes (entities), relationships (edges) and properties on both. Query languages (e.g., Cypher) traverse relationships efficiently. Draw: circles for nodes labeled with type and property list; arrows between nodes labeled with relationship type and properties. Use for social graphs, recommendations, and any data with many relationships. Systems: Neo4j, JanusGraph.

  5. Time-series / specialized stores — optimized for append-only time-stamped measurements (metrics, sensor data). They provide efficient compression and queries over time windows. Draw: a timeline with points, label series key and value. Use when you store frequent metric samples. Systems: InfluxDB, TimescaleDB, OpenTSDB.

Important modeling principles and exact steps universities expect when mapping relational designs to NoSQL:

  • When converting a relational schema to a document model: identify the main access patterns (queries). For each frequent query, embed related data if it will be read together and size remains bounded; otherwise reference by id. Step-by-step:

    1. Choose a document type that corresponds to a main access pattern (e.g., "Order document" if most queries fetch order with items).
    2. For 1-to-many small, bounded relationships, embed (place array of child objects inside parent document).
    3. For many-to-many or unbounded growth, reference (store ids) and fetch separately or via application-side join.
    4. Add indexes on fields used in filters/sorts.
  • When converting to a wide-column model: choose the row key to support primary access (e.g., customerId), place frequently-read dynamic attributes into column families, and use time as column qualifier for series. Denormalize aggressively.

  • For graph modeling: nodes represent entity types you will traverse; relationships represent frequent navigations. Avoid encoding traversals as joins in other models — use graph if traversals of variable depth are common.

Draw diagrams universities ask for: for a document model draw a sample JSON document and annotate which fields you embed vs reference. For a wide-column draw a table showing row keys and a variable number of columns per row (show missing entries as blank). For graph draw nodes and labeled edges with property lists.

Assumptions to state in answers: workload (read-heavy vs write-heavy), data size and growth rate, latency needs, consistency needs (strong vs eventual), operation patterns (point reads vs graph traversals).

Formulas

(No numeric formulas apply; instead list useful syntax patterns to remember.)

db.collection.insertOne(document) — MongoDB insert a document. document: JSON/BSON object. Use in document stores.

db.collection.find(query, projection) — MongoDB find; query is a filter object, projection selects fields. Returns cursor of documents.

CREATE TABLE keyspace.table (pk TYPE PRIMARY KEY, col1 TYPE, col2 TYPE, ...) — Cassandra CQL table create. pk: primary key (may include partition key and clustering columns).

INSERT INTO keyspace.table (pk, col1, col2) VALUES (vpk, v1, v2) — CQL insert; values follow types.

CREATE (n:Label {prop1:value1, prop2:value2}) — Neo4j Cypher create node with label and properties.

MATCH (a:Person)-[:FRIEND]->(b:Person) WHERE a.name='X' RETURN b — Cypher pattern match returning neighbors.

For each syntax line: symbols represent command/clauses; types and values depend on database; these apply when using the named database engines or compatible APIs.

Worked examples

(1) Model answer: Design a document model for an Order system (university long-question style)

Question: Given relational tables ORDERS(orderId, custId, orderDate), ORDER_ITEMS(orderId, itemId, qty, price), CUSTOMERS(custId, name, address), design a document model optimized for fetching an order with its items.

Model answer (step-by-step):

  1. Access pattern: fetch an order with its items and customer name for display.
  2. Choose main document: Order document. Embed items because an order's items are bounded per order.
  3. Structure (example document): { "orderId": "O1001", "custId": "C200", "custName": "Anita Rao", "orderDate": "2026-03-01T10:00:00Z", "items": [ {"itemId":"I10","qty":2,"price":199.0}, {"itemId":"I25","qty":1,"price":499.0} ], "status": "shipped" }
  4. Explain choices: we embedded items to avoid join between ORDERS and ORDER_ITEMS. We denormalized custName to avoid join to CUSTOMERS for display; if customer details change often, store reference custId and fetch separately or update documents via background job.
  5. Indexes: index on orderId (unique) and on custId if queries fetch orders by customer.

(2) Short practical model-answer: Graph query example (Neo4j-style)

Task: Represent users and "follows" relationships and find friends-of-friends for user 'A' excluding direct friends.

Data creation (conceptual Cypher): CREATE (a:User {name:'A'}), (b:User {name:'B'}), (c:User {name:'C'}), (d:User {name:'D'}); CREATE (a)-[:FOLLOWS]->(b), (b)-[:FOLLOWS]->(c), (a)-[:FOLLOWS]->(d), (d)-[:FOLLOWS]->(c);

Query to find friends-of-friends: MATCH (a:User {name:'A'})-[:FOLLOWS]->(:User)-[:FOLLOWS]->(fof) WHERE NOT (a)-[:FOLLOWS]->(fof) AND fof.name <> 'A' RETURN DISTINCT fof.name;

Expected result (model answer form): A single-column result with name 'C' (because both B and D follow C, and C is not directly followed by A). Explain why: C reachable at distance 2, and A does not directly follow C.

(3) Short comparative model answer (exam-style)

Question: When would you choose a wide-column store over a document store?

Answer structure (full marks): state workload (very large rows per key or time-series per key), need for efficient writes of many columns, predictable query patterns by row key and range scans on clustering columns; mention that wide-column better when you need per-row dynamic columns and extremely high write throughput; document store better when you need richer nested queries and ad-hoc querying on fields. Mention consistency and secondary index limitations. End with example: IoT sensor data per device -> wide-column; product catalog with nested specs -> document.

Common mistakes

  • Treating column-family stores like relational tables (expecting joins and ad-hoc queries across unrelated keys).
  • Choosing graph DB for small datasets with no graph traversals — unnecessary complexity.
  • Ignoring access patterns when designing: NoSQL modeling is query-driven, not normalization-driven.
  • Forgetting to state assumptions (workload, consistency needs) in exam answers.

For your exam

Types of questions you will see and what full-marks answers include:

  • Definitions and short notes (e.g., define document store) — give concise definition, one example system, and typical use-case.
  • Compare-and-contrast (e.g., document vs wide-column) — list differences in schema, access patterns, strengths and weaknesses, and give an example scenario for each.
  • Derivations / design steps (mapping relational to document) — show step-by-step conversion and justify embedding vs referencing with access-pattern assumptions.
  • Diagram questions — draw a sample document JSON or wide-column table; label row key, column family, and show an example node-edge graph with properties.
  • Practical queries / syntax recall — write a short MongoDB or CQL or Cypher snippet; state which fields are indexed and why.

Full-marks answers always: define terms, state assumptions about workload and consistency, show concrete example or diagram, and justify design decisions.

Quick check

  1. Define a key–value store in one sentence.
  2. When should you embed related objects inside a document? Give one rule.
  3. What is the primary modelling advantage of a graph database?

Answers: 1) A key–value store is a database where data is stored as pairs (key, value) and basic operations are get/put/delete by key. 2) Embed when the related objects are read together frequently and the child set size is bounded. 3) Graph databases make traversals and queries over relationships fast and natural (variable-depth navigation is efficient).

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?