MongoDB에서 컬렉션 전체 목록 확인하는 방법
MongoDB에서 특정 데이터베이스에 속한 모든 컬렉션의 목록을 조회하려면, 먼저 해당 데이터베이스로 전환해야 합니다. use 명령어를 사용해 대상 데이터베이스로 이동한 뒤, 컬렉션 목록을 가져오는 쿼리를 실행할 수 있습니다.
방법 1: db.getCollectionNames() 사용
먼저 use 명령어로 데이터베이스를 전환한 후, db.getCollectionNames() 메서드를 호출하면 해당 데이터베이스의 모든 컬렉션 이름이 배열 형태로 반환됩니다.
> use sample; switched to db sample > db.getCollectionNames();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
[
"copyThisCollectionToSampleDatabaseDemo",
"deleteDocuments",
"deleteDocumentsDemo",
"deleteInformation",
"employee",
"internalArraySizeDemo",
"sourceCollection",
"updateInformation",
"userInformation"
]방법 2: show collections 명령어 사용
더 간단한 대안으로, show collections 명령어를 사용할 수도 있습니다. 이 명령어는 현재 접속 중인 데이터베이스의 컬렉션 목록을 한 줄씩 출력해 주므로, mongo 셸에서 빠르게 확인할 때 유용합니다.
> show collections;
실행 결과는 다음과 같습니다.
copyThisCollectionToSampleDatabaseDemo deleteDocuments deleteDocumentsDemo deleteInformation employee internalArraySizeDemo sourceCollection updateInformation userInformation
정리
두 가지 방법 모두 동일한 컬렉션 목록을 반환하지만, 용도에 따라 선택하면 됩니다. 프로그래밍 방식으로 결과를 활용해야 한다면 배열을 반환하는 db.getCollectionNames()가 적합하고, 셸에서 단순히 눈으로 확인하는 경우라면 show collections가 더 편리합니다.