sql >> Databasteknik >  >> NoSQL >> MongoDB

Hur man återställer en specifik samling i MongoDB med hjälp av logisk säkerhetskopiering

Att hålla säkerhetskopior av din databas är en av de viktigaste uppgifterna i alla produktionsmiljöer. Det är processen att kopiera din data till någon annan plats för att hålla den säker. Detta kan vara användbart vid återhämtning från nödsituationer som databaskorruption eller en databas som kraschar bortom reparation.

Förutom återställning kan en säkerhetskopia också användas för att efterlikna en produktionsdatabas för att testa en applikation i en annan miljö, eller till och med för att felsöka något som inte kan göras på produktionsdatabasen.

Det finns olika metoder för säkerhetskopiering av databas som du kan implementera, från logisk säkerhetskopiering med hjälp av verktyg som är inbäddade i databasen (t.ex. mysqldump, mongodump, pg_dump) till fysisk säkerhetskopiering med verktyg från tredje part (t.ex. xtrabackup, barman, pgbackrest, mongodb konsekvent backup).

Vilken metod som ska användas bestäms ofta av hur du vill återställa. Anta till exempel att du tappade ett bord eller en samling av misstag. Hur osannolikt det än kan tyckas händer det. Så det snabbaste sättet att återställa skulle vara att återställa just den tabellen eller samlingen, istället för att behöva återställa en hel databas.

Säkerhetskopiera och återställa i Mongodb

Mongodump och mongorestore är verktyget för logisk säkerhetskopiering som används i MongoDB, det är typ mysqldump i MySQL eller pg_dump i PostgreSQL. Verktyget mongodump och mongorestore kommer att inkluderas när du installerar MongoDB och det dumpar data i BSON-format. Mongodump används för att säkerhetskopiera databasen logiskt till dumpfiler, medan mongorestore används för återställningsoperationen.

mongodump och mongorestore-kommandon är lätta att använda, även om det finns många alternativ.

Som vi kan se nedan kan du säkerhetskopiera specifika databaser eller samlingar. Du kan till och med ta en ögonblicksbild av en tidpunkt genom att inkludera oploggen.

[email protected]:~# 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)



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)



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



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 JSON string, e.g., '{x:{$gt:1}}'

      --queryFile=                                          path to a file containing a query filter (JSON)

      --readPreference=<string>|<json>                      specify either a preference name or a preference json object

      --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

      --repair                                              try to recover documents from damaged data files (not supported by all storage engines)

      --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

Det finns många alternativ i mongorestore-kommandot, obligatoriskt alternativ är relaterat till anslutningsalternativ som värd, port och autentisering. Det finns andra parametrar, som -j används för att återställa samlingar parallellt, -c eller --collection används för en specifik samling och -d eller --db används för att definiera en specifik databas. Listan med alternativ för mongorestore-parametern kan visas med hjälp : 

[email protected]:~# 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)



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)



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



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                              preserve order of documents during restoration

  -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                                         stop restoring if an error is encountered on insert (off by default)

      --bypassDocumentValidation                            bypass document validation

      --preserveUUID                                        preserve original collection UUIDs (off by default, requires drop)

Återställning av specifika samlingar i MongoDB kan göras med hjälp av parametersamlingen i mongorestore. Anta att du har en orderdatabas, inne i orderdatabasen finns det några samlingar som visas nedan:

my_mongodb_0:PRIMARY> show dbs;

admin   0.000GB

config  0.000GB

local   0.000GB

orders  0.000GB

my_mongodb_0:PRIMARY> use orders;

my_mongodb_0:PRIMARY> show collections;

order_details

orders

stock

Vi har redan schemalagt en backup för orderdatabasen och vi vill återställa lagersamlingen till en ny databas order_new på samma server. Om du vill använda option --collection måste du skicka samlingsnamnet som parameter för mongorestore eller så kan du använda alternativet --nsInclude={db}.{collection} om du inte angav sökvägen till samlingsfilen .

[email protected]:~/dump/orders# mongorestore -umongoadmin --authenticationDatabase admin --db order_new --collection stock /root/dump/orders/stock.bson

Enter password:

​2020-03-09T04:06:29.100+0000 checking for collection data in /root/dump/orders/stock.bson

2020-03-09T04:06:29.110+0000 reading metadata for order_new.stock from /root/dump/orders/stock.metadata.json

2020-03-09T04:06:29.134+0000 restoring order_new.stock from /root/dump/orders/stock.bson

2020-03-09T04:06:29.202+0000 no indexes to restore

2020-03-09T04:06:29.203+0000 finished restoring order_new.stock (1 document)

2020-03-09T04:06:29.203+0000 done

Du kan kontrollera samlingen i order_new databasen som visas nedan:

​my_mongodb_0:PRIMARY> use order_new;

switched to db order_new

my_mongodb_0:PRIMARY> show collections;

stock

Hur vi kan återställa med mongodump i ClusterControl

Att återställa en säkerhetskopieringsdump via ClusterControl är enkelt, du behöver bara två steg för att återställa säkerhetskopian. Det kommer att finnas massor av säkerhetskopior i listan om du aktiverat ditt säkerhetskopieringsschema, det finns en del information om säkerhetskopiorna som kan vara mycket användbar. Till exempel status för säkerhetskopiering som indikerar om säkerhetskopieringen slutfördes/misslyckades, säkerhetskopieringsmetoden hade tagits, lista över databaser och storleken på dumpen. Stegen för att återställa MongoDB-data via ClusterControl är enligt nedan:

Steg ett

Följ anvisningarna för att återställa säkerhetskopian till en nod som visas nedan...

Steg två

Du måste välja vilken säkerhetskopia som behöver återställas.

Steg tre

Granska sammanfattningen...

 


  1. Ställ in MongoDb-omvandlaren programmatiskt

  2. Redis SortedSet:Hur får man värden i numerisk ordning snarare än alfabetisk ordning när två värden har samma poäng?

  3. Visuell statistik för din MongoDB-server

  4. MongoDB - distinkt med fråga använder inte index