Get MongoDB Databases in a JavaScript Array?

To get MongoDB databases in a JavaScript array, you can use the listDatabases command with runCommand() and then extract database names into an array using JavaScript.

Syntax

use admin;
allDatabasesDetails = db.runCommand({listDatabases: 1});
databaseNames = allDatabasesDetails.databases.map(db => db.name);

Step 1: Get All Databases Details

First, switch to the admin database and run the listDatabases command ?

use admin;
allDatabasesDetails = db.runCommand({listDatabases: 1});
{
   "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" : "test",
         "sizeOnDisk" : 9527296,
         "empty" : false
      }
   ],
   "totalSize" : 12435456,
   "ok" : 1
}

Step 2: Extract Database Names into Array

Use JavaScript to extract only the database names into an array ?

databaseNames = [];
for (var i in allDatabasesDetails.databases) {
    databaseNames.push(allDatabasesDetails.databases[i].name);
}
print(databaseNames);
["admin", "config", "local", "sample", "test"]

Method 2: Using map() Function

A more concise approach using JavaScript's map() function ?

databaseNames = allDatabasesDetails.databases.map(function(db) {
    return db.name;
});
print(databaseNames);
["admin", "config", "local", "sample", "test"]

Get Database Count

To get the total number of databases ?

print("Total databases: " + databaseNames.length);
Total databases: 5

Conclusion

Use db.runCommand({listDatabases: 1}) from the admin database to get all database details, then extract names using JavaScript loops or the map() function. This returns a clean array of database names for further processing.

Updated on: 2026-03-15T00:37:54+05:30

294 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements