Mongo 数据备份恢复

1. 数据导出导入

1.1. 导出mongoexport

语法:
mongoexport -d database -c collection -o  xxx.dat

mongoexport -d database -c collection --type=csv -q '{_id:{$in:["839","817"]}}' -o biao.csv --limit=1

[参数]
-h host
--port 端口
-d   导出的库
-c   要导出的表
-o   导出的文件名
-q   查询条件
-f   导出哪几列

示例:
./mongoexport -h 127.0.0.1:27017 -u admin-p 123456 --authenticationDatabase admin -d db -c table --type=csv -o /home/table.csv

例如:
./mongoexport -d Student -c StudentInfo -o /mongoexport/StudentInfo.dat
# 将数据库Student下的集合StudentInfo导出到mongoexport所在的目录下,并将其命名为StudentInfo.dat

1.2. 导入mongoimport

语法:
mongoimport -h IP地址:port -u 用户 -p 密码 -d database -c colection XXX.dat

例如:
./mongoimport -h 127.0.0.1:27017 -u zhangsan -p zhangsan -d Student -c StudentInfo StudentInfo.dat

[参数]
-h 127.0.0.1:27017:连接到本地,端口号为27017
-u zhangsan:用户名为zhangsan
-p zhangsan:密码为zhangsan
-d Student -c StudentInfo StudentInfo.dat
# 将StudentInfo.dat导入到数据库名称为Student,集合名称为StudentInfo中。

2. 数据备份恢复

2.1. 加减锁

使用fsync命令强制MongoDB服务器同步所有内存数据,然后对数据库加锁防止写入操作

  • 加锁

use admin
db.runCommand({"fsync":1,"lock":1});
{
    "info" : "now locked against writes, use db.fsyncUnlock() to unlock",
    "lockCount" : NumberLong(1),
    "seeAlso" : "http://dochub.mongodb.org/core/fsynccommand",
    "ok" : 1
}
  • 解锁

db.fsyncUnlock();
{ "info" : "fsyncUnlock completed", "lockCount" : NumberLong(0), "ok" : 1 }
> db.currentOp();
{
    "inprog" : [
     ...
  ],
  "ok" : 1
}

2.2. 备份 mongodump

先导库结构,在进行数据导出导入

语法:
mongodump -h 127.0.0.1:27017 -d test (-u 用户 -p 密码) -o /backup 
-d 要导出的库
-c 要导出的表
-o 导出的数据存放位置
-q 查询条件
  • 备份所有数据库

mongodump -u name -p 123456 -o /home --authenticationDatabase admin
  • 备份单个数据库

mongodump --port 27017 -u fkh -p 123456 -d dev_obd -o /home/  --authenticationDatabase admin
  • 备份单个表

mongodump --port 27017 -u fkh -p 123456 -d dev_obd -c test -o /home/  --authenticationDatabase admin

2.3. 恢复 mongorestore

语法:
mongorestore -h localhost:27017 -d dbname (-u anyadmin -p pwd )--dir /backup/test 
-h MongoDB所在服务器地址
-d 需要恢复的数据库实例
-c 要恢复的表  !
--drop 恢复的时候,先删除当前数据,然后恢复备份的数据。就是说,恢复后,备份后添加修改的数据都会被删除,慎用哦!
--dir 指定备份的目录
  • 还原单个表

mongorestore --port 27017 -u superuser -p 123456 --authenticationDatabase admin -d myTest -c test /backup/test.bson
  • 还原单个数据库

mongorestore --port 27017-u admin -p 123456 -d dev_obd /home/dev_obd/ --authenticationDatabase admin
  • 还原所有数据库

mongorestore --port 27017-u name -p 123456 --authenticationDatabase admin /home/mongo