10

I know that in the MongoDB terminal, I can run show dbs to see the available databases. I want to list the databases in a programmatic way so that I can iterate over them and delete some based upon a regular expression.

I have tried db.runCommand("show dbs") but does not return results to iterate.

3 Answers 3

17

Iterate over MongoDB database names:

> db.getMongo().getDBNames()
[
    "test",
    "admin",
    "local"
]
> db.getMongo().getDBNames
function () {
    return this.getDBs().databases.map(function (z) {return z.name;});
}
Sign up to request clarification or add additional context in comments.

Comments

6

Based upon this answer http://groups.google.com/group/mongodb-user/browse_thread/thread/9b3568f3a3cf4271, I was able to code up a solution.

use admin
dbs = db.runCommand({listDatabases: 1})
dbNames = []
for (var i in dbs.databases) { dbNames.push(dbs.databases[i].name) }

Hopefully this will help someone else.

Comments

5

The below will create an array of the names of the database:

var connection = new Mongo();
var dbNames = connection.getDBNames();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.