MongoDB 备份与恢复
系统掌握 MongoDB 数据备份工具 mongodump 与恢复工具 mongorestore 的核心参数、目录结构、--drop 覆盖语义及 <path> 与 --dir 互斥规则,并在本地临时目录完成全库/单集合导出恢复实测。
学完这一章,你能够
- 系统掌握 MongoDB 数据备份工具 mongodump 与恢复工具 mongorestore 的核心参数、目录结构、--drop 覆盖语义及 <path> 与 --dir 互斥规则,并在本地临时目录完成全库/单集合导出恢复实测。
mongodump 数据备份语法与常用选项
MongoDB 官方数据库工具套件(MongoDB 4.4 起作为独立的 MongoDB Database Tools 发行)提供 `mongodump` 与 `mongorestore` 实现逻辑级 BSON 备份与恢复。执行 `mongodump -h dbhost -d dbname -o dbdirectory` 可连接指定实例并将数据库导出为包含集合数据与索引元数据的目录树。
三个基础参数含义明确:`-h`(等价于 `--host`)指定目标服务器地址与端口(如 `127.0.0.1:27017`);`-d`(等价于 `--db`)指定待备份的数据库名(如 `test`);`-o`(等价于 `--out`)指定输出根目录(如 `c:\data\dump`),命令会在该目录下按数据库名自动建立子目录存放各集合备份文件。
本地 `27017` 端口运行 `mongod` 时,直接输入无参 `mongodump` 会默认连接 `127.0.0.1:27017` 并将全部数据库导出到当前工作目录的 `dump/` 文件夹中。此外还可通过 `--host`/`--port`、`--collection`/`--db` 精确控制单集合导出;早期 MMAPv1 时代的 `--dbpath` 离线直读选项已在 MongoDB 3.0+ WiredTiger 引擎中被移除,生产环境应始终通过运行中的服务端口或副本集从节点执行在线导出。
mongorestore 数据恢复选项与 --drop 风险控制
恢复备份时使用 `mongorestore -h <hostname><:port> -d dbname <path>`:其中 `--host`/`-h` 默认指向 `localhost:27017`;`--db`/`-d` 指定目标数据库名,既可恢复回原库名 `test`,也可指定为新库名(如 `test2`)以进行安全演练与数据迁移。
`--drop` 选项会在恢复每个集合前先删除目标库中的同名集合再导入备份数据,这意味着备份时间点之后新增或修改的数据将被彻底清空,生产环境务必谨慎使用;不加 `--drop` 时默认仅插入目标库中尚不存在的 `_id` 文档。指定备份源路径时可使用末尾位置参数 `<path>` 或显式 `--dir` 选项,但两者互斥不可同时传入;无参运行 `mongorestore` 则默认从当前目录的 `dump/` 恢复。离线临时目录脚本已完整验证全库/单集合导出、默认合并与 `--drop` 覆盖差异、跨库恢复至 `test2` 以及 `<path>`/`--dir` 互斥校验。
mongodump 常用组合参数速查
| 语法 | 描述 | 实例 |
| mongodump --host HOST_NAME --port PORT_NUMBER | 连接指定主机与端口备份全部数据库。 | mongodump --host db.example.com --port 27017 |
| mongodump --dbpath DB_PATH --out BACKUP_DIRECTORY | 历史版本离线直读数据目录导出(MongoDB 3.0+ 已废弃,现代版本改用在线 --host/--uri)。 | mongodump --dbpath /data/db/ --out /data/backup/ |
| mongodump --collection COLLECTION --db DB_NAME | 仅导出指定数据库中的单个集合。 | mongodump --collection mycol --db test |
离线临时目录模拟 mongodump/mongorestore 全库与单集合备份、--drop 覆盖及参数校验
展开查看收起
"""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()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
不加 --drop 时,mongorestore 只会插入备份中 _id 不冲突的文档,目标库备份后新增的文档会被保留;加上 --drop 会先删除目标集合再完整导入备份,导致备份后的新增与修改全部丢失。