Để lấy danh sách tất cả database:
use admin
db.runCommand({listDatabases: 1});
Để lấy danh sách collection của một database:
use yourDatabaseName; db.getCollectionNames();
Trường hợp 1: Liệt kê database
> use admin
switched to db admin
> db.runCommand({listDatabases: 1});
Kết quả (ví dụ):
{
"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
}
Trường hợp 2: Liệt kê collection (database "sample")
> use sample; switched to db sample > db.getCollectionNames();
Kết quả:
[
"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"
]
Lưu ý: Cần chuyển sang database admin trước khi chạy listDatabases.