Skip to content

Instantly share code, notes, and snippets.

@imasif

imasif/exportDB.sh

Last active Jun 22, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@imasif 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