MongoDB数据库导出、导入与备份、恢复

MongoDB导入命令:

mongoimport --host mongodb1.example.net --port 37017 --username user --password pass --collection contacts --db marketing --file /opt/backups/mdb1-examplenet.json


mongoimport --host mongodb1.example.net --port 37017 --username user --password pass --collection contacts --db marketing --file /opt/backups/mdb1-examplenet.json



mongoimport --db users --collection contacts --type csv --file /opt/backups/contacts.csv

mongoimport --collection contacts --file contacts.json --journal

mongoimport --db sales --collection contacts --stopOnError --dbpath /srv/mongodb/


MongoDB导出命令:

mongoexport --host mongodb1.example.net --port 37017 --username user --password pass --collection contacts --db marketing --output mdb1-examplenet.json


mongoexport --db users --collection contacts --csv --output /opt/backups/contacts.csv

mongoexport --db sales --collection contacts --output contacts.json --journal

mongoexport --db sales --collection contacts --dbpath /srv/mongodb/


Mongodb 备份与恢复


可以使用Mongodb自带的mongodump和mongorestore工具来实现数据库的备份和恢复。其用法比较简单,可以使用如下命令来获取帮助信息:

mongodump --help

mongorestore --help

备份使用命令mongodump,如果执行该命令不带任何参数,会把本机上运行的在默认端口的mongodb中的除local数据库外的所有数据库备份下来,存放在当前执行命令的目录下的dump(如果不存在该目录会自动创建)目录中,并按照数据库的名字存放在不同的不同的目录下,例如有个数据库名为test,那么其备份的文件存放的位置为./dump/test目录下。大部分情况下,我们可能不会这么干,那么可以通过-d来指定需要备份的数据,-o来指定备份存放的位置,同时可以使用-h来指定需要备份的主机地址。例如:

mongodump -h 127.0.0.1:27017 -d atagdata -o /data/dump 

 mongodump -h 127.0.0.1 --port 27017 -d atagdata -o /data/dump 

 

备份本机上的atagdata数据库中的所有collections到/data/dump目录中

每个collections都是以一个文件独立存在,

存放路径为/data/dump/atagdata/collections_name.bson 

 

mongodump -h 192.168.1.211 --port 27017 -d atagdata -o /data/dump 

备份远程数据库到本地 

mongodump -h 127.0.0.1:27017 -d atagdata -c log_01 -o /data/dump

备份atagdata数据库中collections名为log_01的数据

 

注意:备份不能一次指定多个数据库,也不能一次指定多个collections,也就是说,要么一次备份下来所有数据库,要么一次只备份一个指定的库,同理,在指定了数据库的情况下,要么全部备份该库下的所有collections,要么只备份指定的一个collections,所以要想只备份几个指定的库或collections时,可以多次执行备份命令,修改其数据库名或collections名即可。另外如果数据库需要认证,可以使用-u和-p来指定用户名和密码。

上述用mongodump备份下来的文件,可以通过mongorestore来进行恢复。可以mongodb实例没有启动的情况下执行恢复操作,这个时候必须使用dbpath来指定存放恢复数据的目录,另外可以使用directoryperdb来指定数据库的数据文件是否按文件夹来区分;当然在mongodb已经启动情况下,也是可以执行恢复操作的,这时候dbpath参数不是必须的,如果指定dbpath,那么dbpath不能指定为当前mongodb实例相同的dppath,反之mongorestore会根据当前运行的实例获取dbpath、directoryperdb信息,把备份数据恢复当前的mongodb的dbpath中。例如:

 

mongorestore /data/dump/

把/data/dump/下所有数据库恢复到当前mongodb中,数据库名字跟备份时名字相同

mongorestore -d test /data/dump/test

恢复test数据库到当前mongodb中test数据库

mongorestore -d new_test /data/dump/test

恢复test数据库到当前mongodb中,并且数据库的名字为new_test

mongorestore -d test --drop /data/dump/test

使用drop参数,在恢复前会删除已有的collections

mongorestore --dbpath /data/db_1 --directoryperdb --drop /data/dump/

把/data/dump/下所有数据库恢复到/data/db_1目录中,数据库名字跟备份时名字相同

猜你喜欢

转载自gaozzsoft.iteye.com/blog/1605735