多个数据库和集合 mongodump

Multiple databases and collections mongodump

我有这样的东西:

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

我得到:

positional arguments not allowed

如何对所有数据库中的所有集合使用 mongodump

这是一个工作脚本:

  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

来自 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.

对于多个数据库。

dbs=( z2p Whosebug poststodos)  
for c in ${dbs[@]}
do
mongodump -d  $c  --out ~/backups/dump
done

您可以试试这个脚本,它提供了一个名为 dump_by_filter

的函数
#!/bin/bash

# sudo apt install mongo-tools
# sudo apt install mongo-client

# dump(uri:string,col:string,out:string)
function dump {
    local uri=
    local col=
    local out=

    mongodump --forceTableScan  --uri=$uri  -c $col --out $out
}

# load(uri:string,dir:string)
function load {
    local uri=
    local dir=
    mongorestore --drop --uri=$uri $dir
}

# list_col(uri:string,filter:string)
function list_col {
   local res=`echo show collections |mongo  --quiet |grep ` 
   echo $res
}

# dump(uri:string,filter:string,out:string)
function dump_by_filter {
    local uri=
    local filter=
    local out=

    local cols=$(list_col $uri $filter)
    for col in $cols; do
        dump $uri $col $out
        echo dump $col to $out
    done
}

FROM_URL="mongodb://127.0.0.1:27017/a"
TO_URL="mongodb://127.0.0.1:27017/b"

DIR="./out"
dump_by_filter $FROM_URL xx $DIR
load $TO_URL $DIR

我把它放在here