mongo的备份与恢复

mongodb备份分为冷备与热备。冷备为停止服务的情况下进行备份,我们可以直接copy数据目录。热备为不停止mongod服务的情况下直接进行备份。mongo提供了热备工具mongodump及还原工具mongorestore

一.当前线上备份的意义

     Mongo如果仅仅只是作为一个文档型数据库,其实没有太大的亮点,它的热备功能与良好的可扩展性是使用他的很重要的原因。当前farm项目线上使用mongo使用了mongo的sgn,其实mongo本身有自己的分库(为保证同一个库不宜过大,把本应该在同一个库里的数据分布在多个库里)功能,但是对此项目不太方面,用了自己的sharding模式(在php程序里控制)。对于sgn模式(Primary+Secondary+Arbiter)可以达到数据的安全(Secondary会实时的同步Primary中的数据),但是要达到数据的绝对安全,采用异地存储备份数据是必要的,所以要用到mongodump进行备份,并将备份数据传输到S3保存。

二.mongodump用法

1.常用参数如下:

options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times for more
verbosity e.g. -vvvvv)
-h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for
sets)
--port arg server port. Can also use --host hostname:port
-u [ --username ] arg username
-p [ --password ] arg password
--dbpath arg directly access mongod database files in the given
path, instead of connecting to a mongod server -
needs to lock the data directory, so cannot be used
if a mongod is currently accessing the same path
--directoryperdb if dbpath specified, each db is in a separate
directory
--journal enable journaling
-d [ --db ] arg database to use
-c [ --collection ] arg collection to use (some commands)
-o [ --out ] arg (=dump) output directory or "-" for stdout
-q [ --query ] arg json query
--oplog Use oplog for point-in-time snapshotting
--repair try to recover a crashed database

2.对数据库进行全备份

(说明:mongo备份出来是一个目录,不像mysql备份出来是一个文件)

mongodump -o ${BACKUPDIR}

3.对其中一个库进行备份

mongodump -o ${BACKUPDIR} -d dbname

4.对其中一个collection(table)进行备份

mongodump -o ${BACKUPDIR} -d dbname -c tbname


二.mongorestore对备份进行还原

1.常用参数

options:
--help produce help message
-v [ --verbose ] be more verbose (include multiple times for more
verbosity e.g. -vvvvv)
--version print the program's version and exit
-h [ --host ] arg mongo host to connect to ( <set name>/s1,s2 for sets)
--port arg server port. Can also use --host hostname:port
-u [ --username ] arg username
-p [ --password ] arg password
--dbpath arg directly access mongod database files in the given
path, instead of connecting to a mongod server -
needs to lock the data directory, so cannot be used
if a mongod is currently accessing the same path
--directoryperdb if dbpath specified, each db is in a separate
directory
--journal enable journaling
-d [ --db ] arg database to use
-c [ --collection ] arg collection to use (some commands)
--objcheck validate object before inserting
--filter arg filter to apply before inserting
--drop drop each collection before import

2.全库还原

我们线上应用了sgn,所以在进行全库还原的时候必须保证mongo进行了sgn初始化,保证mongo属于了一个sgn.

> config = {_id:'sgn1',members:[{_id:0,host:'10.230.47.153:27017'}]}

> rs.initiate(config)

> rs.status()

还原: mongorestore  --directoryperdb ${BACKUPDIR}

3.对其中一个库进还原

mongorestore d ${DBNAME}  --drop  ${BACKUPDIR}/${DBNAME}

4.对其中一个表还原

mongorestore d ${DBNAME}  -c {TBNAME}  --drop  ${BACKUPDIR}/${DBNAME}

你可能感兴趣的:(mongo,mongodump,mongo备份)