MongoDB
 sql >> база данни >  >> NoSQL >> MongoDB

Как да възстановите конкретна колекция в MongoDB с помощта на логическо архивиране

Поддържането на резервни копия на вашата база данни е една от най-важните задачи във всяка производствена среда. Това е процес на копиране на вашите данни на друго място, за да ги запазите в безопасност. Това може да бъде полезно при възстановяване от спешни ситуации като повреда на база данни или срив на база данни, която не може да бъде поправена.

Освен възстановяване, резервно копие може да се използва и за имитация на производствена база данни за тестване на приложение в различна среда или дори за отстраняване на грешки в нещо, което не може да се направи в производствената база данни.

Има различни методи за архивиране на база данни, които можете да приложите, от логическо архивиране с помощта на инструменти, които са вградени в базата данни (напр. mysqldump, mongodump, pg_dump) до физическо архивиране с помощта на инструменти на трети страни (напр. xtrabackup, barman, pgbackrest, mongodb последователно архивиране).

Кой метод да използвате често се определя от това как искате да възстановите. Например, приемете, че сте изпуснали таблица или колекция по погрешка. Колкото и малко вероятно да изглежда, това се случва. Така че най-бързият начин за възстановяване би бил да възстановите само тази таблица или колекция, вместо да се налага да възстановявате цяла база данни.

Архивиране и възстановяване в Mongodb

Mongodump и mongorestore е инструментът за логическо архивиране, използван в MongoDB, това е вид mysqldump в MySQL или pg_dump в PostgreSQL. Помощната програма mongodump и mongorestore ще бъде включена, когато инсталирате MongoDB и тя изхвърля данните във формат BSON. Mongodump се използва за логично архивиране на базата данни в дъмп файлове, докато mongorestore се използва за операцията по възстановяване.

Командите mongodump и mongorestore са лесни за използване, въпреки че има много опции.

Както можем да видим по-долу, можете да архивирате конкретни бази данни или колекции. Можете дори да направите моментна снимка за момент във времето, като включите oplog.

[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

Има много опции в командата mongorestore, задължителната опция е свързана с опции за връзка като хост, порт и удостоверяване. Има и други параметри, като -j, използван за паралелно възстановяване на колекции, -c или --collection се използва за конкретна колекция, а -d или --db се използва за дефиниране на конкретна база данни. Списъкът с опции на параметъра mongorestore може да бъде показан с помощта на помощ : 

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

Възстановяването на конкретни колекции в MongoDB може да се извърши с помощта на колекцията от параметри в mongorestore. Да приемем, че имате база данни с поръчки, вътре в базата данни с поръчки има няколко колекции, както е показано по-долу:

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

Вече сме насрочили архивиране на базата данни с поръчки и искаме да възстановим колекцията от запаси в нова база данни order_new на същия сървър. Ако искате да използвате опция --collection, трябва да подадете името на колекцията като  параметър на mongorestore или можете да използвате опцията --nsInclude={db}.{collection}, ако не сте посочили пътя към файла за колекция .

[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

Можете да проверите колекцията в order_new база данни, както е показано по-долу:

​my_mongodb_0:PRIMARY> use order_new;

switched to db order_new

my_mongodb_0:PRIMARY> show collections;

stock

Как можем да възстановим с помощта на mongodump в ClusterControl

Възстановяването на резервно копие чрез ClusterControl е лесно, трябват ви само 2 стъпки, за да възстановите архива. В списъка ще има много архивни файлове, ако сте активирали своя график за архивиране, има известна информация за архивирането, която може да бъде много полезна. Например, състоянието на архивирането, което показва дали архивирането е завършено/неуспешно, методът на архивиране е зает, списък с бази данни и размер на дъмпа. Стъпките за възстановяване на данните на MongoDB чрез ClusterControl са както следва:

Първа стъпка

Следвайте подканите, за да възстановите архива на възел, както е показано по-долу...

Втора стъпка

Трябва да изберете кое резервно копие трябва да бъде възстановено.

Трета стъпка

Преглед на обобщението...

 


  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Проблеми с MongoDB PHP UTF-8

  2. Запитване на MongoDB GridFS?

  3. Планирайте работата на Node.js на всеки пет минути

  4. Многоезично моделиране на данни в MongoDB

  5. Mongoose Model.find не е функция?