To get MongoDB databases in a JavaScript array, you can use runCommand(). Following is the query to get MongoDB databases in a JavaScript array
> use admin; switched to db admin > allDatabasesDetails = db.runCommand({listDatabases: 1});
This will produce the following output
{ "databases" : [ { "name" : "admin", "sizeOnDisk" : 847872, "empty" : false }, { "name" : "config", "sizeOnDisk" : 98304, "empty" : false }, { "name" : "local", "sizeOnDisk" : 73728, "empty" : false }, { "name" : "sample", "sizeOnDisk" : 1273856, "empty" : false }, { "name" : "sampleDemo", "sizeOnDisk" : 352256, "empty" : false }, { "name" : "studentSearch", "sizeOnDisk" : 262144, "empty" : false }, { "name" : "test", "sizeOnDisk" : 9527296, "empty" : false } ], "totalSize" : 12435456, "ok" : 1 }
Following is the query to get total databases:
> allDatabaseName = [] [ ] > for (var j in allDatabasesDetails.databases) { allDatabaseName.push(dbs.databases[j].name) }
This will produce the following output
7