蓝色天空网mbsky.com · 知识 · 实践 · 创造MongoDB · 本地阅读预览
教程 / 数据库 / MongoDB

MongoDB 教程

梳理 MongoDB 文档型 NoSQL 数据库的定位、BSON 嵌套数据模型、分片与副本集架构、聚合与 MQL 查询能力、GridFS 大文件规范及官方学习入口。

本站独立整理的内容草稿。实例显示的是预期结果;浏览器、服务端运行与技术内容验收尚待完成,本页只用于阅读和图文核对。

学完这一章,你能够

MongoDB 定位与文档型数据库价值

MongoDB 是由 MongoDB Inc. 开发并维护的主流开源文档型 NoSQL 数据库,采用类 JSON 的灵活文档模型来组织业务数据,旨在为现代 Web 与高并发应用提供可扩展、高性能的数据持久化方案。在功能谱系上,它处于传统关系型数据库与纯键值 NoSQL 存储之间——既摆脱了严格表结构迁移的束缚,又保留了二级索引、丰富查询条件、聚合分析乃至多文档 ACID 事务(4.0 起)等接近关系数据库的表达力。

核心技术特性与生态体系

MongoDB 的工程能力围绕四大基石展开:第一,文档导向存储采用 BSON(Binary JSON,二进制 JSON)编码,允许在同一文档内直接表达数组与多层嵌套对象;第二,依托内存映射缓存与 WiredTiger 存储引擎的并发控制,对写入密集型和在线检索场景提供低延迟读写性能;第三,借助分片(Sharding)将数据按分片键水平拆分到多台主机,支撑海量数据与吞吐量横向扩展;第四,通过副本集(Replica Set)维护多份数据冗余,主节点故障时由多数派投票自动完成故障转移。

在查询与数据处理层面,MongoDB 提供了声明式聚合框架(Aggregation Pipeline)来组合过滤、分组与排序流水线,并通过 MongoDB 查询语言(MQL)支持常规条件过滤、全文检索与地理空间查询。历史上它也允许在库内运行 JavaScript 逻辑(现代 MongoDB 6–8 更推荐使用聚合表达式以兼顾性能与安全);对于超过单条 BSON 文档 16MB 上限的音视频或大附件,内置 GridFS 规范会自动按 255 KiB 默认块大小切片存储与重组。

在企业治理与研发体验方面,MongoDB 内置身份认证、基于角色的访问控制(RBAC)与传输/静态加密等多层安全机制,同时提供覆盖 Python、Node.js、Java、Go、C#、PHP、C++ 等主流语言的官方驱动程序,以及 `mongosh` 交互终端、MongoDB Compass 图形界面和活跃的开源社区生态,尤其适合结构演进频繁的半结构化与非结构化数据管理。

官方参考与离线实验说明

日常查阅权威语法与下载社区版安装包可直接访问 MongoDB 官网(`https://www.mongodb.com/`)、官方文档手册(`https://docs.mongodb.com/manual/`)以及社区版多平台下载页(`https://www.mongodb.com/try/download/community`)。本站离线验证脚本在本地内存中实测了嵌套文档与 16MB/GridFS 分块计算(20MB 对应 81 块)、`$match`/`$group`/`$sort` 聚合管道以及三节点副本集故障选主与区间分片路由。

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

python · 阅读源码
"""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()
预期结果 · 待实际运行核验
  • 验证嵌套文档与 GridFS 81 块切分、聚合分组排序结果、三节点副本集选主与区间分片路由及官方入口。
运行 MongoDB BSON 16MB/GridFS 分块、聚合管道与副本集/分片路由离线验证

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

当前源码 SHA256:0d7850bddefee560de00b40d96a273c835105ba18b7de778536b3da957c4feaf

下载本站示例源码

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载MongoDB 教程实验

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

ZIP SHA256:d9c81d44ad9ace0ad968b600799613f167c020bc2f86ea7666887d3fad3f25db

常见错误与边界

  • 实际端口、文档资源与应用配置都应和测试条件一致。

练习与解答

当业务需要保存一个 20MB 的视频或 PDF 文件时,为什么不能直接塞入单条 MongoDB 文档,应采用什么内置规范?

展开参考解答

因为 MongoDB 单条 BSON 文档的硬上限为 16MB;超过该阈值的文件应使用 GridFS 规范按默认 255 KiB 块拆分到 `fs.chunks` 与 `fs.files` 集合中存储与读取。

规范与官方依据