Skip to content

Instantly share code, notes, and snippets.

@henno
Last active December 4, 2020 12:13
Show Gist options
  • Select an option

  • Save henno/bc0c8c6cc5b3505c81605c6c7b50b3f0 to your computer and use it in GitHub Desktop.

Select an option

Save henno/bc0c8c6cc5b3505c81605c6c7b50b3f0 to your computer and use it in GitHub Desktop.
refresh_mongodb.sh
#!/bin/bash
# Dumps the database specified in a MONGO_URL variable in the .env file to dump folder in the current directory
# Restores collections from dump folder in current directory to a database specified in a MONGO_URL variable in the .env file
# Usage: refresh_mongodb.sh [--dump]
#
# Get connection string from .env
export $(cat .env | sed 's/#.*//g' | xargs)
echo $MONGO_URL
# Get dbName from connection string
# connectionString example: mongodb+srv://keskpank:[email protected]/Cluster1?retryWrites=true&w=majority
if [[ $MONGO_URL =~ \/\/.*\/([^?]+) ]]; then
DB_NAME=${BASH_REMATCH[1]}
echo "Database name is $DB_NAME"
else
echo "Could not get database name from MONGO_URL in .env file"
exit
fi
if [[ $1 == **--dump** ]]
then
echo "Dumping database $DB_NAME"
# Clean up previous dump files
rm -r dump/*
# Dump the current database state into 'dump' folder
mongodump --uri=$MONGO_URL
# Move the files from dump/projectName to dump
mv dump/$DB_NAME/* dump
# Delete dump/projectName folder
rm -r dump/$DB_NAME
else
echo "Importing database $DB_NAME"
# Drop old DB
mongo $MONGO_URL --eval "printjson(db.dropDatabase())"
# Import
echo mongorestore --uri "$MONGO_URL" -d $DB_NAME dump
mongorestore --uri "$MONGO_URL" -d $DB_NAME dump
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment