Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get MongoDB Databases in a JavaScript Array?

Tags:

mongodb

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.

like image 431
JP Richardson Avatar asked Oct 26 '10 17:10

JP Richardson


People also ask

Can we connect MongoDB with JavaScript?

The MongoDB JavaScript (NodeJS) Driver makes it simple to work with MongoDB databases from Node. js applications. To connect to your database and run the queries discussed in this Quick Start series, you'll need the MongoDB JavaScript (NodeJS) driver.

How do I view databases in MongoDB?

If you want to check your databases list, use the command show dbs. Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. In MongoDB default database is test.

What is $all in MongoDB?

$all. The $all operator selects the documents where the value of a field is an array that contains all the specified elements.

How do I list in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().


3 Answers

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;});
}
like image 76
mstearn Avatar answered Sep 28 '22 12:09

mstearn


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.

like image 34
JP Richardson Avatar answered Sep 28 '22 13:09

JP Richardson


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

var connection = new Mongo();
var dbNames = connection.getDBNames();
like image 34
Peter Ryan Avatar answered Sep 28 '22 13:09

Peter Ryan