系列導航
五、mongo備份篇 mongoexport、mongoimport 以及mongodump、mongorestore
如下是總結mongo數據庫在執行備份和恢復中一些常用的語句。
備份方面比較:
1、mongoexport 可以指定集合中的字段, mongodump最多到集合
2、mongoexport 可以帶導出的過濾條件 -q, mongodump則不可以
3、mongoexport 可以導出json和csv格式, mongodump導出的是bson可讀性不如前者
4、mongodump 的速度和壓縮率都最好,每秒125M的數據,壓縮率達28%
5、mongodump 更適合全庫備份,mongoexport更適合單個集合備份
恢復方面比較:
1、mongoimport 速度較快,但不保證數據完整導入 。
2、mongorestore 速度較慢,比mongoimport慢2.5倍左右,但是根據mongodump導出的數據,可以完整導入數據
----------------mongoexport使用樣例begin-------------------
cd /opt/mongodb/bin
--數據導出
./mongoexport -h 192.168.0.10 -d testdb -c testcollection -q '{_id:{$in:["1193860277","1193860919","1193860428","1193860453","1193860364"]}}' -o /opt/testcollection.json
參數解釋:
-h 192.168.0.10 :192.168.0.10是主機ip
-d testdb :testdb數據庫
-c testcollection :testcollection是數據庫中的集合
-q 后面跟的是查詢條件(可選)
-o 后面跟的是備份的文件存放地址 例如:/opt/testcollection.json
--數據導入
./mongoimport -h 192.168.0.10:27017 -d testdb -c testcollection --type json --file /opt/testcollection.json
參數解釋:
--type json :表示導入的文件是json格式的備份文件
--file 后面跟導入的文件地址
例子:導出整個結合的樣例
--導出person集合
./mongoexport -d testdb -c person --type json -o /opt/person.json
--還原數據語句
cd /opt/mongodb/bin
./mongoimport -d testdb -c person --type json --file /opt/person.json
備份一個時間段的數據樣例 備份statTime時間 大於等於2019-01-01 並且小於2020-01-01這個時間段的數據
./mongoexport -h 192.168.0.10:27017 -d testdb -c person -q '{"statTime":{$gte:Date('`date -d 2019-01-01 +%s000`'),$lt:Date('`date -d 2020-01-01 +%s000`')}}' -o /opt/person.json
密碼校驗
如果mongo數據庫是帶密碼驗證的則需要使用如下語句
./mongoexport -h 192.168.0.10:27017 --authenticationDatabase admin -u dbuser -p dbpwd -d testdb -c person -o /opt/person.json
參數解釋:
--authenticationDatabase admin :指驗證用戶名和密碼的庫是admin
-u dbuser : dbuser是數據庫的用戶名
-p dbpwd : dbpwd是數據庫的密碼
----------------mongoexport使用樣例end-------------------
----------------mongodump使用樣例begin--------------------
--備份 /opt/mongodb/bin/mongodump -h 192.168.0.10:27017 --authenticationDatabase admin -u dbuser -p dbpwd -d testdb -c person -o /opt 參數解釋: --authenticationDatabase admin :指驗證用戶名和密碼的庫是admin -u dbuser : dbuser是數據庫的用戶名 -p dbpwd : dbpwd是數據庫的密碼 注:不用指定備份的文件名 --恢復 /usr/local/mongodb/bin/mongorestore -h 192.168.0.10:27017 --authenticationDatabase admin -u dbuser -p dbpwd -d testdb -c person /opt/person.bson
----------------mongodump使用樣例end--------------------
