Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to get all the collections from all the MongoDB databases?
To get all the collections from all MongoDB databases, you need to first retrieve all databases and then iterate through each database to get their collections.
Syntax
// Step 1: Get all databases
switchDatabaseAdmin = db.getSiblingDB("admin");
allDatabaseName = switchDatabaseAdmin.runCommand({ "listDatabases": 1 }).databases;
// Step 2: Iterate through databases to get collections
allDatabaseName.forEach(function(databaseName) {
db = db.getSiblingDB(databaseName.name);
collectionName = db.getCollectionNames();
// Process collections as needed
});
Method 1: Get All Database Names
First, let us get all the databases using the admin database ?
switchDatabaseAdmin = db.getSiblingDB("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
}
]
Method 2: Get All Collections from All Databases
Following query iterates through each database and retrieves all collection names ?
allDatabaseName.forEach(function(databaseName) {
db = db.getSiblingDB(databaseName.name);
collectionName = db.getCollectionNames();
collectionName.forEach(function(collectionName) {
print(collectionName);
});
});
This will produce the following output with all collection names ?
clearingItemsInNestedArrayDemo customIdDemo deleteRecordDemo documentExistsOrNotDemo findAllExceptFromOneOrtwoDemo mongoExportDemo startup_log arraySizeErrorDemo basicInformationDemo copyThisCollectionToSampleDatabaseDemo deleteAllRecordsDemo deleteDocuments deleteDocumentsDemo employee findListOfIdsDemo userInformation updateInformation sourceCollection prettyDemo
Key Points
- getSiblingDB("admin") switches to the admin database which has privileges to list all databases
- runCommand({ "listDatabases": 1 }) retrieves metadata for all databases in the MongoDB instance
- getCollectionNames() returns an array of collection names for the current database
- The forEach loop iterates through each database and extracts its collections
Conclusion
Use the admin database to list all databases, then iterate through each database using getSiblingDB() and getCollectionNames() to retrieve all collections across your MongoDB instance.
Advertisements
