backup and mongodump

Posted under » MongoDB on 26 Jan 2024

You may want to export data to JSON format by

$ mongoexport --db mth --collection students --out output.json
$ mongoimport --db mth --collection students --file output.json
$ mongoexport --db=mth --collection=students --type=csv --fields=username,cid --query='{"username":"hanafi"}' --noHeaderLine --out=taik.csv

Please note that query='{"username":"hanafi"}' is different from query="{'username':'hanafi'}". Doing the later will cause a JSON error.

Also mongoimport does not import the indexes so you have to recreate them.

If you want backup everything including the indexes, then you should do a mongodump which is equivalent to a mysqldump.

$ mongodump --db students --out $(date +'%m-%d-%y')
$ mongodump --db students --out pelajar

The first example will create a folder with a data format. This is great for cron backups.

The 2nd example will create a folder called pelajar. Inside the pelajar folder will be a students folder. Why I differentiate is because when you want to restore it later, there will be less confusion.

$ mongorestore --db students --drop pelajar/students #whole database
$ mongorestore --db students --collection psy pelajar/students/psy.bson --drop


web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data