Skip to content

Instantly share code, notes, and snippets.

@imasif
Last active June 22, 2020 13:57
Show Gist options
  • Save imasif/d164b90e43a7124fbed99eff79eb6700 to your computer and use it in GitHub Desktop.
Save imasif/d164b90e43a7124fbed99eff79eb6700 to your computer and use it in GitHub Desktop.
Export mongodb database into JSON files, and import the JSON again.
#!/bin/bash
if [ ! $1 ]; then
echo " Example of use: $0 database_name dir_to_store"
exit 1
fi
db=$1
out_dir=$2
if [ ! $out_dir ]; then
out_dir="./"
else
mkdir -p $out_dir
fi
tmp_file="abcdefghijkl.js"
echo "print('_ ' + db.getCollectionNames())" > $tmp_file
cols=`mongo $db $tmp_file | grep '_' | awk '{print $2}' | tr ',' ' '`
for c in $cols
do
mongoexport -d $db -c $c -o "$out_dir/${c}.json"
done
rm $tmp_file
#!/bin/bash
if [ ! $1 ]; then
echo " Example of use: $0 database_name dir_from"
exit 1
fi
db=$1
import_dir=$2
if [ ! $import_dir ]; then
import_dir="./"
fi
for file in $import_dir/*.json;
do c=${file#*};
CN="$(cut -d'/' -f2 <<<"$c")"
c=${CN%.json};
mongoimport --db $db --collection "${c}" --file "${file}";
done
@imasif
Copy link
Author

imasif commented Jun 16, 2020

how to run?
For export:
$imasif->: bash exportDB.sh [dbname] [directory path to export]

For import:
$imasif->: bash importDB.sh [dbname] [directory path to import]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment