MongoDB 數(shù)據(jù)備份與恢復(fù)

在實(shí)際開發(fā)運(yùn)維過程中,數(shù)據(jù)庫(kù)的備份和恢復(fù)必不可少,MongoDB 也提供了對(duì)應(yīng)的備份和恢復(fù)數(shù)據(jù)庫(kù)命令,同時(shí)還支持從多種數(shù)據(jù)形式中導(dǎo)入數(shù)據(jù)。

數(shù)據(jù)備份指令 mongodump

使用 mongodump 指令可以將數(shù)據(jù)庫(kù)導(dǎo)出為壓縮包。使用前需要先安裝官方提供的數(shù)據(jù)庫(kù)工具,建議同時(shí)閱讀官方提供的操作文檔。下載解壓后將里面的 bin 文件下的工具復(fù)制到 mongo 的安裝目錄的 bin目錄下即可。下面的指令就是將 test 數(shù)據(jù)庫(kù)導(dǎo)出為 test.backup.20210713:

# 指定數(shù)據(jù)庫(kù)備份
mongodump --db=test --gzip --out="test.backup.20210713"
# 備份全部數(shù)據(jù)庫(kù)
mongodump --gzip

導(dǎo)出的文件目錄如下:


導(dǎo)出目錄

數(shù)據(jù)恢復(fù)指令 mongorestore

我們先刪除 test 數(shù)據(jù)庫(kù),再恢復(fù)。

 use test;
 db.dropDatabase();

恢復(fù)指令如下:

mongorestore --db test test.backup.20210713/test --drop --gzip;

新版本的指令可以使用--nsInclude 參數(shù)恢復(fù)整個(gè)數(shù)據(jù)庫(kù)或某個(gè)數(shù)據(jù)集。

# 恢復(fù) test 數(shù)據(jù)庫(kù)
mongorestore --gzip --nsInclude="test.*" test.backup.20210713/
# 恢復(fù) test.employees數(shù)據(jù)集
mongorestore --gzip --nsInclude="test.employees" test.backup.20210713/

導(dǎo)出 json 和 csv文件

使用 mongoexport 工具可以導(dǎo)出 json 或 csv 文件,其中導(dǎo)出 csv 必須要指定導(dǎo)出的字段。

mongoexport --collection=employees --db=test --out=employees.json
# 指定字段導(dǎo)出
mongoexport --collection=employees --db=test --fields=name,age,dept --out=employees_f.json
# 導(dǎo)出csv
mongoexport --collection=employees --db=test --fields=name,age,dept --type=csv --out=employees.csv

從 json和 csv 導(dǎo)入

導(dǎo)入使用 mongoimport 工具,從 json 導(dǎo)入時(shí)指定數(shù)據(jù)庫(kù)和數(shù)據(jù)集,以及 json文件位置即可。

mongoimport --collection=employees --db=test employees.json

從 csv導(dǎo)入時(shí)也是類似的,只是需要指定參數(shù)--type=csv--fields 明確導(dǎo)入字段。

mongoimport --collection=employees --db=test --type=csv --fields=name,dept,age employees.csv

總結(jié)

本篇介紹了 MongoDB 的數(shù)據(jù)備份和恢復(fù),導(dǎo)出數(shù)據(jù)集到 json、csv以及從 json 和 csv文件導(dǎo)入數(shù)據(jù)。MongoDB 還提供了更多的工具,感興趣的掘友可以到 Mongo 的官網(wǎng)查看具體的使用方法。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容