0 votes
in MongoDB by
Get MongoDB Databases in a Javascript Array in MongoDB?

1 Answer

0 votes
by
I know that in the MongoDB terminal, I can run “show dbs” to see the available databases. I want to get them programmatically so that I can iterate over them and delete some based upon a regular expression.

I have tried db.runCommand(“show dbs”) but that doesn’t work.

Thanks in advance.

> db.getMongo().getDBNames()

[

“test”,

“admin”,

“local”

]

> db.getMongo().getDBNames

function () {

return this.getDBs().databases.map(function (z) {return z.name;});

}

Based upon this answer

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.

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

var connection = new Mongo();

var dbNames = connection.getDBNames();

Related questions

+2 votes
asked Apr 17, 2021 in MongoDB by rajeshsharma
0 votes
asked Jun 3, 2020 in MongoDB by Robindeniel
...