蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 MongoDB 三层文档结构、MapReduce/聚合等价对比、GridFS 分块与版本里程碑验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-intro.py
explore-intro.py170 行
"""Offline MongoDB architecture, MapReduce, GridFS & version milestones verifier (Ch03 intro)."""
import json
import math

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"


def case_db_collection_document_hierarchy():
    server = {
        "app_db": {
            "users": [
                {
                    "_id": 1,
                    "FirstName": "Alice",
                    "Address": {"city": "Shanghai", "zip": "200000"},
                    "roles": ["editor", "reviewer"],
                },
                {
                    "_id": 2,
                    "FirstName": "Bob",
                    "Address": {"city": "Beijing", "zip": "100000"},
                    "roles": ["reader"],
                },
            ]
        }
    }
    # Index on FirstName and Address.city
    idx_firstname = {d["FirstName"]: d["_id"] for d in server["app_db"]["users"]}
    idx_city = {d["Address"]["city"]: d["_id"] for d in server["app_db"]["users"]}
    actual = {
        "lookup_by_FirstName": idx_firstname["Alice"],
        "lookup_by_Address_city": idx_city["Beijing"],
        "embedded_array_len": len(server["app_db"]["users"][0]["roles"]),
    }
    expected = {
        "lookup_by_FirstName": 1,
        "lookup_by_Address_city": 2,
        "embedded_array_len": 2,
    }
    return {
        "name": "db_collection_document_hierarchy",
        "summary": "验证数据库-集合-文档三层结构、内嵌文档/数组及任意字段(FirstName/Address)索引定位。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mapreduce_emit_and_reduce_aggregation():
    sales = [
        {"cust_id": "A", "amount": 25},
        {"cust_id": "A", "amount": 75},
        {"cust_id": "B", "amount": 40},
        {"cust_id": "C", "amount": 10},
        {"cust_id": "B", "amount": 60},
    ]
    emitted = {}

    def emit(k, v):
        emitted.setdefault(k, []).append(v)

    for doc in sales:
        emit(doc["cust_id"], doc["amount"])
    mr_result = {k: sum(vs) for k, vs in sorted(emitted.items())}

    # Equivalent modern Aggregation Pipeline ($group)
    agg_result = {}
    for doc in sales:
        agg_result[doc["cust_id"]] = agg_result.get(doc["cust_id"], 0) + doc["amount"]
    agg_result = dict(sorted(agg_result.items()))

    actual = {"mapreduce": mr_result, "aggregation": agg_result, "equivalent": mr_result == agg_result}
    expected = {
        "mapreduce": {"A": 100, "B": 100, "C": 10},
        "aggregation": {"A": 100, "B": 100, "C": 10},
        "equivalent": True,
    }
    return {
        "name": "mapreduce_emit_and_reduce_aggregation",
        "summary": "模拟 MapReduce emit(key, value) 与 Reduce 汇总,并验证其与现代聚合管道结果等价。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_gridfs_chunking_and_update_semantics():
    # Simulate splitting a 600 KiB binary payload into 255 KiB GridFS chunks
    payload = b"M" * (600 * 1024)
    chunk_size = 255 * 1024
    chunks = [payload[i : i + chunk_size] for i in range(0, len(payload), chunk_size)]
    reassembled = b"".join(chunks)

    # Field update vs full replacement
    doc = {"_id": 1, "name": "Alice", "age": 25, "city": "Shanghai"}
    updated = dict(doc)
    updated["age"] = 26  # $set field update preserves city
    replaced = {"_id": doc["_id"], "name": "Alice", "age": 26}  # full replace omits city

    actual = {
        "chunk_count": len(chunks),
        "last_chunk_kib": len(chunks[-1]) // 1024,
        "lossless_reassembly": reassembled == payload,
        "field_update_keeps_city": "city" in updated,
        "replace_drops_city": "city" not in replaced,
    }
    expected = {
        "chunk_count": 3,
        "last_chunk_kib": 90,
        "lossless_reassembly": True,
        "field_update_keeps_city": True,
        "replace_drops_city": True,
    }
    return {
        "name": "gridfs_chunking_and_update_semantics",
        "summary": "验证 GridFS 255 KiB 分块与无损重组,以及字段级更新与整文档替换的语义差异。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_version_milestones_and_ecosystem_catalog():
    milestones = {
        "1.4": "sharding",
        "1.6": "replica_sets",
        "3.0": "wiredtiger_scram",
        "3.2": "wiredtiger_default_spidermonkey",
        "3.4": "views_collation",
        "4.0": "multi_doc_transactions",
        "4.4.6": "versioned_api",
        "5.0": "time_series_live_resharding",
        "6.0": "mongosh_separate_shell",
        "7.0": "compound_wildcard_slot_engine",
    }
    platforms = ["Linux", "Windows", "macOS", "Docker"]
    actual = {
        "milestone_count": len(milestones),
        "tx_introduced_in": "4.0",
        "platform_count": len(platforms),
        "supports_docker": "Docker" in platforms,
    }
    expected = {
        "milestone_count": 10,
        "tx_introduced_in": "4.0",
        "platform_count": 4,
        "supports_docker": True,
    }
    return {
        "name": "version_milestones_and_ecosystem_catalog",
        "summary": "核对 MongoDB 1.0 至 7.0 关键版本里程碑与多平台部署矩阵。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_db_collection_document_hierarchy(),
        case_mapreduce_emit_and_reduce_aggregation(),
        case_gridfs_chunking_and_update_semantics(),
        case_version_milestones_and_ecosystem_catalog(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/mongodb-intro-lab/explore-intro.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-intro.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1748.zip

下载课程关联工程包:MongoDB

课程关联工程包(登记关联49章) · 含当前章节或实例 · mbskycom202612a1732.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习