Knowledge / Computer Science and Engineering / NoSQL databases

NoSQL databases

Computer Science and Engineering (B.E./B.Tech) · Databases · free study notes for exams, placements and interviews

In short

NoSQL ("not only SQL") databases store data in models other than the relational table - documents, key-value pairs, wide-column families and graphs - and are designed to scale out across many commodity servers rather than up on one large machine. They trade some of SQL's strict schema and ACID guarantees for horizontal scalability, flexible schemas and high availability, as summarised by the CAP theorem and the BASE model. In Indian university syllabi NoSQL appears as the last unit of the DBMS course and as a full elective (Big Data / Advanced Databases); GATE CS asks little of it directly, but placement technical rounds at Flipkart, Swiggy, Zomato, Paytm, PhonePe, Jio, Razorpay, TCS, Infosys and Wipro ask it constantly. Typical questions are CAP, SQL-versus-NoSQL choice, MongoDB query syntax, sharding keys and when NOT to use NoSQL. Data engineers, backend developers and SRE roles use these systems daily behind UPI, e-commerce catalogues and ride-hailing apps.

Explained

Why NoSQL appeared, and what "NoSQL" means

The four families (classification - asked almost every exam)

  1. Key-value stores - a hash map: put(key, value), get(key), delete(key). Value is opaque (blob/string). Fastest and simplest; no querying inside the value.
    • Examples: Redis (in-memory, data structures: strings, lists, sets, sorted sets, hashes, streams), Amazon DynamoDB, Riak, Memcached (cache only, no persistence).
    • Uses: session store, cache, leaderboards, rate limiting, OTP store, shopping cart.
  2. Document stores - value is a self-describing document (JSON / BSON / XML) that the database can index and query by inner fields; documents may nest arrays and sub-documents.
    • Examples: MongoDB, CouchDB, Couchbase, Elasticsearch (document + inverted-index search), Firestore.
    • Uses: product catalogues, user profiles, CMS, event logs, order documents.
  3. Column-family / wide-column stores - rows keyed by a row key; columns grouped into column families; each row can have different columns; data stored column-family-wise on disk, so scans read only needed columns.
    • Examples: Apache Cassandra, HBase (on HDFS), Google Bigtable, ScyllaDB.
    • Uses: time-series and IoT telemetry, messaging history, write-heavy event logging, recommendation features.
  4. Graph databases - nodes, edges (directed, typed, with properties) and properties; traversal is a pointer hop, not a join.
    • Examples: Neo4j (Cypher query language), JanusGraph, Amazon Neptune, ArangoDB (multi-model).
    • Uses: social graphs, fraud rings, recommendation ("friends of friends"), network/telecom topology, knowledge graphs.
  5. Often listed as a fifth family: time-series databases (InfluxDB, TimescaleDB, Prometheus) and search engines; both are specialisations of the above.

CAP theorem, PACELC and BASE

Distribution: sharding, replication and quorum

Data modelling for NoSQL (query-first design)

Advantages, limitations and the NewSQL middle ground

Key points

Formulas and examples

Quorum consistency condition: R + W > N — N = replication factor, R = replicas read, W = replicas acknowledging a write (counts, dimensionless)
Cassandra QUORUM = ⌊N/2⌋ + 1 replicas
Fault tolerance of a quorum cluster: nodes that may fail = N − max(R, W)
Consistent hashing: expected keys moved when one node joins/leaves ≈ K / N (K = total keys, N = nodes)
Partition ownership: node = first node clockwise from hash(key) mod 2m on an m-bit ring
Storage required = (data size) × (replication factor) × (1 − compression savings), then ÷ target disk utilisation
Availability of a partition with RF replicas, each with independent uptime p: A = 1 − (1 − p)RF

Example 1 - Tunable consistency in Cassandra. A cluster has RF N = 3.

Example 2 - Capacity and node count for an IoT meter workload. A Bengaluru utility ingests readings from 2,00,000 smart meters, one reading every 15 minutes, each row 200 bytes, RF = 3, retention 2 years.

Example 3 - Consistent hashing vs modulo hashing. K = 10,00,000 keys on N = 10 nodes; one node is added.

Example 4 - Document model for an Indian e-commerce order (MongoDB).

// orders collection - one document per order (embed line items: bounded, always read together)
{ _id: ObjectId("..."),
  orderNo: "ABL-2026-004821",
  userId: ObjectId("..."),            // reference: user profile updated independently
  placedAt: ISODate("2026-10-29T10:12:00Z"),
  status: "PACKED",
  payment: { mode: "UPI", vpa: "9xxxxxxxxx@ybl", amount: 2499, currency: "INR" },
  shipTo:  { line1: "Flat 4B, Rose Apt", city: "Kochi", state: "Kerala",
             pin: "682024", geo: { type: "Point", coordinates: [76.30, 9.96] } },
  items: [ { sku: "TSH-RED-M", name: "Cotton T-shirt", qty: 2, price: 699, gstPct: 5 },
           { sku: "SHO-BLK-9", name: "Running shoes", qty: 1, price: 1101, gstPct: 5 } ]
}

db.orders.createIndex({ userId: 1, placedAt: -1 })      // "my orders, newest first"
db.orders.createIndex({ "items.sku": 1 })               // multikey index on an array
db.orders.find({ userId: uid, status: { $in: ["PACKED","SHIPPED"] } })
         .sort({ placedAt: -1 }).limit(20)

// revenue per city for October 2026 (aggregation pipeline)
db.orders.aggregate([
  { $match: { placedAt: { $gte: ISODate("2026-10-01"), $lt: ISODate("2026-11-01") } } },
  { $unwind: "$items" },
  { $group: { _id: "$shipTo.city",
              revenue: { $sum: { $multiply: ["$items.price", "$items.qty"] } } } },
  { $sort: { revenue: -1 } } ])

Example 5 - Same requirement, three models. "Show a user's last 20 orders."

ModelDesignRead cost
Relational (3NF)orders JOIN order_items JOIN users, index on (user_id, placed_at)2 joins, index scan - fine on one server, costly if sharded
Document (MongoDB)one order document with items embedded; index (userId, placedAt)1 index range read, 20 documents, no join
Column-family (Cassandra)orders_by_user(user_id PK, placed_at DESC, order_no, …)1 partition read, rows already sorted; needs a second table for "order by order_no"

Comparison table - SQL vs NoSQL

AspectRelational (SQL)NoSQL
Data modelTables, rows, fixed columnsDocuments, key-value, column families, graphs
SchemaSchema-on-write, enforced by engineSchema-on-read, enforced by application
ScalingMainly vertical; sharding is add-onHorizontal by design
TransactionsFull ACID across rows and tablesAtomic per aggregate; multi-document support growing
JoinsNative, optimiser-drivenAvoided; denormalise or join in application
Query languageStandard SQL (ISO)Per-product (CQL, MQL, Cypher, Gremlin)
ConsistencyStrongTunable: strong to eventual
Storage engineB+ treeUsually LSM tree
Best fitLedgers, ERP, reporting, OLTP with joinsCatalogues, sessions, feeds, telemetry, graphs

Comparison table - the four families

FamilyKey accessQuery inside valueTypical productsClassic use
Key-valueExact key onlyNoRedis, DynamoDB, RiakCache, sessions, OTP, carts
DocumentKey + field queries + indexesYesMongoDB, Couchbase, ElasticsearchCatalogue, profiles, orders
Column-familyPartition key + clusteringLimited (by key design)Cassandra, HBase, ScyllaDBTime series, messages, logs
GraphNode lookup then traversalPattern matchingNeo4j, Neptune, JanusGraphSocial, fraud, recommendations

Where it is used

Interview questions

Common mistakes

Related topics

Transactions, ACID and indexing · ER model and normalisation · Query processing and optimisation · Database design case studies · Distributed systems and consensus (Paxos, Raft) · Big data processing with Hadoop and Spark

Open in the Knowledge reader →Find jobs →