Reference Official Documentation: MongoDB Backup Methods
A backup restore was made using a snapshot of the operating system, and the restore did not succeed after the backup was successful (refer to: Backup and restore with Filesystem snapshots)
So this method is not recorded here first.
Current Test below? Method of Backup restore (personal beginner understanding):
1. Use copy and replace database files for backup and restore
2. Using Mongodump and Mongorestore
3. Using Mongoimport and Mongoexport
1. Use copy and replace database files for backup and restore (some dangerous and bad)
1.1 Backup
A. Execute Db.fsynclock () in MongoDB, flush data to disk and lock the entire instance:
>db.fsynclock ()
B. Packaging compresses the entire database directory (you can also package some databases) as a backup:
[Email protected] ~]# Tar-cvzf/root/mongodb_20150505.tar.gz/var/lib/mongo
C. Perform db.fsyncunlock () unlock in MongoDB, backup step complete! ~
>db.fsyncunlock ()
1.1 Restore
A. Close the service in MongoDB (or shut down the Mongod service at the operating system level):
>use Admin>db.shutdownserver ()
B. Delete the MONGO data file! Note that the backup exists and is OK! ~ Otherwise the helpless!
[Email protected] ~]# rm-rf/var/lib/mongo/*
C. Extract the backed-up files to the root directory, equivalent to restore:
[Email protected] ~]# tar-xvzf/root/mongodb_20150505.tar.gz-c/
D. If you cannot start the service, delete the file Mongod.lock first:
[Email protected] ~]# rm-f/var/lib/mongo/mongod.lock
E. Start the service, normal access.
[[Email protected] ~]# service Mongod start
2. UseMongodump andMongorestore
A. A simple backup method of restoring the local database, backing up all and restoring all:
Mongodumpmongorestore/root/dump
After the backup is complete, a folder "dump" will be generated in the current directory:
B. When restoring a single database, specify the database to restore and its backup directory:
Mongorestore--db Test/root/dump/test
You can also specify the output path, using the computer name:
Mongodump--host localhost.localdomain--port 27017--out/root/mongodump-2015-05-05mongorestore--port 27017--db Test/ Root/mongodump-2015-05-05/test
Specify user name password when remote backup (this does not try, refer to the official example):
Mongodump--host mongodb1.example.net--port 3017--username user--password pass--out/opt/backup/ Mongodump-2013-10-24mongorestore--host mongodb1.example.net--port 3017--username user--password pass/opt/backup/ Mongodump-2013-10-24
C. For more information: executive #mongorestore--help
# Mongorestore--helpgeneral options:--help Print usage--version Print the tool version and exitverbosity options:-V,--verbose more detailed logs out Put (include multiple times for more verbosity, e.g.-vvvvv)--quiet Hide all log outputc Onnection options:-H,--host= MongoDB host to connect to (setname/host1,host2 for replica SE TS)--port= Server port (can also use--host hostname:port) SSL options:--ssl Connect to a Mongod or MONGOs this has SSL enabled--sslcafile= the. P Em 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 Rev Ocation List--sslallowinvalidcertificates bypass the validation for server certificates--sslallowinvalid Hostnames bypass the validation for server name--sslfipsmode use FIPS mode of the INS talled OpenSSL libraryauthentication options:-U,--username= username for authentication-p,-- password= Password for authentication--authenticationdatabase= database that holds The user ' s credentials--authenticationmechanism= authentication mechanism to Usenamespace options:-D,-- db= database to Use-c,--collection= collection to Useinput options: --objcheck validate all objects before inserting--oplogreplay R Eplay Oplog for Point-in-time restore--oploglimit= only include Oplog entries before the provided Timestamp (seconds[:o Rdinal])--restoredbusersandroles restore user and role definitions for the given database--dir= Input directory, use '-' for Stdinrestore 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 ' major ity ')--noindexrestore don ' t restore indexes--nooptionsrestore don ' t restor E collection Options--keepindexversion don ' t update index version--maintaininsertionorder Preserve order of documents during RESTORATION-J,--numparallelcollections= number of collections to R estore in parallel (4 by Default)--numinsertionworkerspercollection= number of insert operations to run concurrently per collection (1 by de Fault)--stoponerror stop restoring if an error was encountered on insert (off bydefault)
3. Using mongoimport and Mongoexport
3.1 Mongoexport Export
--type: For JSON or Csv--fields: Select exported column # Export column {_id,id,size} to CSV format mongoexport--db Test--collection tab--type=csv--fields _id , id,size--out/root/test_tab.csv# export JSON format mongoexport--db Test--collection tab--type=json--out/root/test_tab.json# Output to shell, query id=2 and output by name in ascending order mongoexport--db Test--collection tab--query ' {' id ': 2} '--sort ' {' name ': 1} ' #查询导出mongoexpor T--db Test--collection tab--type=csv--query ' {"id": 2} '--fields _id,id--out/root/test_tab.csv# shorthand options [--db] and [--collect Ion], using the Skip and limit function output mongoexport-d test-c tab--sort ' {"name":-1} '--limit 2--skip 2--out/root/test_tab.json# If remote, you need to add parameters: Host,port,username,password--host servername_or_ip--port 37017--username user--password Pass
View Help: Mongoexport--help
General Options:--help print usage--version print the tool versio N and exitverbosity options:-V,--verbose more detailed log output (include multiple times for more verbosity, e.g-VVVVV)--quiet hide all log outputconnection 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 th At have SSL enabled--sslcafile= the. pem file containing the root certificate chain from the Certif Icate Authority--sslpemkeyfile= the. Pem file containing the certificate and key--SSLPEMKEYPASSW ord= the password to decrypt the sslpemkeyfile, if necessary--sslcrlfile= the. Pem file C Ontaining the CertificatE Revocation List--sslallowinvalidcertificates bypass the validation for server certificates--sslallowinvalid Hostnames bypass the validation for server name--sslfipsmode use FIPS mode of the installed Ope Nssl libraryauthentication options:-U,--username= username for authentication-p,--password= Password for authentication--authenticationdatabase= database that holds the user ' s credentials --authenticationmechanism= authentication mechanism to Usenamespace options:-D,--db= D Atabase to Use-c,--collection= collection to Useoutput options:-F,--fields= Co MMA 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 ' JSO n ')-O,--out= Output file; If not specified, stdout are used--jsonarray output to a JSON array rather than one object per Lin E--pretty output JSON formatted to be human-readablequerying 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 (does not use $snapshot)--skip= Number of documents to skip--limit= limit the number of documents to Expor T--sort= sort order, as a JSON string, e.g. ' {x:1} '
3.2 mongoimport import
#列 "_id" will also be imported, note the duplicate key mongoimport--db mydb--collection tab--file/root/test_tab.jsonmongoimport--db mydb--collection tab --type CSV--headerline--file/root/test_tab.csv# If remote, you need to add parameters: Host,port,username,password--host servername_or_ip-- Port 37017--username User--password Pass
View Help: Mongoimport--help
General Options:--help print usage--version print the tool versio N and exitverbosity options:-V,--verbose more detailed log output (include multiple times for more verbosity, e.g-VVVVV)--quiet hide all log outputconnection 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 th At have SSL enabled--sslcafile= the. pem file containing the root certificate chain from the Certif Icate Authority--sslpemkeyfile= the. Pem file containing the certificate and key--SSLPEMKEYPASSW ord= the password to decrypt the sslpemkeyfile, if necessary--sslcrlfile= the. Pem file C Ontaining the CertificatE Revocation List--sslallowinvalidcertificates bypass the validation for server certificates--sslallowinvalid Hostnames bypass the validation for server name--sslfipsmode use FIPS mode of the installed Ope Nssl libraryauthentication options:-U,--username= username for authentication-p,--password= Password for authentication--authenticationdatabase= database that holds the user ' s credentials --authenticationmechanism= authentication mechanism to Usenamespace options:-D,--db= D Atabase to Use-c,--collection= collection to Useinput options:-F,--fields= com Ma 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 are used--headerline use first line in INPUT source as the field list (CSV and TSV only)--jsonarray Tre At 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 th E order of their appearance in the input source-j,--numinsertionworkers= number of inserts operations to run con Currently (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 ')
Because there is no replication, copy the backup to the time to test the record! ~
MongoDB Basics (v) Backup Restore and Export import