MongoDB 基础(五)备份还原与导出导入

参考官方文档 : MongoDB Backup Methods

原本使用操作系统的快照进行备份还原,备份成功后,还原没有成功(参考:Backup and Restore with Filesystem Snapshots

所以这个方法就先不记录到这里了。

当前测试以下?种备份还原方法(个人初学理解):

1. 使用拷贝和替换数据库文件进行备份还原

2. 使用mongodump和mongorestore

3. 使用mongoimport 和 mongoexport

1. 使用拷贝和替换数据库文件进行备份还原(有些危险又不好)

1.1 备份

a. 在mongodb中执行db.fsyncLock(),刷新数据写入磁盘并锁住整个实例:

>db.fsyncLock()

b. 打包压缩整个数据库目录(也可以打包部分数据库),作为备份:

[[email protected] ~]# tar -cvzf /root/mongodb_20150505.tar.gz /var/lib/mongo

c. 在mongodb中执行db.fsyncUnlock()解锁,备份步骤完成!~

>db.fsyncUnlock()

1.1 还原

a. 在mongodb中关闭服务(或者在操作系统层面关闭mongod服务):

>use admin
>db.shutdownServer()

b. 将mongo数据文件删除!注意确认备份存在且正常!~否则回天无力!

[[email protected] ~]# rm -rf /var/lib/mongo/*

c. 解压备份的文件到根目录下,相当于还原:

[[email protected] ~]# tar -xvzf /root/mongodb_20150505.tar.gz -C /

d. 如果启动不了服务,先删除文件mongod.lock:

[[email protected] ~]# rm -f /var/lib/mongo/mongod.lock

e. 启动服务,正常访问。

[[email protected] ~]# service mongod start

2. 使用mongodump和mongorestore

a. 简单备份还原本地数据库的的方法,备份所有及还原所有:

mongodump
mongorestore /root/dump

备份完成后在当前目录将生成一个文件夹”dump“:

b. 还原单个数据库时,指定要还原的数据库及其备份目录:

mongorestore --db test /root/dump/test

还可以指定输出路径,使用计算机名:

mongodump --host localhost.localdomain --port 27017 --out /root/mongodump-2015-05-05
mongorestore --port 27017 --db test /root/mongodump-2015-05-05/test

远程备份时指定用户名密码(这个没尝试,参考官方例子):

mongodump --host mongodb1.example.net --port 3017 --username user --password pass --out /opt/backup/mongodump-2013-10-24
mongorestore --host mongodb1.example.net --port 3017 --username user --password pass /opt/backup/mongodump-2013-10-24

c. 更多参考:执行 #mongorestore --help

# mongorestore --help

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

verbosity options:
  -v, --verbose                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)
      --quiet                             hide all log output

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

ssl options:
      --ssl                               connect to a mongod or mongos that has ssl enabled
      --sslCAFile=                        the .pem file containing the root certificate chain from
                                          the certificate authority
      --sslPEMKeyFile=                    the .pem file containing the certificate and key
      --sslPEMKeyPassword=                the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=                       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 for authentication
  -p, --password=                         password for authentication
      --authenticationDatabase=           database that holds the user's credentials
      --authenticationMechanism=          authentication mechanism to use

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

input options:
      --objcheck                          validate all objects before inserting
      --oplogReplay                       replay oplog for point-in-time restore
      --oplogLimit=                       only include oplog entries before the provided Timestamp(seconds[:ordinal])
      --restoreDbUsersAndRoles            restore user and role definitions for the given database
      --dir=                              input directory, use '-' for stdin

restore options:
      --drop                              drop each collection before import
      --writeConcern=                     write concern options e.g. --writeConcern majority,
                                          --writeConcern '{w: 3, wtimeout: 500, fsync: true, j:true}' (defaults to 'majority')
      --noIndexRestore                    don't restore indexes
      --noOptionsRestore                  don't restore collection options
      --keepIndexVersion                  don't update index version
      --maintainInsertionOrder            preserve order of documents during restoration
  -j, --numParallelCollections=           number of collections to restore in parallel (4 by default)
      --numInsertionWorkersPerCollection= number of insert operations to run concurrently per collection (1 by default)
      --stopOnError                       stop restoring if an error is encountered on insert (off bydefault)

3. 使用mongoimport 和 mongoexport

3.1 mongoexport导出

--type: 为json 或 csv
--fields: 选择导出的列

#导出列{_id,id,size}为csv的格式
mongoexport --db test --collection tab --type=csv --fields _id,id,size --out /root/test_tab.csv

#导出json格式
mongoexport --db test --collection tab --type=json --out /root/test_tab.json

#输出到shell中,查询id=2 并按name升序输出
mongoexport --db test --collection tab --query '{"id": 2}' --sort '{"name": 1}'

#查询导出
mongoexport --db test --collection tab --type=csv --query '{"id": 2}' --fields _id,id --out /root/test_tab.csv

#简写选项[--db]和[--collection],使用跳过和限制函数输出
mongoexport -d test -c tab --sort '{"name": -1}' --limit 2 --skip 2 --out /root/test_tab.json

#若是远程,需要添加参数:host,port,username,password
--host servername_or_ip --port 37017 --username user --password pass

查看帮助:mongoexport --help

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

verbosity options:
  -v, --verbose                      more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)
      --quiet                        hide all log output

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

ssl options:
      --ssl                          connect to a mongod or mongos that has ssl enabled
      --sslCAFile=                   the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=               the .pem file containing the certificate and key
      --sslPEMKeyPassword=           the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=                  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 for authentication
  -p, --password=                    password for authentication
      --authenticationDatabase=      database that holds the user's credentials
      --authenticationMechanism=     authentication mechanism to use

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

output options:
  -f, --fields=                      comma separated list of field names (required for exporting CSV) e.g. -f "name,age"
      --fieldFile=                   file with field names - 1 per line
      --type=                        the output format, either json or csv (defaults to 'json')
  -o, --out=                         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

querying options:
  -q, --query=                       query filter, as a JSON string, e.g., '{x:{$gt:1}}'
  -k, --slaveOk                      allow secondary reads if available (default true)
      --forceTableScan               force a table scan (do not use $snapshot)
      --skip=                        number of documents to skip
      --limit=                       limit the number of documents to export
      --sort=                        sort order, as a JSON string, e.g. '{x:1}'

3.2 mongoimport 导入

#列"_id"也会导入,注意重复键
mongoimport --db mydb --collection tab --file /root/test_tab.json

mongoimport --db mydb --collection tab --type csv --headerline --file /root/test_tab.csv

#若是远程,需要添加参数:host,port,username,password
--host servername_or_ip --port 37017 --username user --password pass

查看帮助:mongoimport --help

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

verbosity options:
  -v, --verbose                      more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)
      --quiet                        hide all log output

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

ssl options:
      --ssl                          connect to a mongod or mongos that has ssl enabled
      --sslCAFile=                   the .pem file containing the root certificate chain from the certificate authority
      --sslPEMKeyFile=               the .pem file containing the certificate and key
      --sslPEMKeyPassword=           the password to decrypt the sslPEMKeyFile, if necessary
      --sslCRLFile=                  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 for authentication
  -p, --password=                    password for authentication
      --authenticationDatabase=      database that holds the user's credentials
      --authenticationMechanism=     authentication mechanism to use

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

input options:
  -f, --fields=                      comma separated list of field names, e.g. -f name,age
      --fieldFile=                   file with field names - 1 per line
      --file=                        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
      --type=                        input format to import: json, csv, or tsv (defaults to 'json')

ingest options:
      --drop                         drop collection before inserting documents
      --ignoreBlanks                 ignore fields with empty values in CSV and TSV
      --maintainInsertionOrder       insert documents in the order of their appearance in the input source
  -j, --numInsertionWorkers=         number of insert operations to run concurrently (defaults to 1)
      --stopOnError                  stop importing at first insert/upsert error
      --upsert                       insert or update objects that already exist
      --upsertFields=                comma-separated fields for the query part of the upsert
      --writeConcern=                write concern options e.g. --writeConcern majority,
                                     --writeConcern '{w: 3, wtimeout: 500, fsync: true, j: true}'
                                     (defaults to 'majority')

由于没有做复制,复制中的备份到时再测试记录吧!~

时间: 2024-08-02 09:21:19

MongoDB 基础(五)备份还原与导出导入的相关文章

【Oracle】OCR的备份和恢复之导出导入

使用导出导入进行OCR的备份和恢复: 在对集群做调整前,如:增删节点等操作前,应该对OCR进行一次备份,可以使用export备份到指定文件. 实验环境: OS:OEL5.6 RAC:10.2.0.1.0 (1)关闭所有节点的CRS 节点1: [[email protected] crsd]# crsctl stop crs Stopping resources. Successfully stopped CRS resources Stopping CSSD. Shutting down CSS

MongoDB基本操作、备份还原及用户管理

今日趁周末得空,将近日在学习的MongoDB数据库常用命令作以下整理,方便工作中查看 MongoDB的逻辑结构主要由文档.集合和数据库三部分组成.其中文档是MongoDB的核心概念,它是MongoDB逻辑存储的最小单元,相当于关系型数据库中的一行记录,多个文档组成集合,集合相当于关系型数据库中的表,多个集合组成数据库. SQL术语 说明 MongoDB术语 说明 database 数据库 database 数据库 table 数据库表 collection 集合 row 记录 document

4、MongoDB学习之备份还原

一.MongoDB备份 1.MongoDB整库备份 备份数据使用下面的命令 mongodump -h dbhost -d dbname -o dbdirectory 备份user数据库 [[email protected] bin]# ./mongodump -h127.0.0.1 -d user -o /home/ [[email protected] bin]# ls /home/user/ b3.bson  b3.metadata.json  c1.bson  c1.metadata.js

mongodb 数据库操作--备份 还原 导出 导入

一,mongodump备份数据库 1,常用命令格 1 mongodump -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -o 文件存在路径 如果没有用户谁,可以去掉-u和-p. 如果导出本机的数据库,可以去掉-h. 如果是默认端口,可以去掉--port. 如果想导出所有数据库,可以去掉-d. 2,导出所有数据库 1 2 3 4 5 6 7 8 9 10 [[email protected] mongodb]# mongodump -h 127.0.0.1 -o /hom

mongodb数据库操作--备份 还原 导出 导入

首先数据库备份: mongodump -h IP --port 端口 -u 用户名 -p 密码 -d 数据库 -o 文件存在路径  mongodump -h 127.0.0.1 -u admin -p xxx -d blog -o '/home/timeless/桌面/mongodump' --authenticationDatabase admin 注意  --authenticationDatabase  参数制定认证数据库   否则会提示错误: Failed: error connecti

MongoDB备份恢复与导出导入

说明:本文所有操作均在win7下的MongoDB3.4.4版本中进行. 一.备份与恢复 1. 备份: mongodump -h IP --port 端口 -u 用户名 -p 密码 -d数据库 -o 文件路径 (将使用某个用户账号将某个mongodb服务器上的某个数据库备份到某个路径下) 如果无需指定用户,可以去掉-u和-p:如果导出本机的数据库,可以去掉-h:如果是默认端口,可以去掉--port: 如果想导出所有数据库,可以去掉-d.如果只想备份某个集合,应在"-d 数据库"后添加&q

python | MongoDB备份恢复与导出导入

说明:本文所有操作均在win7下的MongoDB3.4.4版本中进行. 一.备份与恢复 1. 备份: mongodump -h IP --port 端口 -u 用户名 -p 密码 -d数据库 -o 文件路径 (将使用某个用户账号将某个mongodb服务器上的某个数据库备份到某个路径下) 如果无需指定用户,可以去掉-u和-p:如果导出本机的数据库,可以去掉-h:如果是默认端口,可以去掉--port: 如果想导出所有数据库,可以去掉-d.如果只想备份某个集合,应在”-d 数据库”后添加”-c 集合名

Oracle数据库备份 expdp/impdp导出导入命令

使用EXPDP和IMPDP时应该注意的事项: EXP和IMP是客户端工具程序,它们既可以在客户端使用,也可以在服务端使用. EXPDP和IMPDP是服务端的工具程序,他们只能在ORACLE服务端使用,不能在客户端使用. IMP只适用于EXP导出的文件,不适用于EXPDP导出文件:IMPDP只适用于EXPDP导出的文件,而不适用于EXP导出文件. 一.创建逻辑目录,该命令不会在操作系统创建真正的目录,最好以system等管理员创建. 在D 盘新建文件路径d:\test\dump,然后在sql运行

MongoDB整库备份与还原以及单个collection备份、恢复方法

mongodb数据库维护离不开必要的备份.恢复操作,而且一般不会出错,所以我们在使用的时候大部分时候使用备份和恢复操作就可以了 mongodump.exe备份的原理是通过一次查询获取当前服务器快照,并将快照写入磁盘中,因此这种方式保存的也不是实时的,因为在获取快照后,服务器还会有数据写入,为了保证备份的安全,同样我们还是可以利用fsync锁使服务器数据暂时写入缓存中. 高效开源数据库(mongodb)下载地址:http://www.jb51.net/softs/41751.html 备份前的检查