MongoDB学习11_MongoDB 基础(五)备份还原与导出导入

来源:互联网 发布:软件编码设计 编辑:程序博客网 时间:2024/05/16 11:06

参考官方文档 : MongoDB Backup Methods


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

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


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

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

2. 使用mongodump和mongorestore

3. 使用mongoimport 和 mongoexport




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

1.1 备份

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

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. >db.fsyncLock()  
b. 打包压缩整个数据库目录(也可以打包部分数据库),作为备份:
[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# tar -cvzf /root/mongodb_20150505.tar.gz /var/lib/mongo  
c. 在mongodb中执行db.fsyncUnlock()解锁,备份步骤完成!~

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. >db.fsyncUnlock()  


1.1 还原

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

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. >use admin  
  2. >db.shutdownServer()  

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

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# rm -rf /var/lib/mongo/*  
c. 解压备份的文件到根目录下,相当于还原:
[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# tar -xvzf /root/mongodb_20150505.tar.gz -C /  
d. 如果启动不了服务,先删除文件mongod.lock:

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# rm -f /var/lib/mongo/mongod.lock  
e. 启动服务,正常访问。

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. [root@localhost ~]# service mongod start  




2. 使用mongodump和mongorestore

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

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. mongodump  
  2. mongorestore /root/dump  

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



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

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. mongorestore --db test /root/dump/test  
还可以指定输出路径,使用计算机名:

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. mongodump --host localhost.localdomain --port 27017 --out /root/mongodump-2015-05-05  
  2. mongorestore --port 27017 --db test /root/mongodump-2015-05-05/test  
远程备份时指定用户名密码(这个没尝试,参考官方例子):

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. mongodump --host mongodb1.example.net --port 3017 --username user --password pass --out /opt/backup/mongodump-2013-10-24  
  2. mongorestore --host mongodb1.example.net --port 3017 --username user --password pass /opt/backup/mongodump-2013-10-24  

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

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. # mongorestore --help  
  2.   
  3.   
  4. general options:  
  5.       --help                              print usage  
  6.       --version                           print the tool version and exit  
  7.   
  8. verbosity options:  
  9.   -v, --verbose                           more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)  
  10.       --quiet                             hide all log output  
  11.   
  12. connection options:  
  13.   -h, --host=                             mongodb host to connect to (setname/host1,host2 for replica sets)  
  14.       --port=                             server port (can also use --host hostname:port)  
  15.   
  16. ssl options:  
  17.       --ssl                               connect to a mongod or mongos that has ssl enabled  
  18.       --sslCAFile=                        the .pem file containing the root certificate chain from  
  19.                                           the certificate authority  
  20.       --sslPEMKeyFile=                    the .pem file containing the certificate and key  
  21.       --sslPEMKeyPassword=                the password to decrypt the sslPEMKeyFile, if necessary  
  22.       --sslCRLFile=                       the .pem file containing the certificate revocation list  
  23.       --sslAllowInvalidCertificates       bypass the validation for server certificates  
  24.       --sslAllowInvalidHostnames          bypass the validation for server name  
  25.       --sslFIPSMode                       use FIPS mode of the installed openssl library  
  26.   
  27. authentication options:  
  28.   -u, --username=                         username for authentication  
  29.   -p, --password=                         password for authentication  
  30.       --authenticationDatabase=           database that holds the user's credentials  
  31.       --authenticationMechanism=          authentication mechanism to use  
  32.   
  33. namespace options:  
  34.   -d, --db=                               database to use  
  35.   -c, --collection=                       collection to use  
  36.   
  37. input options:  
  38.       --objcheck                          validate all objects before inserting  
  39.       --oplogReplay                       replay oplog for point-in-time restore  
  40.       --oplogLimit=                       only include oplog entries before the provided Timestamp(seconds[:ordinal])  
  41.       --restoreDbUsersAndRoles            restore user and role definitions for the given database  
  42.       --dir=                              input directory, use '-' for stdin  
  43.   
  44. restore options:  
  45.       --drop                              drop each collection before import  
  46.       --writeConcern=                     write concern options e.g. --writeConcern majority,  
  47.                                           --writeConcern '{w: 3, wtimeout: 500, fsync: true, j:true}' (defaults to 'majority')  
  48.       --noIndexRestore                    don't restore indexes  
  49.       --noOptionsRestore                  don't restore collection options  
  50.       --keepIndexVersion                  don't update index version  
  51.       --maintainInsertionOrder            preserve order of documents during restoration  
  52.   -j, --numParallelCollections=           number of collections to restore in parallel (4 by default)  
  53.       --numInsertionWorkersPerCollection= number of insert operations to run concurrently per collection (1 by default)  
  54.       --stopOnError                       stop restoring if an error is encountered on insert (off bydefault)  



3. 使用mongoimport 和 mongoexport

3.1 mongoexport导出

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. --type: 为json 或 csv  
  2. --fields: 选择导出的列  
  3.   
  4.   
  5. #导出列{_id,id,size}为csv的格式  
  6. mongoexport --db test --collection tab --type=csv --fields _id,id,size --out /root/test_tab.csv  
  7.   
  8. #导出json格式  
  9. mongoexport --db test --collection tab --type=json --out /root/test_tab.json  
  10.   
  11. #输出到shell中,查询id=2 并按name升序输出  
  12. mongoexport --db test --collection tab --query '{"id": 2}' --sort '{"name": 1}'  
  13.   
  14. #查询导出  
  15. mongoexport --db test --collection tab --type=csv --query '{"id": 2}' --fields _id,id --out /root/test_tab.csv  
  16.   
  17. #简写选项[--db]和[--collection],使用跳过和限制函数输出  
  18. mongoexport -d test -c tab --sort '{"name": -1}' --limit 2 --skip 2 --out /root/test_tab.json  
  19.   
  20.   
  21. #若是远程,需要添加参数:host,port,username,password  
  22. --host servername_or_ip --port 37017 --username user --password pass  


查看帮助:mongoexport --help

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. general options:  
  2.       --help                         print usage  
  3.       --version                      print the tool version and exit  
  4.   
  5. verbosity options:  
  6.   -v, --verbose                      more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)  
  7.       --quiet                        hide all log output  
  8.   
  9. connection options:  
  10.   -h, --host=                        mongodb host to connect to (setname/host1,host2 for replica sets)  
  11.       --port=                        server port (can also use --host hostname:port)  
  12.   
  13. ssl options:  
  14.       --ssl                          connect to a mongod or mongos that has ssl enabled  
  15.       --sslCAFile=                   the .pem file containing the root certificate chain from the certificate authority  
  16.       --sslPEMKeyFile=               the .pem file containing the certificate and key  
  17.       --sslPEMKeyPassword=           the password to decrypt the sslPEMKeyFile, if necessary  
  18.       --sslCRLFile=                  the .pem file containing the certificate revocation list  
  19.       --sslAllowInvalidCertificates  bypass the validation for server certificates  
  20.       --sslAllowInvalidHostnames     bypass the validation for server name  
  21.       --sslFIPSMode                  use FIPS mode of the installed openssl library  
  22.   
  23. authentication options:  
  24.   -u, --username=                    username for authentication  
  25.   -p, --password=                    password for authentication  
  26.       --authenticationDatabase=      database that holds the user's credentials  
  27.       --authenticationMechanism=     authentication mechanism to use  
  28.   
  29. namespace options:  
  30.   -d, --db=                          database to use  
  31.   -c, --collection=                  collection to use  
  32.   
  33. output options:  
  34.   -f, --fields=                      comma separated list of field names (required for exporting CSV) e.g. -f "name,age"  
  35.       --fieldFile=                   file with field names - 1 per line  
  36.       --type=                        the output format, either json or csv (defaults to 'json')  
  37.   -o, --out=                         output file; if not specified, stdout is used  
  38.       --jsonArray                    output to a JSON array rather than one object per line  
  39.       --pretty                       output JSON formatted to be human-readable  
  40.   
  41. querying options:  
  42.   -q, --query=                       query filter, as a JSON string, e.g., '{x:{$gt:1}}'  
  43.   -k, --slaveOk                      allow secondary reads if available (default true)  
  44.       --forceTableScan               force a table scan (do not use $snapshot)  
  45.       --skip=                        number of documents to skip  
  46.       --limit=                       limit the number of documents to export  
  47.       --sort=                        sort order, as a JSON string, e.g. '{x:1}'  



3.2 mongoimport 导入

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. #列"_id"也会导入,注意重复键  
  2. mongoimport --db mydb --collection tab --file /root/test_tab.json  
  3.   
  4. mongoimport --db mydb --collection tab --type csv --headerline --file /root/test_tab.csv  
  5.   
  6.   
  7. #若是远程,需要添加参数:host,port,username,password  
  8. --host servername_or_ip --port 37017 --username user --password pass  

查看帮助: mongoimport --help

[plain] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. general options:  
  2.       --help                         print usage  
  3.       --version                      print the tool version and exit  
  4.   
  5. verbosity options:  
  6.   -v, --verbose                      more detailed log output (include multiple times for more verbosity, e.g. -vvvvv)  
  7.       --quiet                        hide all log output  
  8.   
  9. connection options:  
  10.   -h, --host=                        mongodb host to connect to (setname/host1,host2 for replica sets)  
  11.       --port=                        server port (can also use --host hostname:port)  
  12.   
  13. ssl options:  
  14.       --ssl                          connect to a mongod or mongos that has ssl enabled  
  15.       --sslCAFile=                   the .pem file containing the root certificate chain from the certificate authority  
  16.       --sslPEMKeyFile=               the .pem file containing the certificate and key  
  17.       --sslPEMKeyPassword=           the password to decrypt the sslPEMKeyFile, if necessary  
  18.       --sslCRLFile=                  the .pem file containing the certificate revocation list  
  19.       --sslAllowInvalidCertificates  bypass the validation for server certificates  
  20.       --sslAllowInvalidHostnames     bypass the validation for server name  
  21.       --sslFIPSMode                  use FIPS mode of the installed openssl library  
  22.   
  23. authentication options:  
  24.   -u, --username=                    username for authentication  
  25.   -p, --password=                    password for authentication  
  26.       --authenticationDatabase=      database that holds the user's credentials  
  27.       --authenticationMechanism=     authentication mechanism to use  
  28.   
  29. namespace options:  
  30.   -d, --db=                          database to use  
  31.   -c, --collection=                  collection to use  
  32.   
  33. input options:  
  34.   -f, --fields=                      comma separated list of field names, e.g. -f name,age  
  35.       --fieldFile=                   file with field names - 1 per line  
  36.       --file=                        file to import from; if not specified, stdin is used  
  37.       --headerline                   use first line in input source as the field list (CSV and TSV  
  38.                                      only)  
  39.       --jsonArray                    treat input source as a JSON array  
  40.       --type=                        input format to import: json, csv, or tsv (defaults to 'json')  
  41.   
  42. ingest options:  
  43.       --drop                         drop collection before inserting documents  
  44.       --ignoreBlanks                 ignore fields with empty values in CSV and TSV  
  45.       --maintainInsertionOrder       insert documents in the order of their appearance in the input source  
  46.   -j, --numInsertionWorkers=         number of insert operations to run concurrently (defaults to 1)  
  47.       --stopOnError                  stop importing at first insert/upsert error  
  48.       --upsert                       insert or update objects that already exist  
  49.       --upsertFields=                comma-separated fields for the query part of the upsert  
  50.       --writeConcern=                write concern options e.g. --writeConcern majority,  
  51.                                      --writeConcern '{w: 3, wtimeout: 500, fsync: true, j: true}'  
  52.                                      (defaults to 'majority')  


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


原文来自:http://blog.csdn.net/kk185800961/article/details/45541893

0 0
原创粉丝点击