5

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?

1

"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 \"
| improve this answer | |
1

Use --eval parameter

mongo --eval 'show dbs'
| improve this answer | |
  • 2
    mongo --eval 'show dbs' MongoDB shell version: 3.0.15 connecting to: test 2017-10-12T10:43:10.642+0000 E QUERY SyntaxError: Unexpected identifier – eekfonky Oct 12 '17 at 10:43
0

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
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.