CentOS 7 下 MongoDB 数据库备份 && 数据还原

MongoDB 数据备份

查看数据库

  • 切换 monitor 数据库
> use monitor
switched to db monitor
  • 查看 monitor 数据库
> show tables
InterfaceTest
NumCountZaiyuan
monitor_datasource
monitor_inhospital
monitor_inhospital_cq
monitor_linux
monitor_platstatus
monitor_productstatus
monitor_task
plat_sql
  • 查看数据量
> db.monitor_linux.count()
1704
> db.monitor_linux.findOne()
{
	"_id" : "20200604115002",
	"hostNames" : [
		"hessian01"
	],
	"hessian01" : {
		"dataDirUsed" : NumberDecimal("142.0"),
		"rootDirTotal" : NumberDecimal("34.0"),
		"momortTotal" : 63488,
		"memoryFree" : 26624,
		"cpuPercent" : NumberDecimal("0.25"),
		"loadOfOneMinute" : NumberDecimal("0.02"),
		"dataDirTotal" : NumberDecimal("493.0"),
		"loadOfFifteenMinute" : NumberDecimal("0.28"),
		"loadOfFiveMinute" : NumberDecimal("0.07"),
		"rootDirUsed" : NumberDecimal("3.0")
	},
	"time" : NumberLong("1591242602994")
}

mongoexport – 指定 collection 备份

  • mongoexport 帮助信息
[dev@hessian01 ~]$ mongoexport --help
Usage:
  mongoexport <options>

Export data from MongoDB in CSV or JSON format.

See http://docs.mongodb.org/manual/reference/program/mongoexport/ for more information.

general options:
      --help                                      print usage
      --version                                   print the tool version and exit

verbosity options:
  -v, --verbose=<level>                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a
                                                  numeric value, e.g. --verbose=N)
      --quiet                                     hide all log output

connection options:
  -h, --host=<hostname>                           mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                               server port (can also use --host hostname:port)

ssl options:
      --ssl                                       connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                      the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                  the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>              the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                     the .pem file containing the certificate revocation list
      --sslAllowInvalidCertificates               bypass the validation for server certificates
      --sslAllowInvalidHostnames                  bypass the validation for server name
      --sslFIPSMode                               use FIPS mode of the installed openssl library

authentication options:
  -u, --username=<username>                       username for authentication
  -p, --password=<password>                       password for authentication
      --authenticationDatabase=<database-name>    database that holds the user's credentials
      --authenticationMechanism=<mechanism>       authentication mechanism to use

kerberos options:
      --gssapiServiceName=<service-name>          service name to use when authenticating using GSSAPI/Kerberos ('mongodb' by default)
      --gssapiHostName=<host-name>                hostname to use when authenticating using GSSAPI/Kerberos (remote server's address by default)

namespace options:
  -d, --db=<database-name>                        database to use
  -c, --collection=<collection-name>              collection to use

uri options:
      --uri=mongodb-uri                           mongodb uri connection string

output options:
  -f, --fields=<field>[,<field>]*                 comma separated list of field names (required for exporting CSV) e.g. -f "name,age"
      --fieldFile=<filename>                      file with field names - 1 per line
      --type=<type>                               the output format, either json or csv (defaults to 'json') (default: json)
  -o, --out=<filename>                            output file; if not specified, stdout is used
      --jsonArray                                 output to a JSON array rather than one object per line
      --pretty                                    output JSON formatted to be human-readable
      --noHeaderLine                              export CSV data without a list of field names at the first line
      --jsonFormat=<type>                         the extended JSON format to output, either canonical or relaxed (defaults to 'relaxed') (default:
                                                  relaxed)

querying options:
  -q, --query=<json>                              query filter, as a JSON string, e.g., '{x:{$gt:1}}'
      --queryFile=<filename>                      path to a file containing a query filter (JSON)
  -k, --slaveOk                                   allow secondary reads if available (default true) (default: false)
      --readPreference=<string>|<json>            specify either a preference mode (e.g. 'nearest') or a preference json object (e.g. '{mode:
                                                  "nearest", tagSets: [{a: "b"}], maxStalenessSeconds: 123}')
      --forceTableScan                            force a table scan (do not use $snapshot)
      --skip=<count>                              number of documents to skip
      --limit=<count>                             limit the number of documents to export
      --sort=<json>                               sort order, as a JSON string, e.g. '{x:1}'
      --assertExists                              if specified, export fails if the collection does not exist (default: false)
  • 备份 monitor 库下 monitor_linux – JSON 格式
[dev@hessian01 ~]$ mongoexport --host 127.0.0.1 --port 20000 -u root --authenticationDatabase admin -d monitor -c monitor_linux -f _id,hostNames --type=json -o ./monitor_monitor_linux.json
  • 备份 monitor 库下 monitor_linux – CSV 格式
[dev@hessian01 ~]$ mongoexport --host 127.0.0.1 --port 20000 -u root --authenticationDatabase admin -d monitor -c monitor_linux -f _id,hostNames --type=csv -o ./monitor_monitor_linux.csv
  • 关键参数说明
  -h, --host=<hostname> 		# 远程连接的数据库地址
      --port=<port> 			# 远程连接的数据库端口
  -u, --username=<username> 	# 验证用户名
  -p, --password=<password> 	# 验证用户密码
      --authenticationDatabase=<database-name> 		# 验证库
  -d, --db=<database-name> 		# 要操作的数据库名
  -c, --collection=<collection-name> 				# 要操作的集合名
  -f, --fields=<field>[,<field>]*  					# 要操作的字段
      --fieldFile=<filename> 						# ???
      --type=<type> 			# 导出文件类型 {csv | json}
  -o, --out=<filename> 			# 导出文件位置 && 名称
  -q, --query=<json> 			# 查询条件
      --skip=<count> 			# 跳过指定数量的数据
      --limit=<count> 			# 导出时 -- 读取指定数量的数据记录
      --sort=<json>  			# 导出时 -- 对数据进行排序 e.g. '{x:1}'

mongodump – 全库备份

  • mongodump 帮助信息
[dev@hessian01 ~]$ mongodump --help
Usage:
  mongodump <options>

Export the content of a running server into .bson files.

Specify a database with -d and a collection with -c to only dump that database or collection.

See http://docs.mongodb.org/manual/reference/program/mongodump/ for more information.

general options:
      --help                                                print usage
      --version                                             print the tool version and exit

verbosity options:
  -v, --verbose=<level>                                     more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or
                                                            specify a numeric value, e.g. --verbose=N)
      --quiet                                               hide all log output

connection options:
  -h, --host=<hostname>                                     mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                                         server port (can also use --host hostname:port)

ssl options:
      --ssl                                                 connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                                the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                            the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>                        the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                               the .pem file containing the certificate revocation list
      --sslAllowInvalidCertificates                         bypass the validation for server certificates
      --sslAllowInvalidHostnames                            bypass the validation for server name
      --sslFIPSMode                                         use FIPS mode of the installed openssl library

authentication options:
  -u, --username=<username>                                 username for authentication
  -p, --password=<password>                                 password for authentication
      --authenticationDatabase=<database-name>              database that holds the user's credentials
      --authenticationMechanism=<mechanism>                 authentication mechanism to use

kerberos options:
      --gssapiServiceName=<service-name>                    service name to use when authenticating using GSSAPI/Kerberos ('mongodb' by default)
      --gssapiHostName=<host-name>                          hostname to use when authenticating using GSSAPI/Kerberos (remote server's address by
                                                            default)

namespace options:
  -d, --db=<database-name>                                  database to use
  -c, --collection=<collection-name>                        collection to use

uri options:
      --uri=mongodb-uri                                     mongodb uri connection string

query options:
  -q, --query=                                              query filter, as a v2 Extended JSON string, e.g., '{"x":{"$gt":1}}'
      --queryFile=                                          path to a file containing a query filter (v2 Extended JSON)
      --readPreference=<string>|<json>                      specify either a preference mode (e.g. 'nearest') or a preference json object (e.g.
                                                            '{mode: "nearest", tagSets: [{a: "b"}], maxStalenessSeconds: 123}')
      --forceTableScan                                      force a table scan

output options:
  -o, --out=<directory-path>                                output directory, or '-' for stdout (defaults to 'dump')
      --gzip                                                compress archive our collection output with Gzip
      --oplog                                               use oplog for taking a point-in-time snapshot
      --archive=<file-path>                                 dump as an archive to the specified path. If flag is specified without a value, archive is
                                                            written to stdout
      --dumpDbUsersAndRoles                                 dump user and role definitions for the specified database
      --excludeCollection=<collection-name>                 collection to exclude from the dump (may be specified multiple times to exclude additional
                                                            collections)
      --excludeCollectionsWithPrefix=<collection-prefix>    exclude all collections from the dump that have the given prefix (may be specified
                                                            multiple times to exclude additional prefixes)
  -j, --numParallelCollections=                             number of collections to dump in parallel (4 by default) (default: 4)
      --viewsAsCollections                                  dump views as normal collections with their produced data, omitting standard collections
  • 备份 monitor 库
[dev@hessian01 ~]$ mongodump --host 127.0.0.1 --port 20000 -u root --authenticationDatabase admin -d monitor -o ./mongo_dump/
  • 关键参数说明
  -h, --host=<hostname> 			# 远程连接 mongo 地址
      --port=<port>  				# 远程连接 mongo 端口
  -u, --username=<username> 		# 验证 mongo 用户名
  -p, --password=<password> 		# 验证 mongo 密码
      --authenticationDatabase=<database-name> 			# 用户登录验证库
  -d, --db=<database-name> 			# 需要备份的数据库
  -c, --collection=<collection-name>  					# 数据库中 collection
  -o, --out=<directory-path> 		# 备份后文件位置

MongoDB 数据还原

mongoimport – 指定 collection 还原

  • mongoimport 帮助信息
[dev@hessian01 ~]$ mongoimport --help
Usage:
  mongoimport <options> <file>

Import CSV, TSV or JSON data into MongoDB. If no file is provided, mongoimport reads from stdin.

See http://docs.mongodb.org/manual/reference/program/mongoimport/ for more information.

general options:
      --help                                      print usage
      --version                                   print the tool version and exit

verbosity options:
  -v, --verbose=<level>                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or specify a
                                                  numeric value, e.g. --verbose=N)
      --quiet                                     hide all log output

connection options:
  -h, --host=<hostname>                           mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                               server port (can also use --host hostname:port)

ssl options:
      --ssl                                       connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                      the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                  the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>              the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                     the .pem file containing the certificate revocation list
      --sslAllowInvalidCertificates               bypass the validation for server certificates
      --sslAllowInvalidHostnames                  bypass the validation for server name
      --sslFIPSMode                               use FIPS mode of the installed openssl library

authentication options:
  -u, --username=<username>                       username for authentication
  -p, --password=<password>                       password for authentication
      --authenticationDatabase=<database-name>    database that holds the user's credentials
      --authenticationMechanism=<mechanism>       authentication mechanism to use

kerberos options:
      --gssapiServiceName=<service-name>          service name to use when authenticating using GSSAPI/Kerberos ('mongodb' by default)
      --gssapiHostName=<host-name>                hostname to use when authenticating using GSSAPI/Kerberos (remote server's address by default)

namespace options:
  -d, --db=<database-name>                        database to use
  -c, --collection=<collection-name>              collection to use

uri options:
      --uri=mongodb-uri                           mongodb uri connection string

input options:
  -f, --fields=<field>[,<field>]*                 comma separated list of fields, e.g. -f name,age
      --fieldFile=<filename>                      file with field names - 1 per line
      --file=<filename>                           file to import from; if not specified, stdin is used
      --headerline                                use first line in input source as the field list (CSV and TSV only)
      --jsonArray                                 treat input source as a JSON array
      --parseGrace=<grace>                        controls behavior when type coercion fails - one of: autoCast, skipField, skipRow, stop (defaults to
                                                  'stop') (default: stop)
      --type=<type>                               input format to import: json, csv, or tsv (defaults to 'json') (default: json)
      --columnsHaveTypes                          indicated that the field list (from --fields, --fieldsFile, or --headerline) specifies types; They
                                                  must be in the form of '<colName>.<type>(<arg>)'. The type can be one of: auto, binary, bool, date,
                                                  date_go, date_ms, date_oracle, double, int32, int64, string. For each of the date types, the
                                                  argument is a datetime layout string. For the binary type, the argument can be one of: base32,
                                                  base64, hex. All other types take an empty argument. Only valid for CSV and TSV imports. e.g.
                                                  zipcode.string(), thumbnail.binary(base64)
      --legacy                                    use the legacy extended JSON format (defaults to 'false') (default: false)

ingest options:
      --drop                                      drop collection before inserting documents
      --ignoreBlanks                              ignore fields with empty values in CSV and TSV
      --maintainInsertionOrder                    insert the documents in the order of their appearance in the input source. By default the insertions
                                                  will be performed in an arbitrary order. Setting this flag also enables the behavior of
                                                  --stopOnError and restricts NumInsertionWorkers to 1.
  -j, --numInsertionWorkers=<number>              number of insert operations to run concurrently (defaults to 1) (default: 1)
      --stopOnError                               halt after encountering any error during importing. By default, mongoimport will attempt to continue
                                                  through document validation and DuplicateKey errors, but with this option enabled, the tool will
                                                  stop instead. A small number of documents may be inserted after encountering an error even with this
                                                  option enabled; use --maintainInsertionOrder to halt immediately after an error
      --mode=[insert|upsert|merge]                insert: insert only. upsert: insert or replace existing documents. merge: insert or modify existing
                                                  documents. defaults to insert
      --upsertFields=<field>[,<field>]*           comma-separated fields for the query part when --mode is set to upsert or merge
      --writeConcern=<write-concern-specifier>    write concern options e.g. --writeConcern majority, --writeConcern '{w: 3, wtimeout: 500, fsync:
                                                  true, j: true}'
      --bypassDocumentValidation                  bypass document validation
  • 还原 monitor 库下 monitor_linux – JSON 格式
[dev@hessian01 ~]$ mongoimport --host 127.0.0.1 --port 20000 -u root --authenticationDatabase admin -d monitor -c monitor_linux -f _id,hostNames --type=json --file ./monitor_monitor_linux.json
  • 还原 monitor 库下 monitor_linux – CSV 格式
[dev@hessian01 ~]$ mongoimport --host 127.0.0.1 --port 20000 -u root --authenticationDatabase admin -d monitor -c monitor_linux -f _id,hostNames --type=csv --file ./monitor_monitor_linux.csv
  • 关键参数说明
  -h, --host=<hostname> 		# 远程连接的数据库地址
      --port=<port> 			# 远程连接的数据库端口
  -u, --username=<username> 	# 远程数据库 -- 用户名
  -p, --password=<password> 	# 远程数据库 -- 密码
      --authenticationDatabase=<database-name> 		# 远程数据库 -- 验证库
  -d, --db=<database-name> 		# 还原的数据库名
  -c, --collection=<collection-name> 				# 还原的集合名
  -f, --fields=<field>[,<field>]* 					# 导入集合字段
      --file=<filename> 		# 导入文件名称
      --type=<type> 			# 导入文件类型 {csv | json | tsv}

mongorestore – 全库还原

  • mongorestore 帮助信息
[dev@hessian01 ~]$ mongorestore --help
Usage:
  mongorestore <options> <directory or file to restore>

Restore backups generated with mongodump to a running server.

Specify a database with -d to restore a single database from the target directory,
or use -d and -c to restore a single collection from a single .bson file.

See http://docs.mongodb.org/manual/reference/program/mongorestore/ for more information.

general options:
      --help                                                print usage
      --version                                             print the tool version and exit

verbosity options:
  -v, --verbose=<level>                                     more detailed log output (include multiple times for more verbosity, e.g. -vvvvv, or
                                                            specify a numeric value, e.g. --verbose=N)
      --quiet                                               hide all log output

connection options:
  -h, --host=<hostname>                                     mongodb host to connect to (setname/host1,host2 for replica sets)
      --port=<port>                                         server port (can also use --host hostname:port)

ssl options:
      --ssl                                                 connect to a mongod or mongos that has ssl enabled
      --sslCAFile=<filename>                                the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=<filename>                            the .pem file containing the certificate and key
      --sslPEMKeyPassword=<password>                        the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=<filename>                               the .pem file containing the certificate revocation list
      --sslAllowInvalidCertificates                         bypass the validation for server certificates
      --sslAllowInvalidHostnames                            bypass the validation for server name
      --sslFIPSMode                                         use FIPS mode of the installed openssl library

authentication options:
  -u, --username=<username>                                 username for authentication
  -p, --password=<password>                                 password for authentication
      --authenticationDatabase=<database-name>              database that holds the user's credentials
      --authenticationMechanism=<mechanism>                 authentication mechanism to use

kerberos options:
      --gssapiServiceName=<service-name>                    service name to use when authenticating using GSSAPI/Kerberos ('mongodb' by default)
      --gssapiHostName=<host-name>                          hostname to use when authenticating using GSSAPI/Kerberos (remote server's address by
                                                            default)

uri options:
      --uri=mongodb-uri                                     mongodb uri connection string

namespace options:
  -d, --db=<database-name>                                  database to use when restoring from a BSON file
  -c, --collection=<collection-name>                        collection to use when restoring from a BSON file
      --excludeCollection=<collection-name>                 DEPRECATED; collection to skip over during restore (may be specified multiple times to
                                                            exclude additional collections)
      --excludeCollectionsWithPrefix=<collection-prefix>    DEPRECATED; collections to skip over during restore that have the given prefix (may be
                                                            specified multiple times to exclude additional prefixes)
      --nsExclude=<namespace-pattern>                       exclude matching namespaces
      --nsInclude=<namespace-pattern>                       include matching namespaces
      --nsFrom=<namespace-pattern>                          rename matching namespaces, must have matching nsTo
      --nsTo=<namespace-pattern>                            rename matched namespaces, must have matching nsFrom

input options:
      --objcheck                                            validate all objects before inserting
      --oplogReplay                                         replay oplog for point-in-time restore
      --oplogLimit=<seconds>[:ordinal]                      only include oplog entries before the provided Timestamp
      --oplogFile=<filename>                                oplog file to use for replay of oplog
      --archive=<filename>                                  restore dump from the specified archive file.  If flag is specified without a value,
                                                            archive is read from stdin
      --restoreDbUsersAndRoles                              restore user and role definitions for the given database
      --dir=<directory-name>                                input directory, use '-' for stdin
      --gzip                                                decompress gzipped input

restore options:
      --drop                                                drop each collection before import
      --dryRun                                              view summary without importing anything. recommended with verbosity
      --writeConcern=<write-concern>                        write concern options e.g. --writeConcern majority, --writeConcern '{w: 3, wtimeout: 500,
                                                            fsync: true, j: true}'
      --noIndexRestore                                      don't restore indexes
      --noOptionsRestore                                    don't restore collection options
      --keepIndexVersion                                    don't update index version
      --maintainInsertionOrder                              restore the documents in the order of their appearance in the input source. By default the
                                                            insertions will be performed in an arbitrary order. Setting this flag also enables the
                                                            behavior of --stopOnError and restricts NumInsertionWorkersPerCollection to 1.
  -j, --numParallelCollections=                             number of collections to restore in parallel (4 by default) (default: 4)
      --numInsertionWorkersPerCollection=                   number of insert operations to run concurrently per collection (1 by default) (default: 1)
      --stopOnError                                         halt after encountering any error during insertion. By default, mongorestore will attempt
                                                            to continue through document validation and DuplicateKey errors, but with this option
                                                            enabled, the tool will stop instead. A small number of documents may be inserted after
                                                            encountering an error even with this option enabled; use --maintainInsertionOrder to halt
                                                            immediately after an error
      --bypassDocumentValidation                            bypass document validation
      --preserveUUID                                        preserve original collection UUIDs (off by default, requires drop)
  • 还原 monitor 库
[dev@hessian01 ~]$ mongorestore --host 127.0.0.1 --port 20000 -u root --authenticationDatabase admin -d monitor --dir ./mongo_dump/monitor
  • 关键参数说明
  -h, --host=<hostname> 			# 远程连接 mongo 地址
      --port=<port>  				# 远程连接 mongo 端口
  -u, --username=<username> 		# 验证 mongo 用户名
  -p, --password=<password> 		# 验证 mongo 密码
      --authenticationDatabase=<database-name> 			# 用户登录验证库
  -d, --db=<database-name> 			# 需要备份的数据库
  -c, --collection=<collection-name>  					# 数据库中 collection
      --dir=<directory-name> 		# 需要还原的文件位置

参考 Blog :

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值