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

Windows MongoDB

讲解 Windows 64 位平台下载与 MSI 向导安装 MongoDB、配置环境变量与数据目录、命令行启动 mongod、注册 Windows 系统服务及使用 Shell 连接读写测试。

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

学完这一章,你能够

Windows 架构要求与 MSI 图形化安装

现代 MongoDB 社区版仅向 Windows 64 位系统提供预编译 `.msi` 安装包,可从官网 `https://www.mongodb.com/try/download/community` 获取。回顾历史兼容边界:自 MongoDB 2.2 起不再支持 Windows XP,现代发行版也已全面取消 32 位构建包;早期资料中常区分 64-bit 标准版(Windows 7 / Server 2008 R2 及以上)、32-bit 版(受限于内存地址空间,单库最大约 2GB)以及面向 Vista / Server 2003 / Server 2008 的 64-bit Legacy 版。

双击下载好的 `.msi` 文件进入安装向导:点击 Next 启动安装并勾选同意许可协议;随后在服务运行身份页可选择“Network Service user(网络服务用户,适合快速体验与常规部署)”或指定本地/域账号(适合细粒度权限与资源隔离场景);接着选择 Complete 完整安装(或 Custom 自定义组件路径),点击 Install 执行并在完成后点击 Finish 关闭向导。安装结束后,建议通过“系统属性 -> 环境变量 -> 系统变量 -> Path”将 MongoDB 的 `bin` 目录加入系统 `PATH`,便于在任意终端直接调用命令。

创建数据目录与命令行启动 mongod

手动命令行启动 `mongod` 时,数据文件默认存放在根目录下的 `\data\db`(如 `C:\data\db` 或 `D:\data\db`),可通过命令行执行 `cd C:\` 与 `md "\data\db"`(或直接在资源管理器新建)提前准备目录,随后运行 `mongod --dbpath c:\data\db` 启动数据库服务。需特别注意版本演进:自 MongoDB 6.0 起服务端安装包不再捆绑旧版 `mongo.exe`,需单独安装新版 MongoDB Shell(`mongosh`)来连接实例;旧版本环境中则通过 `mongo` 命令连入。

配置为 Windows 系统服务与多实例管理

若希望 MongoDB 随 Windows 后台托管运行(新版 MSI 安装勾选服务选项时通常已自动完成,已存在目录可跳过),可以管理员身份打开终端创建 `c:\data\db` 与 `c:\data\log` 两个目录,并编写 YAML 配置文件(例如 `C:\mongodb\mongod.cfg`),显式声明 `systemLog.destination: file`、`systemLog.path: c:\data\log\mongod.log` 与 `storage.dbPath: c:\data\db`。

配置就绪后,运行 `mongod --config "C:\mongodb\mongod.cfg" --install` 将其注册为 Windows 服务(如需更换数据目录,可调整配置文件或传入 `--dbpath`;若资源充足需在一机部署多个 `mongod`/`mongos` 服务,可借助 `--serviceName` 与 `--serviceDisplayName` 区分服务名)。日常使用 `net start MongoDB` 启动、`net stop MongoDB` 停止、必要时执行 `mongod --remove` 卸载服务。手动命令行启动与注册系统服务二选一即可,切勿同时占用同一数据目录与 27017 端口。

通过管理 Shell 验证读写

服务就绪后即可通过交互式 JavaScript Shell(现代版为 `mongosh`,历史版为安装目录 `bin` 下的 `mongo.exe`)连入实例。Shell 默认连接到 `test` 数据库,可直接执行 `2 + 2` 等 JavaScript 表达式、输入 `db` 查看当前数据库名,并执行写入与查询验证(现代 `mongosh` 推荐使用 `db.demo.insertOne({x: 10})` 替代历史示例中的 `insert({x: 10})`),随后以 `db.demo.find()` 查回带有自动生成 `_id`(ObjectId)与 `x: 10` 的文档。本站离线脚本完整验证了 YAML 配置解析、服务状态机与 Shell 默认库写入。

运行 Windows mongod.cfg 配置解析、服务状态机及默认 test 库写入离线验证

python · 阅读源码
"""Offline Windows MongoDB installation, YAML config, service FSM & Shell verifier (Ch04 window-install)."""
import json
import ntpath
import re

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


def parse_simple_yaml(text: str) -> dict:
    result = {}
    section = None
    for raw in text.splitlines():
        line = raw.rstrip()
        if not line.strip() or line.strip().startswith("#"):
            continue
        if not raw.startswith(" ") and line.endswith(":"):
            section = line[:-1].strip()
            result[section] = {}
        elif section is not None and ":" in line:
            k, v = line.strip().split(":", 1)
            result[section][k.strip()] = v.strip()
    return result


def case_windows_msi_architecture_and_paths():
    db_path = ntpath.normpath(r"C:\data\db")
    log_dir = ntpath.normpath(r"C:\data\log")
    log_file = ntpath.join(log_dir, "mongod.log")
    legacy_32bit_limit_gb = 2
    actual = {
        "db_path": db_path,
        "log_file": log_file,
        "is_absolute_root_drive": ntpath.isabs(db_path),
        "legacy_32bit_limit_gb": legacy_32bit_limit_gb,
        "modern_64bit_only": True,
    }
    expected = {
        "db_path": r"C:\data\db",
        "log_file": r"C:\data\log\mongod.log",
        "is_absolute_root_drive": True,
        "legacy_32bit_limit_gb": 2,
        "modern_64bit_only": True,
    }
    return {
        "name": "windows_msi_architecture_and_paths",
        "summary": "验证 Windows 64 位安装包要求、历史 32 位 2GB 上限及数据/日志根目录规范化。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mongod_cfg_yaml_config_parser():
    cfg_text = (
        "systemLog:\n"
        "    destination: file\n"
        "    path: c:\\data\\log\\mongod.log\n"
        "storage:\n"
        "    dbPath: c:\\data\\db\n"
    )
    parsed = parse_simple_yaml(cfg_text)
    install_cmd = 'mongod --config "C:\\mongodb\\mongod.cfg" --install --serviceName MongoDB --serviceDisplayName MongoDB'
    has_required_flags = all(flag in install_cmd for flag in ("--config", "--install", "--serviceName"))
    actual = {
        "log_destination": parsed["systemLog"]["destination"],
        "log_path": parsed["systemLog"]["path"],
        "db_path": parsed["storage"]["dbPath"],
        "has_required_flags": has_required_flags,
    }
    expected = {
        "log_destination": "file",
        "log_path": r"c:\data\log\mongod.log",
        "db_path": r"c:\data\db",
        "has_required_flags": True,
    }
    return {
        "name": "mongod_cfg_yaml_config_parser",
        "summary": "解析 Windows mongod.cfg YAML 配置项(systemLog.path 与 storage.dbPath)并校验服务安装参数。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_windows_service_lifecycle_fsm():
    state = "not_installed"
    history = [state]
    transitions = [
        ("mongod --config C:\\mongodb\\mongod.cfg --install", "stopped"),
        ("net start MongoDB", "running"),
        ("net stop MongoDB", "stopped"),
        ("mongod --remove", "not_installed"),
    ]
    for _cmd, nxt in transitions:
        state = nxt
        history.append(state)
    expected = ["not_installed", "stopped", "running", "stopped", "not_installed"]
    return {
        "name": "windows_service_lifecycle_fsm",
        "summary": "模拟 Windows 下 MongoDB 服务注册、net start 启动、net stop 停止与 --remove 移除状态机。",
        "expected": expected,
        "actual": history,
        "passed": history == expected,
    }


def case_shell_default_test_db_and_crud():
    dbs = {"test": {"demo": []}}
    current_db = "test"
    arith = 2 + 2
    inserted = {"_id": "5604ff74a274a611b0c990aa", "x": 10}
    dbs[current_db]["demo"].append(inserted)
    found = list(dbs[current_db]["demo"])
    actual = {
        "default_db": current_db,
        "js_eval_2_plus_2": arith,
        "inserted_count": len(found),
        "first_doc_x": found[0]["x"],
        "id_is_24_hex": bool(re.fullmatch(r"[0-9a-f]{24}", found[0]["_id"])),
    }
    expected = {
        "default_db": "test",
        "js_eval_2_plus_2": 4,
        "inserted_count": 1,
        "first_doc_x": 10,
        "id_is_24_hex": True,
    }
    return {
        "name": "shell_default_test_db_and_crud",
        "summary": "验证 Shell 默认连接 test 库、基础算术求值、插入 {x: 10} 与 ObjectId 检索结果。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_windows_msi_architecture_and_paths(),
        case_mongod_cfg_yaml_config_parser(),
        case_windows_service_lifecycle_fsm(),
        case_shell_default_test_db_and_crud(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证 Windows 路径与 32 位 2GB 历史约束、mongod.cfg YAML 解析、服务安装/启停/卸载状态机及 Shell 读写。
运行 Windows mongod.cfg 配置解析、服务状态机及默认 test 库写入离线验证

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

当前源码 SHA256:1de12875758372ec74601cd6900f6fc974043d2d1c148453a7c89eadaca26895

下载本站示例源码

本地运行

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

下载Windows MongoDB实验

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

ZIP SHA256:edefff96c845c374849960b8fadebf62653b8f20a56421025de6e21309d64573

常见错误与边界

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

练习与解答

在 Windows 上同时通过命令行启动 `mongod --dbpath c:\data\db` 并运行 `net start MongoDB` 会产生什么冲突?

展开参考解答

如果两者指向相同的 `dbPath` 或监听相同的 `27017` 端口,后启动的实例会因数据目录锁文件冲突或端口已被占用而启动失败;两种启动方式应二选一。

规范与官方依据