Multiple databases and collections mongodump

11,760

Solution 1

Here is a working script:

  dbs=`mongo --eval "db.getMongo().getDBNames()" | grep '"' | tr -d '",' `


    for db in $dbs; do
        col=`mongo  $db --host example.com --quiet --eval "db.getCollectionNames()" | tr -d ',"[]' `
        for collection in $col; do
          mongodump --host example.com -q '{_id: {$gt: 10}}' -d $db -c $collection --out dump

       done
    done

from mongodump documentation :

--query , -q

Provides a JSON document as a query that optionally limits the documents included in the output of mongodump. You must enclose the query in single quotes (e.g. ') to ensure that it does not interact with your shell environment.

Solution 2

For multiple database.

dbs=( z2p stackoverflow poststodos)  
for c in ${dbs[@]}
do
mongodump -d  $c  --out ~/backups/dump
done
Share:
11,760
basante
Author by

basante

Updated on June 13, 2022

Comments

  • basante
    basante about 2 years

    I have something like this:

    dbs=$(mongo --quiet --eval "db.getMongo().getDBNames()" --host exemple.com | \ 
                grep '"' | tr -d '"' | tr -d ',')
    
    for db in $dbs; do
        cols=$(mongo --quiet --eval "print(db.getCollectionNames())" $db \
                      --host exemple.com | tr ',' ' ')
        for col in $cols; do
            mongodump --host example.com -q "{_id:{\$gt:$oid}}" \
                       -d $dbs -c $col --out /data/
       done
    done
    

    I'm getting:

    positional arguments not allowed

    How can I use mongodump for all collections in all databases ?