1、執(zhí)行備份還原前為了數(shù)據(jù)的安全 需要通過通過fsync和鎖可以在[MongoDB]不是必須運(yùn)行時(shí),安全有效地使用復(fù)制數(shù)據(jù)目錄的方式進(jìn)行備份!fsync命令會(huì)強(qiáng)制服務(wù)器將所有緩沖區(qū)內(nèi)容寫入到磁盤!通過上鎖,可以阻止數(shù)據(jù)庫的進(jìn)一步寫入!下面演示具體做法:
use admin;
switched to db admin
> db.runCommand({"fsync" : 1, "lock" : 1});
命令正確運(yùn)行結(jié)果
{
"info" : "now locked against writes, use db.fsyncUnlock() to unlock",
"seeAlso" : "http://www.mongodb.org/display/DOCS/fsync+Command",
"ok" : 1
}
1、開始執(zhí)行備份命令
mongodump -h dbhost -d dbname -o dbdirectory
# -h MongDB所在服務(wù)器地址,例如:127.0.0.1,當(dāng)然也可以指定端口號(hào):127.0.0.1:27017
# 需要備份的數(shù)據(jù)庫實(shí)例,例如:test
# 備份的數(shù)據(jù)存放位置,例如:c:\data\dump
mongodump -h 127.0.0.1 -u admin -p xxx -d blog -o /home/timeless/桌面/mongodump --authenticationDatabase admin
注意: --authenticationDatabase 參數(shù)制定認(rèn)證數(shù)據(jù)庫 否則會(huì)提示錯(cuò)誤,注意認(rèn)證庫是和-u -p
指定的賬號(hào)密碼是對(duì)應(yīng)的:
Failed: error connecting to db server: server returned error on SASL authentication step: Authentication failed. //提示認(rèn)證失敗
注意: -0 指定的備份路徑是具體的路徑不要增加"" 如上/home/timeless/桌面/mongodump 不是‘/home/timeless/桌面/mongodump’
#恢復(fù) 同樣要先lock 在 unclock (不是必須的)
-h:MongoDB所在服務(wù)器地址
-d:需要恢復(fù)的數(shù)據(jù)庫實(shí)例,例如:test,當(dāng)然這個(gè)名稱也可以和備份時(shí)候的不一樣,比如test2
–drop:恢復(fù)的時(shí)候,先刪除當(dāng)前數(shù)據(jù),然后恢復(fù)備份的數(shù)據(jù)。就是說,恢復(fù)后,備份后添加修改的數(shù)據(jù)都會(huì)被刪除,慎用哦!
mongorestore -h XXX -u admin -p XXX -d blog /home/timeless/桌面/mongodump/blog --authenticationDatabase admin
3、備份完成后 恢復(fù)數(shù)據(jù)庫鎖
> use admin;
switched to db admin
> db.$cmd.sys.unlock.findOne();
{ "ok" : 1, "info" : "unlock completed" }
#db.currentOp()來確認(rèn)解鎖成功
> db.currentOp();
{ "inprog" : [ ] }
備份恢復(fù)說明實(shí)例
mongorestore -u "xxx" -p "xxx" -h 127.0.0.1:27017 -d dbbackTest E:\mongoBak\host127.0.0.1\dbbackTest --authenticationDatabase dbbackTest
#注意這里的 --authenticationDatabase dbbackTest 是恢復(fù)時(shí)登錄驗(yàn)證的數(shù)據(jù)庫,可以是任意庫。比如可以是admin 也可以是要恢復(fù)的庫dbbackTest。
# 注意點(diǎn)二 --authenticationDatabase 后面跟那個(gè)庫,-u -p 就是那個(gè)庫的對(duì)應(yīng)的賬號(hào)和密碼。并且這個(gè)賬號(hào)和密碼要有足夠的權(quán)限角色執(zhí)行恢復(fù)的命令。