Skip to content

Instantly share code, notes, and snippets.

@eftakhairul
Last active June 16, 2020 21:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eftakhairul/e0c395bb8685e23a18f055d8af6bf867 to your computer and use it in GitHub Desktop.
Save eftakhairul/e0c395bb8685e23a18f055d8af6bf867 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
##### HOW to Run ###########
## ./exportDB.sh [dbname] [directory path to export]
#!/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
##### HOW to Run ###########
## ./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