How to iterate over all MongoDB databases?

MongoDBDatabaseBig Data Analytics

To iterate over all MongoDB databases, you need to switch your database to admin. Following is the query to switch to admin and get information about all the databases

> switchDatabaseAdmin = db.getSiblingDB("admin");
admin
> allDatabaseName = switchDatabaseAdmin.runCommand({ "listDatabases": 1 }).databases;

This will produce the following output

[
   {
      "name" : "admin",
      "sizeOnDisk" : 495616,
      "empty" : false
   },
   {
      "name" : "config",
      "sizeOnDisk" : 98304,
      "empty" : false
   },
   {
      "name" : "local",
      "sizeOnDisk" : 73728,
      "empty" : false
   },
   {
      "name" : "sample",
      "sizeOnDisk" : 1335296,
      "empty" : false
   },
   {
      "name" : "sampleDemo",
      "sizeOnDisk" : 278528,
      "empty" : false
   },
   {
      "name" : "studentSearch",
      "sizeOnDisk" : 262144,
      "empty" : false
   },
   {
      "name" : "test",
      "sizeOnDisk" : 8724480,
      "empty" : false
   }
]
raja
Published on 11-Apr-2019 14:49:49
Advertisements