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

MongoDB Shell

系统介绍新一代官方交互终端 MongoDB Shell(mongosh)在 macOS、Linux 与 Windows 的安装方式、连接参数、常用会话指令及完整 CRUD 操作示例。

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

学完这一章,你能够

MongoDB Shell(mongosh)定位与多平台安装

MongoDB Shell(`mongosh`)是官方提供的现代交互式命令行环境,基于 JavaScript(Node.js 运行时),允许开发者在终端或脚本中直接向 MongoDB 实例发起查询、写入与运维管理。相比历史上的旧版 `mongo` 工具,`mongosh` 提供语法高亮、自动补全与更一致的现代 CRUD 驱动接口;需留意在 MongoDB 6.0 及以上版本中,部分安装包需单独获取或确认勾选 `mongosh`。

在 macOS 上既可通过 Homebrew(`brew tap mongodb/brew` 后安装官方 shell 包,现代包名为 `mongosh`,早期亦有 `mongodb-community-shell`)一键获取,也可前往 `https://www.mongodb.com/try/download/shell` 下载归档并解压,将 `mongosh` 可执行文件复制至 `/usr/local/bin/`、将配套共享库 `mongosh_crypt_v1.so` 复制至 `/usr/local/lib/`。若首次运行被 macOS 安全机制拦截,可在“系统设置/偏好设置 -> 隐私与安全性”中放行。

在 Linux(以 Ubuntu 22.04 Jammy 为例)上,可向 `/etc/apt/sources.list.d/mongodb-org-7.0.list` 添加官方 APT 源并更新缓存后通过包管理器安装(现代官方包名为 `mongodb-mongosh`),或者同样从官网下载压缩包并将 `mongosh` 与 `mongosh_crypt_v1.so` 拷贝至 `PATH` 与系统库目录。在 Windows 上则直接下载官网安装程序并按向导勾选环境变量配置,即可在 PowerShell 或 CMD 中运行 `mongosh`。

连接选项与核心交互命令

安装完成后,执行 `mongosh` 默认连接本机 `27017` 端口,执行 `mongosh --version` 可核对版本号(如 `2.2.9`);若连接远程或自定义端口实例,可使用 `mongosh --host <hostname>:<port>`(其中 `<hostname>` 为主机名或 IP、`<port>` 为监听端口)。连入会话后的高频基础命令包括:`db` 查看当前库、`show dbs` 列出数据库、`use <database_name>` 切换数据库、`db.<collection_name>.find()` 查询文档、`insertOne()` / `updateOne()` / `deleteOne()` 执行增改删,以及 `quit()` 或 `exit` 退出终端。

完整 CRUD 交互流程实测

一个标准的 `mongosh` 演练周期依次包含:启动后用 `show dbs` 查看已有库并 `use` 切换到工作库;调用 `db.mycollection.insertOne({ name: "Alice", age: 30 })` 写入文档并获得包含 `acknowledged: true` 与 `insertedId` 的回执;调用 `db.mycollection.find()` 检视文档;执行 `db.mycollection.updateOne({ name: "Alice" }, { $set: { age: 31 } })` 验证 `matchedCount: 1`、`modifiedCount: 1` 与 `upsertedCount: 0`;执行 `db.mycollection.deleteOne({ name: "Alice" })` 确认 `deletedCount: 1`;最后以 `quit()` 结束会话。更多平台细节可参考官方文档 `https://www.mongodb.com/zh-cn/docs/mongodb-shell/install/`。

运行 mongosh 安装规范、CLI 参数解析、会话命令与完整 CRUD 回执离线验证

python · 阅读源码
"""Offline MongoDB Shell (mongosh) CLI, session & CRUD walkthrough verifier (Ch07 shell)."""
import json
import re

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


def parse_mongosh_args(argv):
    host = "127.0.0.1"
    port = 27017
    show_version = False
    i = 0
    while i < len(argv):
        if argv[i] == "--version":
            show_version = True
        elif argv[i] == "--host" and i + 1 < len(argv):
            val = argv[i + 1]
            if ":" in val:
                host, p = val.rsplit(":", 1)
                port = int(p)
            else:
                host = val
            i += 1
        elif argv[i] == "--port" and i + 1 < len(argv):
            port = int(argv[i + 1])
            i += 1
        i += 1
    return {"host": host, "port": port, "show_version": show_version}


def case_mongosh_cross_platform_install_spec():
    install_targets = {
        "macos_manual": ["/usr/local/bin/mongosh", "/usr/local/lib/mongosh_crypt_v1.so"],
        "linux_apt": "/etc/apt/sources.list.d/mongodb-org-7.0.list",
        "windows_msi": "mongosh.exe",
    }
    actual = {
        "platforms_covered": len(install_targets),
        "crypt_lib_included": any("mongosh_crypt_v1.so" in p for p in install_targets["macos_manual"]),
        "apt_list_suffix_ok": install_targets["linux_apt"].endswith(".list"),
    }
    expected = {
        "platforms_covered": 3,
        "crypt_lib_included": True,
        "apt_list_suffix_ok": True,
    }
    return {
        "name": "mongosh_cross_platform_install_spec",
        "summary": "核对 macOS、Linux 与 Windows 平台安装 mongosh 的二进制路径与加密库配置规范。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mongosh_cli_connection_parser():
    default_conn = parse_mongosh_args([])
    remote_conn = parse_mongosh_args(["--host", "db.example.internal:27018"])
    ver_flag = parse_mongosh_args(["--version"])
    actual = {
        "default_host_port": [default_conn["host"], default_conn["port"]],
        "remote_host_port": [remote_conn["host"], remote_conn["port"]],
        "version_flag": ver_flag["show_version"],
    }
    expected = {
        "default_host_port": ["127.0.0.1", 27017],
        "remote_host_port": ["db.example.internal", 27018],
        "version_flag": True,
    }
    return {
        "name": "mongosh_cli_connection_parser",
        "summary": "解析 mongosh 默认连接 127.0.0.1:27017、--host <host>:<port> 与 --version 命令行参数。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mongosh_session_commands():
    dbs = {"admin": {}, "config": {}, "local": {}, "demo": {"items": []}}
    cur = "test"
    initial_db = cur
    listed = sorted(dbs.keys())
    cur = "demo"
    switched_db = cur
    exit_aliases = {"quit()", "exit"}
    actual = {
        "initial_db": initial_db,
        "show_dbs": listed,
        "switched_db": switched_db,
        "exit_commands_valid": "quit()" in exit_aliases and "exit" in exit_aliases,
    }
    expected = {
        "initial_db": "test",
        "show_dbs": ["admin", "config", "demo", "local"],
        "switched_db": "demo",
        "exit_commands_valid": True,
    }
    return {
        "name": "mongosh_session_commands",
        "summary": "验证 db、show dbs、use <db> 以及 quit()/exit 会话控制命令状态转移。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def case_mongosh_full_crud_walkthrough():
    coll = []
    oid = "667cd8789a69705686ed70f2"
    # insertOne
    doc = {"_id": oid, "name": "Alice", "age": 30}
    coll.append(doc)
    ins_res = {"acknowledged": True, "insertedId": oid}
    # find
    found_before = [dict(d) for d in coll]
    # updateOne({name: "Alice"}, {$set: {age: 31}})
    matched = modified = 0
    for d in coll:
        if d["name"] == "Alice":
            matched += 1
            if d["age"] != 31:
                d["age"] = 31
                modified += 1
            break
    upd_res = {
        "acknowledged": True,
        "insertedId": None,
        "matchedCount": matched,
        "modifiedCount": modified,
        "upsertedCount": 0,
    }
    age_after_update = coll[0]["age"]
    # deleteOne({name: "Alice"})
    deleted = 0
    for i, d in enumerate(coll):
        if d["name"] == "Alice":
            coll.pop(i)
            deleted = 1
            break
    del_res = {"acknowledged": True, "deletedCount": deleted}

    actual = {
        "insert_ok": ins_res["acknowledged"] and bool(re.fullmatch(r"[0-9a-f]{24}", ins_res["insertedId"])),
        "found_before_age": found_before[0]["age"],
        "update_res": upd_res,
        "age_after_update": age_after_update,
        "delete_res": del_res,
        "remaining_docs": len(coll),
    }
    expected = {
        "insert_ok": True,
        "found_before_age": 30,
        "update_res": {
            "acknowledged": True,
            "insertedId": None,
            "matchedCount": 1,
            "modifiedCount": 1,
            "upsertedCount": 0,
        },
        "age_after_update": 31,
        "delete_res": {"acknowledged": True, "deletedCount": 1},
        "remaining_docs": 0,
    }
    return {
        "name": "mongosh_full_crud_walkthrough",
        "summary": "完整执行 insertOne -> find -> updateOne -> deleteOne 交互流程并核对返回计数结构。",
        "expected": expected,
        "actual": actual,
        "passed": actual == expected,
    }


def main():
    cases = [
        case_mongosh_cross_platform_install_spec(),
        case_mongosh_cli_connection_parser(),
        case_mongosh_session_commands(),
        case_mongosh_full_crud_walkthrough(),
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
预期结果 · 待实际运行核验
  • 验证三平台安装配置、--host/--version 解析、db/show dbs/use 状态及 insertOne/find/updateOne/deleteOne 全周期回执。
运行 mongosh 安装规范、CLI 参数解析、会话命令与完整 CRUD 回执离线验证

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

当前源码 SHA256:c9742910d0ffa32a249cee6248cfeb7b581c8fb6c7db16e57e301cc8d3cadb6f

下载本站示例源码

本地运行

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

下载MongoDB Shell实验

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

ZIP SHA256:6143432e72bf5929e4e5b0273a8e8d910f86a8394278616226d20d82eaaac2b5

常见错误与边界

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

练习与解答

在 `mongosh` 中执行 `updateOne({ name: "Alice" }, { $set: { age: 31 } })` 时,若文档原本 `age` 已经是 `31`,`matchedCount` 与 `modifiedCount` 分别是多少?

展开参考解答

`matchedCount` 为 `1`(命中条件),而 `modifiedCount` 为 `0`(因为字段值未发生实质变化)。

规范与官方依据