How to export all collection in MongoDB ?



  • 3 Answer(s)

    Can you use mongodump it’s faster:

    mongodump -d <database_name> -o <directory_backup>
    
    

    Then  to “restore/import” that, i used (from directory_backup/dump/):

    mongorestore -d <database_name> <directory_backup>
    
    

    For this answer, you don’t want to each entire collections and export one by one. Just you want to specify the database. I will 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.

    Answered on December 27, 2018.
    Add Comment

    Just try to execute it for the two parameter (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
    
    Answered on December 27, 2018.
    Add Comment

    To make the mongodump  from the server and then import it other server/local machine which has a username and a password

    1. mongodump -d dbname -o dumpname -u username -p password
    2. scp -r [email protected]:~/location/of/dumpname ./
    3. mongorestore -d dbname dumpname/dbname/ -u username -p password
    
    Answered on December 27, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.