8

Do you know if it is possible to get a list of databases(like 'show dbs' in console) from javascript. I want to drop all databases from mongo via javascript file (mongo admin.js), but i can't find a way to list all databases...

Thx

I'm trying to prepare simple script but i can't find out how i can change db from script. Here is the sample javascript script. It always fails on command "use". I tried with db.eval and eval but it fails.

print(db.getMongo().getDBNames());
var environments = db.getMongo().getDBNames()
for(var environmentIndex in environments){
    print(environments[environmentIndex])   
    eval("use staging");
    //db.dropDatabase();
} 
Community
  • 1
  • 1
  • Apparently it's better practice to use a "sequential" for loop instead. See http://stackoverflow.com/a/3010848/156060 . Here's some JavaScript I just used to drop all databases in my MongoDB server: https://gist.github.com/1754355 – Adam Monsen Feb 06 '12 at 19:47

2 Answers2

13

Use db.adminCommand('listDatabases'). For other commands see http://www.mongodb.org/display/DOCS/List+of+Database+Commands

EDIT:

In util.js use dbname is defined as:

shellHelper.use = function( dbname ){
    db = db.getMongo().getDB( dbname );
    print( "switched to db " + db.getName() );
}
pingw33n
  • 12,292
  • 2
  • 37
  • 38
  • yes, thx. But how i can switch to different db via script? I updated description with sample script. –  Jan 19 '11 at 10:25
  • @pingw33n Can we run the mongodb commands as scripts in bash/linux without having mongo shell installed on machine? – Ravi Teja Muddada Aug 21 '21 at 06:32
7

http://www.mongodb.org/display/DOCS/Scripting+the+shell

db = db.getSiblingDB("otherdb") //same as use otherdb
csgwro
  • 181
  • 2
  • 5