Ubuntu 上 MongoDB 数据恢复指南
一 场景与准备
二 使用 mongorestore 恢复逻辑备份(最常见)
sudo systemctl stop mongodmongodump --out /path/to/backup/foldermongorestore --uri='mongodb://127.0.0.1:27017/?authSource=admin' /path/to/backup/foldermongorestore --uri='mongodb://127.0.0.1:27017/?authSource=admin' --db mydb /path/to/backup/folder/mydbmongorestore --uri='mongodb://127.0.0.1:27017/?authSource=admin' --db mydb --collection mycol /path/to/backup/folder/mydb/mycol.bsonsudo systemctl start mongodmongo --host 127.0.0.1 -u <user> -p <pwd> --authenticationDatabase admin,在 shell 中执行 show dbs、use <db>、db.<col>.countDocuments({})。?authSource=admin。三 分片备份的 bson 合并与恢复
import os, shutil
def merge_bson_dir(input_dir: str, output_dir: str):
for root, dirs, files in os.walk(input_dir):
for f in files:
if f.endswith('.bson') and not f.endswith('.metadata.json'):
rel = os.path.relpath(root, input_dir)
ns = rel.replace(os.sep, '.') # db.collection
out_dir = os.path.join(output_dir, rel)
os.makedirs(out_dir, exist_ok=True)
out_file = os.path.join(out_dir, f"{ns}.bson")
with open(out_file, 'ab') as of:
with open(os.path.join(root, f), 'rb') as inf:
shutil.copyfileobj(inf, of)
# 复制元数据
meta = os.path.join(root, f"{f}.metadata.json")
if os.path.exists(meta):
shutil.copy2(meta, os.path.join(out_dir, f"{ns}.bson.metadata.json"))
if __name__ == '__main__':
import argparse
p = argparse.ArgumentParser()
p.add_argument('input_root')
p.add_argument('-o', '--output_root', default=None)
args = p.parse_args()
merge_bson_files_dir(args.input_root, args.output_root or args.input_root)
python3 merge_bson_files.py /path/to/backup/folder -o /path/to/mergedmongorestore --uri='mongodb://127.0.0.1:27017/?authSource=admin' /path/to/merged四 物理备份恢复 WiredTiger 数据目录(同版本)
systemLog:
destination: file
path: /test/mongo/mongod.log
logAppend: true
security:
authorization: enabled
storage:
dbPath: /test/mongo/data
directoryPerDB: true
net:
port: 27017
unixDomainSocket:
enabled: false
processManagement:
fork: true
pidFilePath: /test/mongo/mongod.pid
mongod -f /test/mongo/mongod.confmongo --host 127.0.0.1 -u <user> -p <pwd> --authenticationDatabase admin,执行 show dbs 等。五 常见问题与排错