MongoDB备份和恢复

时间:2023-03-08 21:59:34

mongodump备份数据

该命令可以导出所有数据到指定目录中, 也能通过参数指定备份服务器

mongodump -h dbhost -d dbname -o dbdirectory
  • dbhost: mongodb所在服务器地址 如127.0.0.1, 也能指定端口号127.0.0.1:27017
  • -d: 需要备份的数据库名称
  • -o: 备份后的数据存放位置, 如: /usr/local/mongodump, 该目录要提前建立

加上-c参数表示复制某个集合


  • 建立备份目录
sudo mkdir /usr/local/mongodump
  • 现在有数据
> db
test
>
> db.stu.find()
{ "_id" : ObjectId("57fc846076ebf20f3518b61b"), "name" : "aa", "age" : 20 }
{ "_id" : ObjectId("57fc846676ebf20f3518b61c"), "name" : "bb", "age" : 30 }
>
  • 执行备份(是在终端环境)
ql@ql:~$ sudo mongodump -h 127.0.0.1:27017 -d test -o /home/ql/桌面
[sudo] ql 的密码:
2016-10-11T14:22:21.173+0800 writing test.stu to
2016-10-11T14:22:21.174+0800 done dumping test.stu (2 documents)
ql@ql:~$
ql@ql:~$ cd 桌面/test
ql@ql:~/桌面/test$ ls
stu.bson stu.metadata.json
  • 此时删除test数据库进行恢复
> db
test
>
> db.dropDatabase()
{ "dropped" : "test", "ok" : 1 }
>
>
> show dbs
local 0.000GB
>

mongorerstore数据恢复

>mongorestore -h dbhost -d dbname --dir dbdirectory
  • -h: 主机地址
  • -d: 需要恢复的数据库实例,例如:test,当然这个名称也可以和备份时候的不一样,比如test2
  • --dir: 备份数据所在位置
ql@ql:~$ mongorestore -h 127.0.0.1:27017 -d test --dir /home/ql/桌面/test

再次查看数据库

> show dbs
local 0.000GB
test 0.000GB
>
>
> db
test
>
> show collections
stu
>
>
> db.stu.find()
{ "_id" : ObjectId("57fc846076ebf20f3518b61b"), "name" : "aa", "age" : 20 }
{ "_id" : ObjectId("57fc846676ebf20f3518b61c"), "name" : "bb", "age" : 30 }
>