Get list of databases with a UNIX command

45 views
Skip to first unread message

Loïc Decloedt

unread,
Aug 28, 2015, 11:06:46 PM8/28/15
to mongodb-user
Hi,
I would like to get the list of the database manage by on server through a single shell command, on UNIX. The objective is to be able to do a full export of all dbs for validation pruposes.
Right now, I can see only two ways to do this. 
 - Start mongo, type 'show dbs', to a manual copy of the list and exit. I do not like this way as this requires several manual operations.
 - Scan the files.'*.0' in the db directory. This works but is dependent on the format of the database.
Is there any better way to list all the DBs managed by a server through a single command ?
I am using MongoDB 3.0.4 on Scientific Linux.

Thanks,

Loïc.

Chris De Bruyne

unread,
Aug 29, 2015, 4:41:00 AM8/29/15
to mongodb-user
Hi Loic,

Because the mongo shell is actually a JavaScript shell, you can write mongo commands in a script and export these to a file.
For example,

mongo dbname command.js > output.json

command.js can then be something like 

printjson(db.adminCommand('listDatabases'));


It should be fairly easy to get to the solution you are looking for with some more fiddling in the commands.js and some post-processing of the output file to fit your specific use case.

Regards
Chris

Loïc Decloedt

unread,
Aug 31, 2015, 12:36:19 PM8/31/15
to mongodb-user
Hi Chris,
Thanks for your reply, it was really helpful. I was actually missing the pointer to the admin command 'listDatabases'. By using the completion features of the mongo shell,  I wrote this scrip (listdbs.js):

db.adminCommand('listDatabases').databases.
    filter(function(it){return it.name != "local";}).
    forEach(function(it){print(it.name);})

Then, I can run the following command:
> mongo --quiet listdbs.js
prod
test
...

To be complete, I used the capabitilites of javaScript to filter out the output from the 'databases' field.
Regards,
Loïc.

Chris De Bruyne

unread,
Aug 31, 2015, 2:29:02 PM8/31/15
to mongodb-user
I'm glad it helped.

Regards
Chris
Reply all
Reply to author
Forward
0 new messages