MongoDB的备份与恢复

像MongoDB这样强大的数据库,自然提供了完善,丰富而且好用的备份与恢复机制,且看。

1、整库备份与恢复

1.1 工具说明

mongodb中有工具mongodump和mongorestore提供了非常方便的对整个数据库备份与恢复功能。对于如何使用,可以采用命令后面加--help选项查看两个工具的帮助文档。如下:

$ mongodump --help
Export MongoDB data to BSON files.
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
  --ipv6                   enable IPv6 support (disabled by default)
  -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
  --forceTableScan         force a table scan (do not use $snapshot)

$ mongorestore --help
usage: mongorestore [options] [directory or filename to restore from]
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
  --ipv6                  enable IPv6 support (disabled by default)
  -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
  --oplogReplay           replay oplog for point-in-time restore
  --keepIndexVersion      don't upgrade indexes to newest version
常用的选项如下:

mongodump -h host -d dbname -o directory
-h:MongDB所在服务器地址,如:127.0.0.1,也可以指定端口号:127.0.0.1:27017
-d:需要备份的数据库名称,如:db_test
-o:备份的数据存放位置,如:~\dump,当然该目录需要提前建立,在备份完成后,系统自动在dump目录下建立一个db_test目录,这个目录里面存放该数据库实例的备份数据。

mongorestore -h host -d dbname --directoryperdb dbdirectory
-h:MongoDB所在服务器地址
-d:需要恢复的数据库名称,如:db_test,当然这个名称可以不同于备份的时候,比如new_db
--directoryperdb:备份数据文件所在位置,如:~\dump\db_test(这里之所以要加db_test子目录,从mongoretore的help中的--directoryperdb,可以读出“每一个db在一个单独的目录”。)

如果没有指定-d和--directorydb则会默认将指定host上的所有数据库备份到当前目录下的dump目录下。

1.2 工具使用实例

现在在一个远端mongo数据库服务器上,有一个test数据库,其中,建立了两个collection(book和user)供测试,其中的内容通过简单的mongo命令行可以查看,如下:

book collection:
{
    _id: ObjectId("52441b86d8947f5302000000"),
    name: "C++ Primer",
    author: "Not Known",
    type: "good book"
}
{
    _id: ObjectId("52441bd0d8947fb601000000"),
    name: "C++ Model Exploration",
    author: "A Foreigner",
    type: "Should Be Read Before Interview"
}
user collection:
{
    _id: ObjectId("52442736d8947fb501000001"),
    name: "lfqy",
    gender: "male"
}
下面用mongodump工具对该数据库进行备份:

$ mongodump -h 10.77.20.xx -d test -o ~/dump
connected to: 10.77.20.xx
DATABASE: test	 to 	/home/lfqy/dump/test
	test.system.indexes to /home/lfqy/dump/test/system.indexes.bson
		 2 objects
	test.book to /home/lfqy/dump/test/book.bson
		 2 objects
	test.user to /home/lfqy/dump/test/user.bson
		 1 objects
下面我们将服务器上的test数据库删除(可以用各种方式,命令,工具。。。这里采用的是一个mongo的可视化管理工具。),然后用命令对该库进行恢复。

$ mongorestore -h 10.77.20.xx -d test --directoryperdb ~/dump/test
connected to: 10.77.20.xx
Thu Sep 26 20:37:14 /home/lfqy/dump/test/book.bson
Thu Sep 26 20:37:14 	 going into namespace [test.book]
2 objects found
Thu Sep 26 20:37:14 /home/lfqy/dump/test/user.bson
Thu Sep 26 20:37:14 	 going into namespace [test.user]
1 objects found
Thu Sep 26 20:37:14 /home/lfqy/dump/test/system.indexes.bson
Thu Sep 26 20:37:14 	 going into namespace [test.system.indexes]
Thu Sep 26 20:37:14 { key: { _id: 1 }, ns: "test.book", name: "_id_" }
Thu Sep 26 20:37:14 { key: { _id: 1 }, ns: "test.user", name: "_id_" }
2 objects found

这样便完成了对test数据库的恢复。

另外,这里利用mongorestore工具恢复数据库对在备份之后新插入数据库的记录并不会影响。具体地说,假设备份前,test数据库的book集合中有两条记录A和B,备份之后,book集合中又新插入了记录C。这样,利用mongorestore工具恢复数据库之后,备份数据将会覆盖掉其中的记录A和B,而不会对C产生影响,最终,book集合中还是会有A、B和C三条记录。当然,也可以指定--drop选项,显示说明在恢复之前先将原来的数据库drop掉。

2、导出单个collection的数据

除了整库的备份和恢复,mongo还提供了方便的单个collection数据的导出和导入工具mongoexport和mongoimport,可以用来在对数据进行有风险的操作时对数据进行备份和灾后恢复。

2.1 工具说明

mongoexport工具可以把一个collection导出成JSON格式或CSV格式的文件;mongoimport工具可以把一个特定格式文件中的内容导入到指定的collection中(可以导入JSON格式数据,也可以导入CSV格式数据)。同样也可以使用命令加--help选项来查看两个工具的帮助,如下:

$ mongoexport --help
Export MongoDB data to CSV, TSV or JSON files.
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
  --ipv6                    enable IPv6 support (disabled by default)
  -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)
  -f [ --fields ] arg       comma separated list of field names e.g. -f 
                            name,age
  --fieldFile arg           file with fields names - 1 per line
  -q [ --query ] arg        query filter, as a JSON string
  --csv                     export to csv instead of json
  -o [ --out ] arg          output file; if not specified, stdout is used
  --jsonArray               output to a json array rather than one object per 
                            line
  -k [ --slaveOk ] arg (=1) use secondaries for export if available, default 
                            true
$ mongoimport --help
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
  --ipv6                  enable IPv6 support (disabled by default)
  -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)
  -f [ --fields ] arg     comma separated list of field names e.g. -f name,age
  --fieldFile arg         file with fields names - 1 per line
  --ignoreBlanks          if given, empty fields in csv and tsv will be ignored
  --type arg              type of file to import.  default: json (json,csv,tsv)
  --file arg              file to import from; if not specified stdin is used
  --drop                  drop collection first 
  --headerline            CSV,TSV only - use first line as headers
  --upsert                insert or update objects that already exist
  --upsertFields arg      comma-separated fields for the query part of the 
                          upsert. You should make sure this is indexed
  --stopOnError           stop importing at first error rather than continuing
  --jsonArray             load a json array, not one item per line. Currently 
                          limited to 4MB.
其中常用选项如下:

mongoexport -h host -d dbname -c collection_name -o filename(将host数据库服务器上dbname数据库中的名为collection_name的集合中的数据导出到名为filename的文件。)
-h:指明数据库服务器IP
-u:指明数据库的用户名
-p:指明数据库的密码
-d:指明数据库的名字
-c:指明collection的名字
-f:指明要导出那些列
-o:指明到要导出的文件名
-q:指明导出数据的过滤条件
mongoimport -h host -d dbname -c collection_name filename(把名为filename的文件中的数据恢复到地址为host的数据库服务器上的名为dbname的数据库中的collection_name集合中。)
-h:指明数据库服务器IP
-u:指明数据库的用户名
-p:指明数据库的密码
-d:指明数据库的名字
-c:指明collection的名字
-f:指明要导入那些列
2.2 工具使用实例

这里也采用上面提到的test数据库作为例子,首先导出其中的book集合。

$ mongoexport -h 10.77.20.xx -d test -c book -o book.json
connected to: 10.77.20.xx
exported 2 records
下面将book集合删除(这里也是采用前面的方法),然后从文件对其进行恢复(也就是将文件中的数据导入数据库)。

$ mongoimport -h 10.77.20.xx -d test -c book book.json
connected to: 10.77.20.xx
imported 2 objects
这样,便将book.json中的数据导入了test中的book集合中。

同样地,这里book.json导入数据库之后并不会影响,备份之后新加入数据库中的记录。具体地说,假设备份前,book集合中有两条记录A和B,备份之后,book集合中又新插入了记录C。这样,将备份数据导入book集合之后将会覆盖掉其中的记录AB,而不会对C产生影响,最终,book集合中还是会有A、B和C三条记录。类似与mongorestore,也可以指定--drop选项,显示说明在恢复之前先将原来的集合drop掉。
3、两者的区别

这个了解不深。首先,从上面不难看出,mongorestore和mongodump提供的是对mongo数据库的整个数据库的恢复和备份,而mongoimport和mongoexport则是提供更细粒度的collection级别的数据导入和导出。两者的粒度不同,mongoimport和mongoexport粒度更细,相对来说,更加灵活。其次,mongoimport和mongoexport只是将集合中的数据导出和导入,但是没有对数据库中的其它成分进行备份(比如索引),而mongorestore和mongodump则是对数据库中的所有成分(包括索引等其它)进行恢复和备份。然而,这也导致了mongorestore和mongodump导出的文件比较大耗时较长,而mongoimport和mongoexport导出的文件比较小,速度比较快,而且格式较为灵活。至于使用场合,大家自己根据需求揣度吧。

大笑

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值