MongoDB 서버에 존재하는 모든 데이터베이스의 모든 컬렉션을 한 번에 조회하고 싶다면, 크게 두 단계로 작업을 진행할 수 있습니다. 먼저 admin 데이터베이스에서 listDatabases 명령으로 전체 데이터베이스 목록을 가져온 뒤, 각 데이터베이스를 순회하면서 getCollectionNames() 메서드로 컬렉션 이름을 출력하는 방식입니다.
1단계: 모든 데이터베이스 목록 조회하기
먼저 getSiblingDB() 메서드를 사용해 admin 데이터베이스로 전환한 후, listDatabases 명령을 실행하여 전체 데이터베이스 목록을 가져옵니다.
> switchDatabaseAdmin = db.getSiblingDB("admin");
admin
> allDatabaseName = switchDatabaseAdmin.runCommand({ "listDatabases": 1 }).databases;위 쿼리를 실행하면 다음과 같이 각 데이터베이스의 이름(name), 디스크 사용량(sizeOnDisk), 비어 있는지 여부(empty)가 담긴 배열이 반환됩니다.
[
{
"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
}
]
2단계: 각 데이터베이스의 컬렉션 이름 출력하기
가져온 데이터베이스 목록을 forEach()로 순회하면서, 각 데이터베이스마다 getCollectionNames()를 호출하면 해당 데이터베이스에 속한 모든 컬렉션 이름을 확인할 수 있습니다.
> allDatabaseName.forEach(function(databaseName)
... {
... db = db.getSiblingDB(databaseName.name);
... collectionName = db.getCollectionNames();
... collectionName.forEach(function(collectionName)
... {
... print(collectionName);
... });
... });
이 스크립트를 실행하면 서버의 모든 데이터베이스에 포함된 컬렉션 이름들이 데이터베이스 순서대로 차례차례 출력됩니다.
clearingItemsInNestedArrayDemo
customIdDemo
deleteRecordDemo
documentExistsOrNotDemo
findAllExceptFromOneOrtwoDemo
mongoExportDemo
startup_log
arraySizeErrorDemo
basicInformationDemo
copyThisCollectionToSampleDatabaseDemo
deleteAllRecordsDemo
deleteDocuments
deleteDocumentsDemo
deleteSomeInformation
documentWithAParticularFieldValueDemo
employee
findListOfIdsDemo
findSubstring
getAllRecordsFromSourceCollectionDemo
getElementWithMaxIdDemo
internalArraySizeDemo
largestDocumentDemo
makingStudentInformationClone
oppositeAddToSetDemo
prettyDemo
returnOnlyUniqueValuesDemo
selectWhereInDemo
sourceCollection
studentInformation
sumOfValueDemo
truncateDemo
updateInformation
userInformation
col1
col2
indexingForArrayElementDemo
removeObjectFromArrayDemo
specifyAKeyDemo
useVariableDemo
ConvertStringToDateDemo
Employee_Information
IdUpdateDemo
IndexingDemo
NotAndDemo
ProductsInformation
addCurrentDateTimeDemo
addFieldDemo
aggregateSumDemo
aggregationSortDemo
andOrDemo
arrayInnerElementsDemo
arrayOfArraysDemo
avoidDuplicateEntriesDemo
caseInsensitiveDemo
castingDemo
changeDataType
checkFieldContainsStringDemo
checkFieldExistsOrNotDemo
collectionOnDifferentDocumentDemo
comparingTwoFieldsDemo
concatStringAndIntDemo
conditionalSumDemo
convertStringToNumberDemo
countDemo
createSequenceDemo
creatingUniqueIndexDemo
dateDemo
deleteAllElementsInArrayDemo
demo.insertCollection
distinctAggregation
distinctCountValuesDemo
distinctRecordDemo
doubleNestedArrayDemo
embeddedCollectionDemo
employeeInformation
fieldIsNullOrNotSetDemo
filterArray
findByMultipleArrayDemo
findDocumentWithObjectIdDemo
findDuplicateByKeyDemo
findDuplicateRecordsDemo
findMinValueDemo
firstDocumentDemo
getDistinctListOfSubDocumentFieldDemo
getIndexSizeDemo
getLastNRecordsDemo
getNThElementDemo
getSizeDemo
gettingHighestValueDemo
groupByDateDemo
incrementValueDemo
indexDemo
indexOptimizationDemo
indexingDemo
insertDemo
insertIfNotExistsDemo
insertOneRecordDemo
matchBetweenFieldsDemo
my-collection
nestedArrayDemo
nestedObjectDemo
new_Collection
numberofKeysInADocumentDemo
objectInAnArrayDemo
objectidToStringDemo
orConditionDemo
orderDocsDemo
paginationDemo
performRegex
priceStoredAsStringDemo
queryArrayElementsDemo
queryByKeyDemo
queryBySubFieldDemo
queryForBooleanFieldsDemo
queryToEmbeddedDocument
regexSearchDemo
removeArrayElement
removeDocumentOnBasisOfId
removeDuplicateDocumentDemo
renameFieldDemo
retrieveValueFromAKeyDemo
searchArrayDemo
searchDocumentDemo
searchMultipleFieldsDemo
selectInWhereIdDemo
selectSingleFieldDemo
sortDemo
sortInnerArrayDemo
sortingDemo
sqlLikeDemo
stringFieldLengthDemo
stringToObjectIdDemo
test.js
unwindOperatorDemo
updateDemo
updateExactField
updateManyDocumentsDemo
updateNestedValueDemo
updatingEmbeddedDocumentPropertyDemo
userStatus
...
※ 실제 출력 결과는 위 예시보다 훨씬 길며, 서버에 존재하는 모든 데이터베이스의 모든 컬렉션 이름이 순서대로 나열됩니다.
코드 주요 부분 해설
db.getSiblingDB("admin"): 현재 mongo 셸 세션을 유지한 상태에서 admin 데이터베이스로 전환합니다.runCommand({ "listDatabases": 1 }): 서버에 존재하는 모든 데이터베이스의 정보를 반환하는 관리자 명령입니다.db.getSiblingDB(databaseName.name): 반복문 안에서 각 데이터베이스 이름으로 컨텍스트를 전환합니다.db.getCollectionNames(): 현재 선택된 데이터베이스의 모든 컬렉션 이름을 배열 형태로 반환합니다.print(collectionName): 조회된 컬렉션 이름을 콘솔에 한 줄씩 출력합니다.
이처럼 listDatabases 명령과 getCollectionNames() 메서드를 조합하면, 별도의 GUI 도구 없이 mongo 셸만으로 서버 전체의 데이터베이스 및 컬렉션 구조를 손쉽게 파악할 수 있습니다.