문제

Can you list all databases in MongoDB from a linux bash terminal? I cannot find the correct command. I am trying to list all so as that I can write a bash script to backup all DB's individually. Is there a better way?

도움이 되었습니까?

해결책

"show dbs" calculate the databases sizes and that may take some time.

You can pass this command to the mongo shell, then clean the response:

echo "db.getMongo().getDBNames()"|mongo --quiet |tr -d \[\] | tr , "\n"|cut -c3-| tr -d \"

다른 팁

Use --eval parameter

mongo --eval 'show dbs'

This is a bit tricky, as built-in command show dbs will show databases with sizes. Plus this command cannot be evaled.

However commands can be passed with bash heredoc syntax. And to get rid of sizes, only even values can be displayed.

To skip showing welcome message use --quiet option.

Resulting script:

#!/bin/bash

# $dbs will contain db names and sizes mixed together
# Use --quiet to skip connection information
dbs=$(mongo --quiet <<EOF
show dbs
quit()
EOF
)
i=0
for db in ${dbs[*]}
do
    # Odd values are db names
    # Even values are sizes
    i=$(($i+1))
    # Show db name, ignore size
    if (($i % 2)); then
        echo "$db"
    fi
done
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 dba.stackexchange
scroll top