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

离线临时目录模拟 mongodump/mongorestore 全库与单集合备份、--drop 覆盖及参数校验

PYTHONWindows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。explore-mongodump-mongorestore.py
explore-mongodump-mongorestore.py160 行
"""Offline MongoDB mongodump / mongorestore archive & CLI option verifier."""
import hashlib
import json
from pathlib import Path
import tempfile

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


def parse_restore_args(args):
    has_dir = "--dir" in args
    positional = [a for a in args if not a.startswith("-") and a not in {"127.0.0.1:27017", "test", "test2", "/data/dump"}]
    # Explicit mutually exclusive check: positional <path> vs --dir
    if has_dir and any(a.startswith("dump/") for a in args):
        return {"valid": False, "error": "cannot specify both positional <path> and --dir"}
    return {
        "valid": True,
        "drop": "--drop" in args,
        "target_db": args[args.index("-d") + 1] if "-d" in args else None,
        "has_dir": has_dir,
        "positional_count": len(positional),
    }


def dump_database(store, out_dir, db_name=None, collection=None):
    out_path = Path(out_dir)
    written = []
    dbs = [db_name] if db_name else sorted(store.keys())
    for db in dbs:
        db_dir = out_path / db
        db_dir.mkdir(parents=True, exist_ok=True)
        cols = [collection] if collection else sorted(store[db].keys())
        for col in cols:
            docs = store[db][col]
            data_file = db_dir / f"{col}.bson.json"
            meta_file = db_dir / f"{col}.metadata.json"
            payload = json.dumps(docs, ensure_ascii=False, sort_keys=True)
            data_file.write_text(payload, encoding="utf-8")
            meta = {
                "collection": col,
                "db": db,
                "count": len(docs),
                "sha256": hashlib.sha256(payload.encode("utf-8")).hexdigest(),
            }
            meta_file.write_text(json.dumps(meta, ensure_ascii=False, sort_keys=True), encoding="utf-8")
            written.append(f"{db}/{col}")
    return written


def restore_database(store, dump_dir, src_db, target_db=None, drop=False):
    dst_db = target_db or src_db
    db_dir = Path(dump_dir) / src_db
    store.setdefault(dst_db, {})
    restored = {}
    for data_file in sorted(db_dir.glob("*.bson.json")):
        col = data_file.name[:-len(".bson.json")]
        docs = json.loads(data_file.read_text(encoding="utf-8"))
        if drop or col not in store[dst_db]:
            store[dst_db][col] = [dict(d) for d in docs]
        else:
            existing_ids = {d["_id"] for d in store[dst_db][col]}
            for d in docs:
                if d["_id"] not in existing_ids:
                    store[dst_db][col].append(dict(d))
                    existing_ids.add(d["_id"])
        restored[col] = len(store[dst_db][col])
    return restored


def main():
    source_store = {
        "test": {
            "mycol": [
                {"_id": 1, "title": "MongoDB Backup"},
                {"_id": 2, "title": "MongoDB Restore"},
            ],
            "logs": [
                {"_id": 10, "msg": "started"},
            ],
        }
    }

    with tempfile.TemporaryDirectory() as tmp:
        full_dump = Path(tmp) / "dump_all"
        col_dump = Path(tmp) / "dump_col"

        # Case 1: Full DB dump and single-collection dump layout
        full_written = dump_database(source_store, full_dump, db_name="test")
        col_written = dump_database(source_store, col_dump, db_name="test", collection="mycol")
        c1_actual = {
            "full_written": full_written,
            "col_written": col_written,
            "metadata_exists": (full_dump / "test" / "mycol.metadata.json").exists(),
        }
        c1_expected = {
            "full_written": ["test/logs", "test/mycol"],
            "col_written": ["test/mycol"],
            "metadata_exists": True,
        }

        # Case 2: mongorestore merge (without --drop) vs overwrite (with --drop) and DB rename
        target_store = {
            "test": {
                "mycol": [
                    {"_id": 2, "title": "Modified After Backup"},
                    {"_id": 3, "title": "New Doc After Backup"},
                ]
            }
        }
        restore_database(target_store, full_dump, src_db="test", target_db="test", drop=False)
        merged_ids = sorted(d["_id"] for d in target_store["test"]["mycol"])
        restore_database(target_store, full_dump, src_db="test", target_db="test", drop=True)
        dropped_ids = sorted(d["_id"] for d in target_store["test"]["mycol"])
        restore_database(target_store, full_dump, src_db="test", target_db="test2", drop=True)
        c2_actual = {
            "merged_ids": merged_ids,
            "dropped_ids": dropped_ids,
            "renamed_db_mycol_count": len(target_store["test2"]["mycol"]),
        }
        c2_expected = {
            "merged_ids": [1, 2, 3],
            "dropped_ids": [1, 2],
            "renamed_db_mycol_count": 2,
        }

        # Case 3: CLI argument contract (<path> vs --dir mutual exclusion)
        ok_dir = parse_restore_args(["-h", "127.0.0.1:27017", "-d", "test2", "--drop", "--dir", "/data/dump"])
        conflict = parse_restore_args(["-d", "test", "--dir", "/data/dump", "dump/test"])
        c3_actual = {"ok_dir_valid": ok_dir["valid"], "ok_drop": ok_dir["drop"], "conflict_valid": conflict["valid"]}
        c3_expected = {"ok_dir_valid": True, "ok_drop": True, "conflict_valid": False}

    cases = [
        {
            "name": "mongodump_full_and_collection_layout",
            "summary": "Verify mongodump writes per-database/per-collection data and metadata files cleanly.",
            "expected": c1_expected,
            "actual": c1_actual,
            "passed": c1_actual == c1_expected,
        },
        {
            "name": "mongorestore_merge_drop_and_rename",
            "summary": "Verify mongorestore preserves post-backup docs by default, overwrites with --drop, and supports restoring into test2.",
            "expected": c2_expected,
            "actual": c2_actual,
            "passed": c2_actual == c2_expected,
        },
        {
            "name": "mongorestore_path_vs_dir_contract",
            "summary": "Verify mongorestore rejects passing both positional <path> and --dir simultaneously.",
            "expected": c3_expected,
            "actual": c3_actual,
            "passed": c3_actual == c3_expected,
        },
    ]
    print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。

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

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-mongodump-mongorestore.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14 离线文档/管道/索引/GridFS/ObjectId 验证环境(本地未安装 mongod/mongosh 服务端)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:MongoDB

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

下载课程关联工程包:MongoDB

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

搜索教程、工具与资讯

热门搜索

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

欢迎登录蓝色天空网

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