Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 20 min · revision 2

Lab: Flattening Nested Documents for Analytics

Export ride-hailing trips from MongoDB to Parquet with explicit PyArrow schemas: flatten nested fields, explode an embedded array into a child table, cast known type drift and quarantine the rest, keep missing, null and false apart, then prove the result with DuckDB.

Contentsand lesson path

What you will learn

  • Extract documents into an analytical format, flattening nested fields and handling missing or drifting attributes explicitly.

01. Goal and setup

Operational documents are shaped for the app, not for analysis. Analysts want flat tables with one type per column, where SUM(fare_total) just works. Between the two sits an export job, and most of its bugs are silent: a column whose type depends on which batch came first, an array squeezed into a string, a missing field quietly turned into false.

In this lab you export 1,000 trip documents from MongoDB into three Parquet files: trips (one row per trip, nested fields flattened into columns), trip_stops (one row per element of the embedded stops array) and quarantine (documents the export refused, with the reason). Parquet is a columnar file format that stores a typed schema with the data. You then read the files with DuckDB, an in-process SQL engine, to prove that nothing was lost or changed.

You need: Docker with mongo:7, Python 3.12, PyMongo, PyArrow and DuckDB. Tested with MongoDB 7.0, PyMongo 4.20, PyArrow 26.0 and DuckDB 1.5.3. Scripts read MONGO_URL, defaulting to mongodb://localhost:27017; reuse the container from lesson 4 if it is still running.

Project layout at the end of the lab
flatten-lab/
├── seed_trips.py       step 1: 1,000 trip documents with drift
├── profile_source.py   step 2: what the source really contains
├── why_schema.py       step 3: inferred against declared types
├── export.py           step 4: MongoDB -> three Parquet files
├── reconcile.py        step 5: prove nothing was lost
├── analyse.py          step 6: query the flat tables
└── out/                trips, trip_stops and quarantine .parquet
Terminal · setup
docker run -d --name nosql-mongo -p 27017:27017 mongo:7
mkdir flatten-lab && cd flatten-lab
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install pymongo==4.20.0 pyarrow==26.0.1 duckdb==1.5.3

02. Step 1: Seed trips that drifted over time

The seed imitates three years of app releases. fare.total was written as a double by the current app, as an int by a version that rounded, as a string by the first app and as a decimal by a billing backfill; a few documents hold values nobody can safely convert. The first 300 trips predate two features, so they have no stops array and no shared_ride field. Later trips have 0 to 3 stops, and shared_ride is true, false or, when the app could not tell, null. rider.tier is present on about 70% of trips.

Python · seed_trips.py
"""Load 1,000 trip documents with realistic drift into MongoDB (seeded)."""
import os
import random
from datetime import datetime, timedelta, timezone

from bson.decimal128 import Decimal128
from pymongo import MongoClient

rng = random.Random(5)
coll = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))[
    "export_lab"]["trips"]
coll.drop()
START = datetime(2026, 11, 2, tzinfo=timezone.utc)


def fare_total(amount: float):
    """How different app versions and services have written fare.total."""
    roll = rng.random()
    if roll < 0.80:
        return amount                       # double (current app)
    if roll < 0.88:
        return int(amount)                  # int (a version that rounded down)
    if roll < 0.95:
        return f"{amount:.2f}"              # numeric string (app v1)
    if roll < 0.98:
        return Decimal128(f"{amount:.2f}")  # decimal (billing backfill)
    return rng.choice(["N/A", "12,50"])    # values nobody can safely convert


docs = []
for n in range(1, 1001):
    doc = {
        "_id": f"T{n:05d}",
        "rider": {"id": f"R{rng.randint(1, 200):04d}"},
        "requested_at": START + timedelta(minutes=10 * n),
        "pickup": {"city": rng.choice(["London", "Leeds", "Bristol"])},
        "fare": {"currency": "GBP", "total": fare_total(round(rng.uniform(6, 40), 2))},
    }
    if rng.random() < 0.7:
        doc["rider"]["tier"] = rng.choice(["standard", "plus"])
    if n > 300:  # trips before n=300 predate multi-stop and shared rides
        doc["stops"] = [{"address": f"{rng.randint(1, 99)} High Street",
                         "wait_s": rng.choice([0, 30, 60, 120])}
                        for _ in range(rng.choice([0, 0, 1, 1, 2, 3]))]
        roll = rng.random()
        doc["shared_ride"] = None if roll < 0.05 else roll < 0.35
    docs.append(doc)
coll.insert_many(docs)
print("documents:", coll.count_documents({}))
Terminal
python seed_trips.py
Expected output
documents: 1000

03. Step 2: Profile the source before designing the target

Do not design an export from one sample document. Ask the database what each field really holds. The aggregation operator $type returns the BSON type of a value, and the string missing when the field is absent:

Python · profile_source.py
"""Profile the source before designing the target schema."""
import os

from pymongo import MongoClient

coll = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))[
    "export_lab"]["trips"]


def census(expr) -> list:
    pipeline = [{"$group": {"_id": expr, "n": {"$sum": 1}}}, {"$sort": {"_id": 1}}]
    return [(row["_id"], row["n"]) for row in coll.aggregate(pipeline)]


print("fare.total types:", census({"$type": "$fare.total"}))
TYPE = {"$type": "$shared_ride"}
print("shared_ride:", census({"$switch": {"branches": [
    {"case": {"$eq": [TYPE, "missing"]}, "then": "missing"},
    {"case": {"$eq": [TYPE, "null"]}, "then": "null"}],
    "default": {"$toString": "$shared_ride"}}}))
print("{shared_ride: null} matches:", coll.count_documents({"shared_ride": None}))
print("stops:", census({"$cond": [{"$isArray": "$stops"},
                                  {"$size": "$stops"}, "missing"]}))
Terminal
python profile_source.py
Expected output
fare.total types: [('decimal', 26), ('double', 824), ('int', 75), ('string', 75)]
shared_ride: [('false', 458), ('missing', 300), ('null', 36), ('true', 206)]
{shared_ride: null} matches: 336
stops: [(0, 217), (1, 237), (2, 129), (3, 117), ('missing', 300)]

fare.total has four types. shared_ride has four states, and they mean different things: missing means the trip predates the feature, so nobody was asked; null means the app did not know; false means a solo ride. Merge them and you change the answer to what share of riders chose not to share?

The third line shows how easily they merge. In MongoDB, the filter {shared_ride: null} matches documents where the field is null or missing, so it returns 336, not 36. To find only explicit nulls, filter on the type ({"$type": "null"}); to find only absent fields, use {"$exists": false}. stops has the same split: an empty array (217 trips with no stops) is not the same as no array at all (300 trips from before the feature).

04. Step 3: See why the schema must be declared

If you hand PyArrow a list of dictionaries without a schema, it infers one from the values it sees. Run that on two batches of the same field:

Python · why_schema.py
"""Why the export declares its schema instead of letting PyArrow infer it."""
from decimal import Decimal

import pyarrow as pa

batch_1 = [{"fare_total": 18.4}, {"fare_total": 12}]
batch_2 = [{"fare_total": "18.40"}, {"fare_total": "N/A"}]
for name, batch in (("batch 1", batch_1), ("batch 2", batch_2)):
    print(f"inferred from {name}:", pa.Table.from_pylist(batch).schema.types[0])

TARGET = pa.schema([pa.field("fare_total", pa.decimal128(9, 2))])
for name, batch in (("batch 1", batch_1), ("batch 2", batch_2)):
    try:
        pa.Table.from_pylist(batch, schema=TARGET)
        print(f"explicit schema, {name}: accepted")
    except (pa.ArrowInvalid, pa.ArrowTypeError) as err:
        print(f"explicit schema, {name}: refused ({type(err).__name__})")
ok = pa.Table.from_pylist([{"fare_total": Decimal("18.40")}], schema=TARGET)
print("after casting to Decimal:", ok.column(0).to_pylist())
Terminal
python why_schema.py
Expected output
inferred from batch 1: double
inferred from batch 2: string
explicit schema, batch 1: refused (ArrowTypeError)
explicit schema, batch 2: refused (ArrowTypeError)
after casting to Decimal: [Decimal('18.40')]

Inference made the same field a double in one file and a string in the next, depending on which documents happened to be in the batch. A reader combining those files now has to reconcile types, or fails. With a declared target schema, decimal128(9, 2) for money, PyArrow refused both raw batches: it will not guess how to turn a float or a string into a decimal. That refusal is what you want. It forces the export to convert each known variant on purpose, and to send anything else somewhere visible instead of into the analytics tables.

05. Step 4: Export with flattening, explosion, casts and quarantine

The export declares three schemas and builds rows that must fit them:

  • Flatten nested objects into prefixed columns: rider.id becomes rider_id, fare.currency becomes fare_currency.
  • Explode the stops array into the child table trip_stops, one row per element, keyed by trip_id and stop_no, the element's 1-based position. An array is a one-to-many relationship, so it gets its own table at its own grain and joins back to trips.
  • Cast the known variants of fare.total (double, int, numeric string, Decimal128) to an exact decimal with two places. Anything else raises ValueError, and the whole document goes to quarantine with its raw value and the reason.
  • Keep states apart. stop_count is null when stops is missing and 0 when it is empty. shared_ride keeps true, false and null, and shared_ride_present records whether the field existed at all.
Python · export.py
"""Export trips from MongoDB to three Parquet files with explicit schemas."""
import os
import re
from collections import Counter
from decimal import Decimal
from pathlib import Path

import pyarrow as pa
import pyarrow.parquet as pq
from bson.decimal128 import Decimal128
from pymongo import MongoClient

client = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"),
                     tz_aware=True)  # datetimes come back as UTC-aware values
coll = client["export_lab"]["trips"]

TRIPS = pa.schema([
    pa.field("trip_id", pa.string(), nullable=False),
    pa.field("rider_id", pa.string(), nullable=False),
    pa.field("rider_tier", pa.string()),            # null when the doc has no tier
    pa.field("city", pa.string(), nullable=False),
    pa.field("requested_at", pa.timestamp("ms", tz="UTC"), nullable=False),
    pa.field("fare_currency", pa.string(), nullable=False),
    pa.field("fare_total", pa.decimal128(9, 2), nullable=False),
    pa.field("stop_count", pa.int16()),             # null when stops is missing
    pa.field("shared_ride", pa.bool_()),            # null when missing OR null
    pa.field("shared_ride_present", pa.bool_(), nullable=False),
])
STOPS = pa.schema([
    pa.field("trip_id", pa.string(), nullable=False),
    pa.field("stop_no", pa.int16(), nullable=False),  # 1-based array position
    pa.field("address", pa.string()),
    pa.field("wait_s", pa.int32()),
])
QUARANTINE = pa.schema([
    pa.field("trip_id", pa.string(), nullable=False),
    pa.field("field", pa.string(), nullable=False),
    pa.field("raw_value", pa.string()),
    pa.field("reason", pa.string(), nullable=False),
])
CENTS = Decimal("0.01")
PLAIN_NUMBER = re.compile(r"\d+(\.\d{1,2})?")


def to_money(value) -> Decimal:
    """Cast the known variants of fare.total; raise ValueError for anything else."""
    if isinstance(value, bool):  # bool is a subclass of int in Python
        raise ValueError("boolean")
    if isinstance(value, (int, float)):
        return Decimal(str(value)).quantize(CENTS)
    if isinstance(value, Decimal128):
        return value.to_decimal().quantize(CENTS)
    if isinstance(value, str) and PLAIN_NUMBER.fullmatch(value):
        return Decimal(value)
    raise ValueError(f"unknown format ({type(value).__name__})")


trips, stops, quarantine = [], [], []
for doc in coll.find().sort("_id", 1):
    raw = doc.get("fare", {}).get("total")
    try:
        total = to_money(raw)
    except ValueError as err:
        quarantine.append({"trip_id": doc["_id"], "field": "fare.total",
                           "raw_value": repr(raw), "reason": str(err)})
        continue
    doc_stops = doc.get("stops")  # None when the field is missing
    trips.append({
        "trip_id": doc["_id"],
        "rider_id": doc["rider"]["id"],
        "rider_tier": doc["rider"].get("tier"),
        "city": doc["pickup"]["city"],
        "requested_at": doc["requested_at"],
        "fare_currency": doc["fare"]["currency"],
        "fare_total": total,
        "stop_count": None if doc_stops is None else len(doc_stops),
        "shared_ride": doc.get("shared_ride"),
        "shared_ride_present": "shared_ride" in doc,
    })
    for position, stop in enumerate(doc_stops or [], start=1):  # explode the array
        stops.append({"trip_id": doc["_id"], "stop_no": position,
                      "address": stop.get("address"), "wait_s": stop.get("wait_s")})

Path("out").mkdir(exist_ok=True)
for name, rows, schema in (("trips", trips, TRIPS), ("trip_stops", stops, STOPS),
                           ("quarantine", quarantine, QUARANTINE)):
    pq.write_table(pa.Table.from_pylist(rows, schema=schema), f"out/{name}.parquet")
    print(f"out/{name}.parquet: {len(rows)} rows")
print("quarantined:", sorted(Counter(q["raw_value"] for q in quarantine).items()))
Terminal
python export.py
Expected output
out/trips.parquet: 981 rows
out/trip_stops.parquet: 822 rows
out/quarantine.parquet: 19 rows
quarantined: [("'12,50'", 5), ("'N/A'", 14)]

Three details carry the design. isinstance(value, bool) is checked first because Python treats True as the integer 1, so a stray boolean would otherwise become a fare of 1.00. The regular expression accepts only plain numbers with up to two decimals, so 12,50, which could mean 12.50 or 1,250, is refused rather than guessed. And tz_aware=True makes PyMongo return UTC-aware datetimes, so the values written to the timestamp("ms", tz="UTC") column state their time zone instead of relying on how a library treats naive times. Casting fixes types, not history: the trips written by the rounding app version come out as whole pounds because that is what was stored.

06. Step 5: Reconcile the export against the source

An export is finished when you can prove it. DuckDB reads Parquet files directly in SQL, so the checks are short: every source document is either exported or quarantined; the child table has exactly one row per array element of the exported trips; the columns have the declared types; and each kind of fare.total came out as the same decimal value.

Python · reconcile.py
"""Reconcile the Parquet export against MongoDB, using DuckDB to read it."""
import os

import duckdb
from pymongo import MongoClient

src = MongoClient(os.environ.get("MONGO_URL", "mongodb://localhost:27017"))[
    "export_lab"]["trips"]
con = duckdb.connect()
for name in ("trips", "trip_stops", "quarantine"):
    con.execute(f"CREATE VIEW {name} AS SELECT * FROM 'out/{name}.parquet'")


def one(sql: str):
    return con.execute(sql).fetchone()[0]


# 1. Every source document is either exported or quarantined, never lost.
source = src.count_documents({})
exported = one("SELECT count(*) FROM trips")
held = one("SELECT count(*) FROM quarantine")
print(f"source {source} = exported {exported} + quarantined {held}:",
      source == exported + held)

held_ids = [r[0] for r in con.execute("SELECT trip_id FROM quarantine").fetchall()]
QUARANTINED = ("SELECT reason, raw_value, count(*) FROM quarantine "
               "GROUP BY ALL ORDER BY ALL")
for reason, raw, n in con.execute(QUARANTINED).fetchall():
    print(f"  quarantined: {raw:<7} {reason} x{n}")

# 2. The child table has one row per array element of the exported trips.
pipeline = [{"$match": {"_id": {"$nin": held_ids}}},
            {"$project": {"n": {"$size": {"$ifNull": ["$stops", []]}}}},
            {"$group": {"_id": None, "n": {"$sum": "$n"}}}]
elements = next(src.aggregate(pipeline))["n"]
stop_rows = one("SELECT count(*) FROM trip_stops")
print(f"stop elements {elements} = trip_stops rows {stop_rows}:", elements == stop_rows)

# 3. The schema is the declared one, not a guess.
for column, kind in con.execute(
        "SELECT column_name, column_type FROM (DESCRIBE trips) WHERE column_name "
        "IN ('requested_at', 'fare_total', 'stop_count', 'shared_ride')").fetchall():
    print(f"  {column:<13} {kind}")

# 4. Each known variant of fare.total was cast to the same decimal value.
for bson_type in ("double", "int", "string", "decimal"):
    doc = src.find_one({"fare.total": {"$type": bson_type}, "_id": {"$nin": held_ids}},
                       sort=[("_id", 1)])
    value = one(f"SELECT fare_total FROM trips WHERE trip_id = '{doc['_id']}'")
    print(f"  {doc['_id']} {bson_type:<8} {doc['fare']['total']!r:<22} -> {value}")
Terminal
python reconcile.py
Expected output
source 1000 = exported 981 + quarantined 19: True
  quarantined: '12,50' unknown format (str) x5
  quarantined: 'N/A'   unknown format (str) x14
stop elements 822 = trip_stops rows 822: True
  requested_at  TIMESTAMP WITH TIME ZONE
  fare_total    DECIMAL(9,2)
  stop_count    SMALLINT
  shared_ride   BOOLEAN
  T00001 double   31.22                  -> 31.22
  T00005 int      12                     -> 12.00
  T00016 string   '23.42'                -> 23.42
  T00063 decimal  Decimal128('29.43')    -> 29.43

07. Step 6: Query the flat tables

Now use the tables the way an analyst would: count the shared_ride states, compare missing and empty stops, then join the child table back to trips for revenue and stops per city.

Python · analyse.py
"""Query the flat tables with DuckDB, keeping missing, null and false apart."""
import duckdb

con = duckdb.connect()
for name in ("trips", "trip_stops"):
    con.execute(f"CREATE VIEW {name} AS SELECT * FROM 'out/{name}.parquet'")

# 1. Missing, null and false stay apart.
print("shared_ride:", con.execute("""
    SELECT CASE WHEN NOT shared_ride_present THEN 'missing'
                WHEN shared_ride IS NULL THEN 'null'
                ELSE shared_ride::VARCHAR END AS state, count(*)
    FROM trips GROUP BY state ORDER BY state""").fetchall())
print("stop_count missing / zero:", con.execute(
    "SELECT count(*) FILTER (stop_count IS NULL), count(*) FILTER (stop_count = 0) "
    "FROM trips").fetchone())
print("'not shared' if nulls are coalesced to false:",
      con.execute("SELECT count(*) FROM trips "
                  "WHERE NOT coalesce(shared_ride, false)").fetchone()[0])

# 2. An analyst query: revenue and stops per city, joining the child table.
for city, n, revenue, n_stops in con.execute("""
    SELECT t.city, count(*) AS trips, sum(t.fare_total) AS revenue,
           sum(coalesce(s.n, 0)) AS stops
    FROM trips t LEFT JOIN (SELECT trip_id, count(*) AS n FROM trip_stops
                            GROUP BY trip_id) s USING (trip_id)
    GROUP BY t.city ORDER BY t.city""").fetchall():
    print(f"  {city:<8} trips={n:<4} revenue={revenue:>8} stops={n_stops}")
Terminal
python analyse.py
Expected output
shared_ride: [('false', 447), ('missing', 294), ('null', 36), ('true', 204)]
stop_count missing / zero: (294, 215)
'not shared' if nulls are coalesced to false: 777
  Bristol  trips=344  revenue= 8112.88 stops=305
  Leeds    trips=326  revenue= 7555.85 stops=260
  London   trips=311  revenue= 6810.11 stops=257

The four states survive the export: 294 missing (6 of the 300 pre-feature trips were quarantined), 36 null, 447 false and 204 true. A query that coalesces null to false reports 777 trips as not shared; the true answer to how many riders declined? is 447. The same holds for stops: 294 trips have no stop data at all and 215 have an empty list. The revenue query joins trip_stops back to trips through a pre-aggregated subquery, so a trip with three stops is still counted once in the revenue.

08. Check your understanding

Practice check · 3 questions

Reading the export

Use the code and outputs of this lab. Each question has one best answer.

Q1. In step 2, why does `count_documents({"shared_ride": None})` return 336 when only 36 documents hold an explicit null?
Q2. A colleague changes one line to `stop_count = len(doc.get('stops', []))`. What changes in the output?
Q3. A new app version writes `fare.total` as an object, `{amount: '18.40', currency: 'GBP'}`. What does export.py do with those trips?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

  1. Your week of trips. Export one week of trips from your ride-hailing project to Parquet with explicit schemas, a child table for every embedded array, and a reconciliation script like reconcile.py. Write down every cast rule and what goes to quarantine.
  2. Accept the new shape. Extend to_money() to accept the object form from the last practice question, but only when its currency is GBP; quarantine other currencies with a clear reason.
  3. Partition the output. Write trips as a Parquet dataset partitioned by city with pyarrow.parquet.write_to_dataset, and check in DuckDB that the counts per city are unchanged.

10. Review prompt

Without looking back:

  1. Why does an export declare its target schema instead of inferring it, and what should happen to values that do not fit?
  2. How do you flatten a nested object, and how do you flatten an array? Why are they different?
  3. Which states of a document field can a nullable boolean column not tell apart, and how do you keep them apart?
  4. Which checks prove that an export lost or changed nothing?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check