How to export all collections in MongoDB?

Solution 1:

For lazy people, use mongodump, it's faster:

mongodump -d <database_name> -o <directory_backup>

And to "restore/import" it (from directory_backup/dump/):

mongorestore -d <database_name> <directory_backup>

This way, you don't need to deal with all collections individually. Just specify the database.

Note that I would recommend against using mongodump/mongorestore for big data storages. It is very slow and once you get past 10/20GB of data it can take hours to restore.

Solution 2:

I wrote bash script for that. Just run it with 2 parameters (database name, dir to store files).

#!/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="fadlfhsdofheinwvw.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/exp_${db}_${c}.json"
done
rm $tmp_file