使用mongodump与mongorestore迁移MongoDB数据时恢复0文档的问题排查
看起来你遇到的是那种让人摸不着头脑的问题——明明导出了几百万条数据,恢复时却一条都没进库还没报错。我帮你梳理几个最可能的原因和解决办法:
1. 命名空间不匹配(最可能的元凶)
仔细看你的mongodump输出:
2021-04-16T19:45:30.436-0600 done dumping testDB.testCollection (43992193 documents)
但前面的进度条一直显示的是testDB1.testCollection,这里明显不一致!这说明你实际导出的集合是testDB.testCollection,而不是你以为的testDB1.testCollection。
你mongorestore用的--nsFrom testDB1.testCollection和归档里的命名空间完全不匹配,mongorestore找不到要恢复的内容,自然就输出0条成功了。
解决办法:
- 先确认归档里的真实命名空间:用
mongorestore --archive=test_dump --list(MongoDB 4.4支持这个参数)直接列出归档里的所有集合;或者用bsondump test_dump查看归档内容的开头,也能看到集合命名空间。 - 如果确实是命名空间错了,要么调整mongorestore的
--nsFrom参数(比如改成--nsFrom testDB.testCollection),要么重新用正确的mongodump命令导出testDB1.testCollection。
2. 调整mongorestore的命令参数格式
MongoDB 4.4对参数解析的细节比较敏感,建议你改用--uri参数明确指定目标连接,同时给命名参数加引号避免解析问题:
mongorestore --uri="<connection_string>/testDB2?retryWrites=true&w=majority" \ --archive=test_dump \ --ssl \ --drop \ --nsFrom "testDB1.testCollection" \ --nsTo "testDB2.testCollection"
另外,也可以去掉连接字符串里的数据库名,完全通过--nsTo指定目标命名空间,避免潜在的冲突:
mongorestore --uri="<connection_string>?retryWrites=true&w=majority" \ --archive=test_dump \ --ssl \ --drop \ --nsFrom "testDB1.testCollection" \ --nsTo "testDB2.testCollection"
3. 验证归档文件的完整性
虽然mongodump显示成功,但也有可能归档文件损坏或者没正确写入。你可以用mongorestore --archive=test_dump --dryRun做一次模拟恢复,看看它是否能识别出要恢复的集合和文档数量。如果dryRun也显示0条,那肯定是归档文件的问题,需要重新执行mongodump。
4. 检查目标数据库的权限
确保你用来连接目标库的用户对testDB2有足够权限:至少需要dbWrite权限,以及dropCollection权限(因为你用了--drop参数)。可以在目标MongoDB里执行以下命令验证:
use testDB2; db.getUser("<你的用户名>"); // 查看该用户的权限列表是否包含write和drop相关权限
内容的提问来源于stack exchange,提问作者adamgy




