Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Working with Flexible Document-Oriented Data from Python

Notebook Guide

This lesson uses a Python document simulation to explain NoSQL thinking without requiring an external server.

Learning objectives

  • understand document-style storage

  • compare flexible documents with fixed relational schemas

  • perform insert and filter logic conceptually

  • connect Python dictionary structures to NoSQL ideas

Guided Example

Real NoSQL systems such as MongoDB and Firebase store flexible records that may not all share exactly the same fields. The example below simulates that document-oriented style in plain Python.

collection = [
    {"_id": 1, "customer": "Asha", "sales": 1200, "region": "West"},
    {"_id": 2, "customer": "Rahul", "sales": 900},
]

new_document = {"customer": "Mina", "sales": 1500, "region": "South", "vip": True}
next_id = max(document["_id"] for document in collection) + 1
new_document["_id"] = next_id
collection.append(new_document)

high_sales = [document for document in collection if document.get("sales", 0) >= 1000]
print("Collection:")
for document in collection:
    print(document)

print("\nHigh-sales documents:")
for document in high_sales:
    print(document)
Collection:
{'_id': 1, 'customer': 'Asha', 'sales': 1200, 'region': 'West'}
{'_id': 2, 'customer': 'Rahul', 'sales': 900}
{'customer': 'Mina', 'sales': 1500, 'region': 'South', 'vip': True, '_id': 3}

High-sales documents:
{'_id': 1, 'customer': 'Asha', 'sales': 1200, 'region': 'West'}
{'customer': 'Mina', 'sales': 1500, 'region': 'South', 'vip': True, '_id': 3}

Exercises

Exercise

Simulate inserting a document: write insert_document(collection, doc) which assigns a unique _id and appends the doc to the collection (a list). Return the inserted document.


Wrap-Up

NoSQL systems are useful when structure varies, documents evolve quickly, or nested records feel more natural than fixed tables. The trade-off is that consistency and analytical joins often require more deliberate design.

8. Interactive Code

Expected output
{'customer': 'Asha', 'sales': 1200}
Expected output
[{'customer': 'Rahul', 'sales': 1600}]

9. Guided Practice

What is a common idea behind many NoSQL document stores?

Every record must look exactly like a SQL row alwaysDocument models are often more flexible.
Data can be stored as flexible document-like structuresCorrect. Document-oriented storage is common in NoSQL systems.
NoSQL means no data structure at allNoSQL systems still structure data, just differently.
It can only store imagesThat is not the defining idea.

Which document is selected in the second example?

Asha's documentAsha's sales do not exceed 1300.
Rahul's documentCorrect. Rahul has sales of 1600.
Both documentsOnly one satisfies the filter.
No documentRahul's document meets the condition.