In the actual development, operation and maintenance process, database backup and recovery is essential, MongoDB also provides the corresponding backup and recovery database commands, and supports the import of data from a variety of data forms.

Data backup instructionmongodump

Use the Mongodump directive to export the database as a compressed package. Before using the database tool, you must install the official database tool. The official document also provides operation instructions. Download and decompress the tool in the bin file to the bin directory of the Mongo installation directory. Export test database as test.backup.20210713

# Specify database backup
mongodump --db=test --gzip --out="test.backup.20210713"
# Back up all databases
mongodump --gzip
Copy the code

The exported file directory is as follows:

Data recovery instructionmongorestore

We first delete the test database and then restore it.

 use test;
 db.dropDatabase();
Copy the code

The recovery instructions are as follows:

mongorestore --db test test.backup.20210713/test --drop --gzip;
Copy the code

The newer version of the directive can restore the entire database or a data set using the –nsInclude parameter.

# Restore test database
mongorestore --gzip --nsInclude="test.*" test.backup.20210713/
# Restore the test.employees dataset
mongorestore --gzip --nsInclude="test.employees" test.backup.20210713/
Copy the code

Export JSON and CSV files

Mongoexport tool can be used to export JSON or CSV files, where CSV export must specify the exported fields.

mongoexport --collection=employees --db=test --out=employees.json
# Specify field export
mongoexport --collection=employees --db=test --fields=name,age,dept --out=employees_f.json
# export CSV
mongoexport --collection=employees --db=test --fields=name,age,dept --type=csv --out=employees.csv
Copy the code

Import from JSON and CSV

Import using the MongoImport tool, when importing from JSON, specify the database and data set, as well as the JSON file location.

mongoimport --collection=employees --db=test employees.json
Copy the code

The same is true when importing from CSV, except that you need to specify the parameters –type= CSV and –fields to specify the fields to import.

mongoimport --collection=employees --db=test --type=csv --fields=name,dept,age employees.csv
Copy the code

conclusion

This article introduces MongoDB data backup and recovery, export data sets to JSON and CSV, and import data from JSON and CSV files. MongoDB also provides more tools, and interested users can check out the Mongo website to see how to use them.