List all MongoDB databases from Linux bash terminal
-
09-10-2020 - |
Question
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?
Solution
"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 \"
OTHER TIPS
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 eval
ed.
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
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange