前言
前陣子使用 ssr 重構(gòu)了博客蝴乔,需要對之前的舊數(shù)據(jù)進(jìn)行備份四啰,之前的做法是直接把mongo/data目錄下的所有文件進(jìn)行備份...... (沒錯(cuò)我之前就是這么干的.)
最近研究了一下宁玫,有兩種方法可以備份 mongo 數(shù)據(jù)庫
如下圖,有一個(gè) blog 數(shù)據(jù)庫柑晒,我們下面開始對其進(jìn)行備份
1. mongodump欧瘪、mongorestore
? mongodump 是 MongoDB 官方提供的備份工具,它可以從 MongoDB 數(shù)據(jù)庫讀取數(shù)據(jù)匙赞,并生成 BSON 文件佛掖,mongodump 適合用于備份和恢復(fù)數(shù)據(jù)量較小的 MongoDB 數(shù)據(jù)庫,不適用于大數(shù)據(jù)量備份涌庭。
備份
語法如下苦囱,注意有幾個(gè)參數(shù):
- -h:MongDB所在服務(wù)器地址,如 localhost:27017
- -d:備份的數(shù)據(jù)庫
- -c:備份的數(shù)據(jù)表
- -o:備份的數(shù)據(jù)存放位置
mongodump -h dbhost -d dbname -o dbdirectory
我們直接運(yùn)行命令:
# 導(dǎo)出 blog 數(shù)據(jù)庫 到當(dāng)前目錄
mongodump -h localhost:27017 -d blog -o ./
# 也可以導(dǎo)出特定表
# 導(dǎo)出 blog 數(shù)據(jù)庫的 articles 表 到當(dāng)前目錄
mongodump -h localhost:27017 -c articles -d blog -o ./
執(zhí)行完畢脾猛,我們點(diǎn)開blog目錄發(fā)現(xiàn),下面有后綴為 bson鱼鸠、json的文件猛拴,輸出一個(gè)bson文件看,發(fā)現(xiàn)是亂碼:
cat articles.bson
其實(shí)我們備份的數(shù)據(jù)都是二進(jìn)制的蚀狰,我們直接查看不到的愉昆,需要結(jié)合 mongo 自帶的 bsondump :
bsondump .\articles.bson
emmm,可以正常查看了
恢復(fù)
和備份差不多:
- -h:MongDB所在服務(wù)器地址麻蹋,如 localhost:27017
- -d:需要恢復(fù)的數(shù)據(jù)庫
- -c:需要恢復(fù)的數(shù)據(jù)表
- <path>:mongorestore 最后的一個(gè)參數(shù)跛溉,備份數(shù)據(jù)所在位置
>mongorestore -h <hostname><:port> -d dbname <path>
我們先把 blog 數(shù)據(jù)庫刪除,然后開始恢復(fù)
# 恢復(fù) blog 數(shù)據(jù)庫的所有表
mongorestore -h localhost:27017 -d blog ./
# 當(dāng)然你也可以只恢復(fù)特定的表
# 比如扮授,只恢復(fù) articles 表
mongorestore -h localhost:27017 -c articles -d blog ./articles.bson
執(zhí)行芳室,所有數(shù)據(jù)已恢復(fù)~
2. mongoexport、mongoimport
Mongodb中 的 mongoexport 工具可以把一個(gè) collection 導(dǎo)出成 JSON 格式或 CSV 格式的文件刹勃。
mongoexport 只能一個(gè)一個(gè)表導(dǎo)出堪侯,額.......
導(dǎo)出
mongoexport 的使用和參數(shù)基本和 mongodump 一樣:
- -h:MongDB所在服務(wù)器地址,如 localhost:27017
- -d:備份的數(shù)據(jù)庫
- -c:備份的數(shù)據(jù)表
- -o:備份的數(shù)據(jù)存放位置荔仁,必須指定存放類型伍宦,如 json芽死、csv
# 導(dǎo)出 blog 數(shù)據(jù)庫的 articles 表
mongoexport -h localhost:27017 -d blog -c articles -o ./articles.json
mongoexport -h localhost:27017 -d blog -c articles -o ./articles.csv
恢復(fù)
- -h:MongDB所在服務(wù)器地址,如 localhost:27017
- -d:恢復(fù)的數(shù)據(jù)庫
- -c:恢復(fù)的數(shù)據(jù)表
- <path>:mongorestore 最后的一個(gè)參數(shù)次洼,備份數(shù)據(jù)所在位置
# 從json導(dǎo)入
mongoimport -h localhost:27017 -d blog -c articles ./articles.json
# 從csvf導(dǎo)入
mongoimport -h localhost:27017 -d blog -c articles ./articles.csv
恢復(fù)成功~
END