Skip to content

Instantly share code, notes, and snippets.

@wangpin34
Created May 15, 2025 09:23
Show Gist options
  • Save wangpin34/70c4eefa9c48e05b136db4efc8f0fca1 to your computer and use it in GitHub Desktop.
Save wangpin34/70c4eefa9c48e05b136db4efc8f0fca1 to your computer and use it in GitHub Desktop.
migrate mongdb, read from and to database properties from .env file
base migrate.sh # by default read variables like `FROM_DB_URI` (the connection string) from `.env` file.
bash migrate.sh --env .env.prod # specify other env config file

Environment variables

The env file should contains the following variables.

FROM_DB_URI="mongodb://mongodb0.example.com:27017"
FROM_DB_USERNAME="username"
FROM_DB_PASSWORD="password"
FROM_DB_NAME="from-db-name"


TO_DB_URI="mongodb://mongodb0.example.com:27017"
TO_DB_USERNAME="username"
TO_DB_PASSWORD="password"
TO_DB_NAME="to-db-name"
#!/bin/bash
# Default .env file
ENV_FILE=".env"
# Parse arguments
while [[ "$#" -gt 0 ]]; do
case $1 in
--env) ENV_FILE="$2"; shift ;; # Set the environment file
*) echo "Unknown parameter passed: $1"; exit 1 ;;
esac
shift
done
# Load environment variables from the specified .env file if it exists
if [ -f "$ENV_FILE" ]; then
echo "Loading environment variables from $ENV_FILE"
set -o allexport
source "$ENV_FILE"
set +o allexport
else
echo "Environment file $ENV_FILE not found!"
exit 1
fi
DUMP_DIR="./backup"
rm -rf $DUMP_DIR
mkdir -p $DUMP_DIR
mongodump --uri=$FROM_DB_URI --username=$FROM_DB_USERNAME --password=$FROM_DB_PASSWORD -d $FROM_DB_NAME --out $DUMP_DIR
if [ -d "${DUMP_DIR}/${FROM_DB_NAME}" ]; then
mongorestore --uri=$TO_DB_URI --username=$TO_DB_USERNAME --password=$TO_DB_PASSWORD --nsFrom="${db_name}.*" --nsTo="${TO_DB_NAME}.*" "${DUMP_DIR}"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment