MongoDB 提供了 mongorestore
工具来恢复之前使用 mongodump
创建的备份。mongorestore
可以将备份文件还原到现有的 MongoDB 实例中。
基本用法
mongorestore
的基本语法如下:
mongorestore [options]
常用选项
--dir <directory>
:指定包含备份文件的目录。--archive <filename>
:从单一的归档文件中恢复数据。--host <hostname>
:指定 MongoDB 服务器的主机名或 IP 地址。--port <port>
:指定 MongoDB 服务器的端口。--db <database>
:指定要恢复的数据库名称。--collection <collection>
:指定要恢复的集合名称。--gzip
:从 gzip 压缩的备份文件中恢复数据。--drop
:在恢复之前删除目标数据库中的现有数据。--authenticationDatabase <authdb>
:指定认证数据库。--username <username>
:指定用户名。--password <password>
:指定密码。
示例
假设你有一个名为 test
的数据库的备份文件夹位于 /backups/mongo
,现在想要将数据恢复到名为 restored_test
的新数据库中,可以使用以下命令:
mongorestore --dir /backups/mongo --db restored_test
如果你的 MongoDB 服务器需要身份验证,可以使用 --username
和 --password
选项:
mongorestore --dir /backups/mongo --db restored_test --host localhost --port 27017 --username admin --password mypassword --authenticationDatabase admin
恢复特定集合
如果你只想恢复特定集合,可以使用 --collection
选项:
mongorestore --dir /backups/mongo --db test --collection users
恢复到单一文件
如果你之前使用 --archive
选项创建了单一的归档文件,可以使用以下命令恢复数据:
mongorestore --archive=/backups/mongo/test.archive
使用 gzip 压缩
如果你使用了 gzip 压缩备份文件,可以使用 --gzip
选项恢复数据:
mongorestore --dir /backups/mongo --db test --gzip
清空现有数据
如果你想在恢复数据之前清空目标数据库中的现有数据,可以使用 --drop
选项:
mongorestore --dir /backups/mongo --db test --drop
使用示例
以下是使用 Node.js 脚本来执行 mongorestore
的一个示例。我们将使用 Node.js 的 child_process
模块来调用 mongorestore
命令。
const { exec } = require('child_process');
const restoreCommand = 'mongorestore --dir /backups/mongo --db test --gzip';
exec(restoreCommand, (error, stdout, stderr) => {
if (error) {
console.error(`执行错误: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
if (stderr) {
console.error(`stderr: ${stderr}`);
}
});
注意事项
- 权限:确保执行
mongorestore
的用户有足够的权限访问 MongoDB 数据库。 - 数据完整性:在恢复数据之前,确保备份文件完整无误。
- 版本兼容性:确保备份文件与目标 MongoDB 版本兼容。
- 数据冲突:如果目标数据库中已经存在数据,恢复过程中可能会发生数据冲突。使用
--drop
选项可以避免这类问题。
自动化恢复
如果你需要自动化恢复过程,可以使用 cron 作业或类似的调度工具来定期执行 mongorestore
。
如果你需要更详细的示例或有其他具体需求,请随时告诉我!