Skip to content

Instantly share code, notes, and snippets.

@jackrobertscott
Last active February 14, 2021 04:25
Show Gist options
  • Select an option

  • Save jackrobertscott/77df160adcb7b2f75f5b3648d5e6b8ee to your computer and use it in GitHub Desktop.

Select an option

Save jackrobertscott/77df160adcb7b2f75f5b3648d5e6b8ee to your computer and use it in GitHub Desktop.
Export & import all MongoDB collections using JSON files.
#!/bin/bash
# Usage: ./mongodb-json-export.sh dbName
DB=$1
COLLECTIONS=$(mongo localhost:27017/$DB --quiet --eval "db.getCollectionNames()" | tr -d '\[\]\"[:space:]' | tr ',' ' ')
mkdir json
for collection in $COLLECTIONS; do
echo "Exporting $DB/$collection ..."
mongoexport -d $DB -c $collection -o json/$collection.json
done
#!/bin/bash
# Usage: ./mongodb-json-import.sh dbName jsonFilesFolderLocation
DB=$1
FOLDER=$2
WORKDIR=$(pwd)
cd $FOLDER
COLLECTIONS=$(ls -1 *.json | sed 's/.json$//')
for collection in $COLLECTIONS; do
echo "Importing $DB/$collection ..."
mongoimport -d $DB -c $collection --file $collection.json
done
cd $WORKDIR
@jackrobertscott
Copy link
Author

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