发布时间:2026-07-25阅读(1)
更多深度文章,请关注云计算频道:https://yq.aliyun.com/cloud,我来为大家讲解一下关于mongodb 没有备份数据能恢复么?跟着小编一起来看一看吧!

mongodb 没有备份数据能恢复么
更多深度文章,请关注云计算频道:https://yq.aliyun.com/cloud
近日有 MongoDB 用户遇到一个问题,使用 Wiredtiger 存储引擎的 MongoDB 无法启动,咨询我数据能否恢复回来,能恢复多少是多少 ...
问题出现的场景据用户描述是「mongod磁盘写满了,导致进程 crash」,尝试重新启动,结果 wiredtiger 报错,错误信息类似如下,类似的问题 mongodb jira 上也有人提过,可以参考 SERVER-26924,说明此时 MongoDB 数据文件已经损坏。
2017-03-28T22:06:05.315-0500 W - [initandlisten] Detected unclean shutdown - /data/mongodb/mongod.lock is not empty.
MongoDB 3.2及以后的版本已经很少会出现这样的问题,至少从我接触 MongoDB 到现在还没实际遇到过这个问题,不过既然问题已经发生,我们来看看遇到这种情况应该怎么恢复数据?
如何恢复 MongoDB 数据?
第一招: 从复制集其他节点同步数据
MongoDB 通过复制集能保证高可靠的数据存储,通常生产环境建议使用「3节点复制集」,这样即使其中一个节点崩溃了无法启动,我们可以直接将其数据清掉,重新启动后,以全新的 Secondary 节点加入复制集,它会自动的同步数据,这样也就达到了恢复数据的目的。
然而不幸的是,该用户的 MongoDB 实例 只部署了一个节点 ... 我只能呵呵了 ...
第二招:从最近的一个备份集恢复数据
MongoDB 3.2 最新版本已经是了 wiredtiger 2.8,所以编译 wt 工具时,可以下载 2.8 版本的 wiredtiger 源代码。
MongoDB 默认会对集合数据进行 snappy 压缩,所以一定要确保 snappy 正确安装,在执行 wt 工具时,通过扩展的形式加载 snappy lib,否则运行时会报错。
如果需要恢复的集合很多,本文的方法效率是很低的。
第五招:从文件里提取bson文档来恢复
MongoDB json格式的文档,最终是以 BSON (Binary json) 格式持久化存储。
假设我们有个工具叫 bsonextract(有兴趣的同学可以尝试实现下贡献到社区里,直接调 BSON 的接口,实现起来不难),它能从一个数据文件里分析并提取出所有 BSON 格式的内容,那么我们也就达到了恢复数据的目的。
分析时,一段数据满足2个条件,我们即可认为是一个合法的 MongoDB 文档
这段数据是一个合法的 BSON 文档
包含一个 id 字段 (oplog 集合不包含 id 字段,但通常也没有去恢复 oplog 的必要)
上面这个方法不仅只能恢复 wiredtiger 的数据,对 MongoDB 所有存储引擎都有效。
总结
最后,issue SERVER-19815 里介绍了 MongoDB 一直在优化 MongoDB ,让它能在 repair 模式里自动处理各种数据文件损坏(或部分丢失)的场景,目标就是万一遇到数据集损坏的场景,repair都能自动修复掉。
下面是 repair 以后能自动处理的一些场景及处理方法
Database files missing
An entry for a file will exist in the catalogue, but on disk file is gone
Will be impossible to recover from, remove the entry from the catalogue
Warn the user strongly about this (Error message)
Database files corrupted
An entry for a file will exist in the catalogue, but on disk file is unable to be opened
Attempt to rename the collection with WiredTiger to a new table that has some mention of it being corrupted in the name
Re-create the same collection with the same name (in order to continue repair)
Warn the user strongly about this problem, the creation of the new collection
Index files missing
An entry will exist in the catalogue, but on disk file is gone
Build the index as part of repair
Index files corrupted
An entry will exist in the catalogue, but on disk file is unable to be opened
Drop, then rebuild the index as part of repair
MongoDB catalogue metadata may be out of alignment with the WT files on disk
When something is missing on disk, then this should be resolved by the changes above
When something is missing from the catalogue metadata but exists as a wt table on disk we have no recourse. We would need a user accessible function to import
If the WiredTiger metadata is corrupt, then the database is corrupt
上一篇:可以投资的兼职项目一部手机就可以
下一篇:在室内用花卉装饰的布局方法
Copyright © 2024 有趣生活 All Rights Reserve吉ICP备19000289号-5 TXT地图HTML地图XML地图