How to operate on all databases from the MongoDB shell?


To operate on all databases from MongoDB shell, you can use listDatabases along with adminCommand().

Let’s say we are using a sample database “test”. At first, check the current database with the help of db command.

Following is the query to get the current database

> db;

This will produce the following output

Test

Following is the query to operate on all the databases from the Mongo shell

> var allDatabaseList = db.adminCommand('listDatabases');

Now you need to use printjson() in order to print all databases. Following is the query

> printjson (allDatabaseList);

This will produce the following output

{
   "databases" : [
      {
         "name" : "admin",
         "sizeOnDisk" : 495616,
         "empty" : false
      },
      {
         "name" : "config",
         "sizeOnDisk" : 98304,
         "empty" : false
      },
      {
         "name" : "local",
         "sizeOnDisk" : 73728,
         "empty" : false
      },
      {
         "name" : "sample",
         "sizeOnDisk" : 1388544,
         "empty" : false
      },
      {
         "name" : "sampleDemo",
         "sizeOnDisk" : 278528,
         "empty" : false
      },
      {
         "name" : "studentSearch",
         "sizeOnDisk" : 262144,
         "empty" : false
      },
      {
         "name" : "test",
         "sizeOnDisk" : 9695232,
         "empty" : false
      }
   ],
   "totalSize" : 12292096,
   "ok" : 1
}
raja
Published on 11-Apr-2019 11:55:25
Advertisements