How can I get a list of databases and collections on a MongoDB server?


To get a list of all databases, you need to use the below syntax −

use admin

db.runCommand({listDatabases: 1});

To get a list of all collection names of a particular database, you need to use below syntax −

use yourDatabaseName;

db.getCollectionNames();

Let us implement the above syntaxes −

Case 1 − To get a list of databases

> use admin
switched to db admin

> db.runCommand({listDatabases: 1});

This will produce the following output −

{
   "databases" : [
      {
         "name" : "admin",
         "sizeOnDisk" : 1675264,
         "empty" : false
      },
      {
         "name" : "config",
         "sizeOnDisk" : 131072,
         "empty" : false
      },
      {
         "name" : "local",
         "sizeOnDisk" : 77824,
         "empty" : false
      },
      {
         "name" : "main",
         "sizeOnDisk" : 184320,
         "empty" : false
      },
      {
         "name" : "my",
         "sizeOnDisk" : 753664,
         "empty" : false
      },
      {
         "name" : "sample",
         "sizeOnDisk" : 1286144,
         "empty" : false
      },
      {
         "name" : "sampleDemo",
         "sizeOnDisk" : 352256,
         "empty" : false
      },
      {
         "name" : "studentSearch",
         "sizeOnDisk" : 262144,
         "empty" : false
      },
      {
         "name" : "test",
         "sizeOnDisk" : 15810560,
         "empty" : false
      },
      {
         "name" : "university",
         "sizeOnDisk" : 229376,
         "empty" : false
      },
      {
         "name" : "web",
         "sizeOnDisk" : 217088,
         "empty" : false
      }
   ],
   "totalSize" : 20979712,
   "ok" : 1
}

Case 2 − To get a list of collections

Here, we are getting the list of collections for database “sample”

> use sample;
switched to db sample

> db.getCollectionNames();

This will produce the following output −

[
   "arraySizeErrorDemo",
   "basicInformationDemo",
   "copyThisCollectionToSampleDatabaseDemo",
   "documentWithAParticularFieldValueDemo",
   "employee",
   "findListOfIdsDemo",
   "findMimimumElementInArrayDemo",
   "findSubstring",
   "getAllRecordsFromSourceCollectionDemo",
   "getElementWithMaxIdDemo",
   "insertDocumentWithDateDemo",
   "internalArraySizeDemo",
   "largestDocumentDemo",
   "makingStudentInformationClone",
   "nestedArrayDemo",
   "oppositeAddToSetDemo",
   "prettyDemo",
   "returnOnlyUniqueValuesDemo",
   "selectItemDemo",
   "selectWhereInDemo",
   "sourceCollection",
   "specificFieldDemo",
   "studentInformation",
   "sumOfValueDemo",
   "sumTwoFieldsDemo",
   "truncateDemo",
   "updateFieldIfValueIsGreaterDemo",
   "updateInformation",
   "userInformation"
]

Updated on: 30-Jul-2019

118 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements