NoSQL

Definition

  • NoSQL = “Not Only SQL”
  • Stores data not in tables, but in flexible formats
  • Designed for:
    • Big data
    • High traffic systems
    • Flexible / changing data
  • Key models:
    • Key-value
    • Documents
    • Wide-column
    • Graph

Problems with SQL (RDBMS)

  • Fixed schema → inflexible
  • Hard to scale (vertical scaling only)
  • Poor for:
    • Big data
    • Unstructured data

NoSQL Fixes

  • Horizontal scaling (add more servers)
  • Schema-less (dynamic structure)
  • Handles structured + semi-structured + unstructured data

When to use NoSQL vs SQL

Use SQL when:

  • Strong consistency needed
  • Structured data
  • Transactions (banking, payments)

Use NoSQL when:

  • Large-scale apps
  • Changing data structure
  • Real-time / high traffic systems
  • Content-heavy apps (images, JSON, etc.)

MongoDB Data Model

MongoDBSQL Equivalent
DatabaseDatabase
CollectionTable
DocumentRow
FieldColumn
  • Documents are JSON-like
  • Can have:
    • Nested data (embedded documents)
    • Arrays

CRUD Operations

Create

db.coll.insert_one({...})
db.coll.insert_many([{...}, {...}])

Read (Query)

db.coll.find({})
db.coll.find({"name":"Ken"})

With operators:

$eq, $gt, $lt, $in, $ne

Logical:

$and, $or

Projection:

db.coll.find(query, {"field":1})

Extra:

.limit(n)
.sort()

Update

db.coll.update_one(filter, {$set: {...}}, upsert=true)
db.coll.update_many(...)

Operators:

  • $set → change value
  • $inc → increment
  • $unset → remove field

Delete

db.coll.delete_one(filter)
db.coll.delete_many(filter)

Advanced Structures

Embedded document

{
 "name": {
   "given": "John",
   "family": "Tan"
 }
}

Query:

db.coll.find({"name.given": "John"})

Arrays

"subjects": ["GP", "CP", "MA"]

Query:

{"subjects": "CP"}
{“subjects”: [“CP”]}
{"subjects": {$in: ["CP","PH"]}}

Array of embedded docs

"vaccination": [
    {"type":"RNA", "manufacturer":"Moderna"}
]

Query:

{"vaccination.manufacturer":"Moderna"}

PyMongo

Script

import pymongo
client = pymongo.MongoClient("localhost", 27017)
 
db = client["mydatabase"]
coll = db["customers"]
 
coll.find({})
coll.insert_one({...})

Server

>> C:\mongodb\bin\mongod.exe
...
2026-03-18T12:28:15.573+0800 I NETWORK  [thread1] waiting for connections on port 27017