版本:mongodb3.2.6
备份格式:
/data/mongodb/bin/mongodump -h IP --port 端口号 -u用户 -p 密码-d 数据库名-o 存储路径
恢复格式:
/mnt/mongodb/bin/mongorestore -h IP --port 端口号-u用户名-p密码 -d 数据库名 备份的文件夹名/*
注意,如果mongodb开启了认证登录,那么需要加参数--authenticationDatabase=admin,
因为笔者使用的mongodb开启了认证登录,因此在备份和恢复中都使用了该参数。
查看过相关资料,说是开启了认证(auth=true)会导致数据库变慢,笔者暂时未遇到过,推测应该是在一定数据量的情况才会出现。毕竟要过滤下嘛。如果服务器是在公网,建议还是要开启认证的,如果实在内网,不用认证也行,但是要保证服务器安全哦,比如指定IP才可连接mongodb数据库
如果是在本地导入导出,端口也没有更改的情况下,-h和--port参数就不用加了。
还有一个,使用导入导出的用户名需要有数据库管理权限哦。
解释一下用到的命令
1.-h:MongoDB所在服务器地址
2.-d:需要恢复的数据库实例,例如:test,当然这个名称也可以和备份时候的不一样,比如test2
3.-o:备份的数据存放位置,例如:/data/dump,当然该目录需要提前建立,在备份完成后,系统自动在dump目录下建立一个test目录,这个目录里面存放该数据库实例的备份数据。
4.--directoryperdb:备份数据所在位置,例如:/data/dump/test,这里为什么要多加一个test,而不是备份时候的dump,读者自己查看提示吧!
5.--drop:恢复的时候,先删除当前数据,然后恢复备份的数据。就是说,恢复后,备份后添加修改的数据都会被删除,慎用哦!
原始解释:-v [ --verbose ]be more verbose (include multiple times
for more verbosity e.g. -vvvvv)
--versionprint the program‘s version and exit
-h [ --host ] argmongo host to connect to (
name>/s1,s2 for sets)
--port argserver port. Can also use --host
hostname:port
--ipv6enable IPv6 support (disabled by
default)
-u [ --username ] argusername
-p [ --password ] argpassword
--authenticationDatabase arguser source (defaults to dbname)
--authenticationMechanism arg (=MONGODB-CR)
authentication mechanism
--dbpath argdirectly 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
--directoryperdbeach db is in a separate directly
(relevant only if dbpath specified)
--journalenable journaling (relevant only if
dbpath specified)
-d [ --db ] argdatabase to use
-c [ --collection ] argcollection to use (some commands)
--objcheckvalidate object before inserting
(default)
--noobjcheckdon‘t validate object before inserting
--filter argfilter to apply before inserting
--dropdrop each collection before import
--oplogReplayreplay oplog for point-in-time restore
--oplogLimit arginclude oplog entries before the
provided Timestamp (seconds[:ordinal])
during the oplog replay; the ordinal
value is optional
--keepIndexVersiondon‘t upgrade indexes to newest version
--noOptionsRestoredon‘t restore collection options
--noIndexRestoredon‘t restore indexes
--w arg (=0)minimum number of replicas per write
实战操作:
mongodb数据库的备份:
/data/mongodb/bin/mongodump -u root -p 123456 -d test -o/data/mongodb_$(date +%F) --authenticationDatabase=admin
mongodb数据库的恢复,笔者的恢复文件夹路径为/mnt/mongodb20160905/:
参考如下代码:
[[email protected] bin]# /mnt/mongodb/bin/mongorestore -uroot –p123456 -d test /mnt/mongodb20160905/ --authenticationDatabase=admin
如果导入有报错:可以在文件夹后面加*试试:
[[email protected] bin]# /mnt/mongodb/bin/mongorestore -uroot –p123456 -d test /mnt/mongodb20160905/*--authenticationDatabase=admin