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

运行 MongoDB BSON 16MB/GridFS 分块、聚合管道与副本集/分片路由离线验证

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-tutorial.py
explore-tutorial.py153 行
"""Offline MongoDB document model, BSON limit, MQL/aggregation & architecture verifier (Ch01 tutorial)."""
import json
import math

VERSION = "CPython 3.12.14 offline MongoDB document/query verifier (mongod absent)"
BSON_MAX_BYTES = 16 * 1024 * 1024
GRIDFS_DEFAULT_CHUNK_BYTES = 255 * 1024


def case_bson_document_model_and_16mb_limit():
    doc = {
        "_id": "66a100000000000000000001",
        "title": "MongoDB 入门指南",
        "tags": ["NoSQL", "BSON", "Document"],
        "meta": {"author": "蓝色天空网", "views": 1200, "published": True},
        "chapters": [
            {"no": 1, "name": "基础概念"},
            {"no": 2, "name": "查询与索引"},
        ],
    }
    raw = json.dumps(doc, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
    large_file_bytes = 20 * 1024 * 1024
    needs_gridfs = large_file_bytes > BSON_MAX_BYTES
    gridfs_chunks = math.ceil(large_file_bytes / GRIDFS_DEFAULT_CHUNK_BYTES)
    actual = {
        "has_nested_object": isinstance(doc["meta"], dict),
        "has_doc_array": isinstance(doc["chapters"], list) and isinstance(doc["chapters"][0], dict),
        "doc_within_16mb": len(raw) < BSON_MAX_BYTES,
        "large_file_needs_gridfs": needs_gridfs,
        "gridfs_chunks_for_20mb": gridfs_chunks,
    }
    expected = {
        "has_nested_object": True,
        "has_doc_array": True,
        "doc_within_16mb": True,
        "large_file_needs_gridfs": True,
        "gridfs_chunks_for_20mb": 81,
    }
    return {
        "name": "bson_document_model_and_16mb_limit",
        "summary": "验证嵌套对象/文档数组模型、16MB BSON 上限判断与 20MB 文件的 GridFS 分块数。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mql_filter_and_aggregation_pipeline():
    orders = [
        {"sku": "A1", "category": "db", "qty": 2, "price": 50, "status": "paid"},
        {"sku": "A2", "category": "db", "qty": 1, "price": 80, "status": "paid"},
        {"sku": "B1", "category": "web", "qty": 3, "price": 40, "status": "paid"},
        {"sku": "B2", "category": "web", "qty": 5, "price": 40, "status": "cancelled"},
    ]
    # $match status == "paid" -> $group by category sum(qty*price) -> $sort total desc
    matched = [d for d in orders if d["status"] == "paid"]
    grouped = {}
    for d in matched:
        grouped[d["category"]] = grouped.get(d["category"], 0) + d["qty"] * d["price"]
    result = sorted(
        [{"_id": k, "total": v} for k, v in grouped.items()],
        key=lambda x: x["total"],
        reverse=True,
    )
    expected = [{"_id": "db", "total": 180}, {"_id": "web", "total": 120}]
    return {
        "name": "mql_filter_and_aggregation_pipeline",
        "summary": "在内存文档集上模拟 MQL 过滤与 $match/$group/$sort 聚合管道。",
        "expected": expected,
        "actual": result,
        "passed": result == expected,
    }


def case_replica_set_failover_and_sharding_routing():
    nodes = [
        {"id": "node0", "role": "PRIMARY", "priority": 2, "alive": True},
        {"id": "node1", "role": "SECONDARY", "priority": 2, "alive": True},
        {"id": "node2", "role": "SECONDARY", "priority": 1, "alive": True},
    ]
    # Primary fails -> elect highest-priority alive secondary (tie-break by id)
    nodes[0]["alive"] = False
    nodes[0]["role"] = "DOWN"
    candidates = [n for n in nodes if n["alive"]]
    elected = sorted(candidates, key=lambda n: (-n["priority"], n["id"]))[0]
    elected["role"] = "PRIMARY"

    # Range sharding across 3 shards: [0,100), [100,200), [200,inf)
    def route_shard(tenant_id: int) -> str:
        if tenant_id < 100:
            return "shard0"
        if tenant_id < 200:
            return "shard1"
        return "shard2"

    actual = {
        "new_primary": elected["id"],
        "quorum_alive": len(candidates) > len(nodes) // 2,
        "shard_routes": [route_shard(25), route_shard(150), route_shard(310)],
    }
    expected = {
        "new_primary": "node1",
        "quorum_alive": True,
        "shard_routes": ["shard0", "shard1", "shard2"],
    }
    return {
        "name": "replica_set_failover_and_sharding_routing",
        "summary": "模拟三节点副本集主节点宕机后的多数派自动选主以及按区间键的水平分片路由。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_official_resources_and_driver_matrix():
    official_urls = {
        "home": "https://www.mongodb.com/",
        "manual": "https://www.mongodb.com/docs/manual/",
        "download": "https://www.mongodb.com/try/download/community",
    }
    drivers = sorted(["Python", "Java", "Node.js", "Go", "C#", "PHP", "C++", "Ruby"])
    actual = {
        "all_https": all(u.startswith("https://") for u in official_urls.values()),
        "driver_count": len(drivers),
        "has_python_and_node": "Python" in drivers and "Node.js" in drivers,
    }
    expected = {
        "all_https": True,
        "driver_count": 8,
        "has_python_and_node": True,
    }
    return {
        "name": "official_resources_and_driver_matrix",
        "summary": "校验 MongoDB 官方资源入口规范与多语言官方驱动生态清单。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_bson_document_model_and_16mb_limit(),
        case_mql_filter_and_aggregation_pipeline(),
        case_replica_set_failover_and_sharding_routing(),
        case_official_resources_and_driver_matrix(),
    ]
    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-tutorial-lab/explore-tutorial.py

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

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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