Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB 셸에서 모든 컬렉션 목록을 확인하는 방법

MongoDB 셸에서 모든 컬렉션 나열하기

MongoDB 셸(mongo shell)에서 현재 데이터베이스에 포함된 모든 컬렉션의 목록을 확인하려면 getCollectionNames() 함수를 사용할 수 있습니다.

사용 문법은 다음과 같습니다.

db.getCollectionNames();

또한 show collections 명령어를 사용해도 동일하게 컬렉션 목록을 조회할 수 있습니다.

show collections;

아래에서 두 가지 방법의 실제 실행 예시와 출력 결과를 살펴보겠습니다.

1. getCollectionNames() 함수로 컬렉션 목록 조회

먼저 첫 번째 방법인 getCollectionNames() 함수를 호출합니다.

> db.getCollectionNames();

이 함수는 컬렉션 이름들을 문자열 배열 형태로 반환하며, 실행 결과는 다음과 같습니다.

[
  "ConvertStringToDateDemo",
  "IdUpdateDemo",
  "ProductsInformation",
  "addFieldDemo",
  "addNewFieldToEveryDocument",
  "arrayInnerElementsDemo",
  "arrayLengthGreaterThanOne",
  "arrayOfArraysDemo",
  "caseInsensitiveDemo",
  "changeDataType",
  "changeType",
  "charactersAllowedDemo",
  "charactersDemo",
  "checkFieldContainsStringDemo",
  "checkSequenceDemo",
  "combinationOfArrayDemo",
  "conditionalSumDemo",
  "convertStringToNumberDemo",
  "copyThisCollectionToSampleDatabaseDemo",
  "countDemo",
  "createSequenceDemo",
  "distinctCountValuesDemo",
  "distinctRecordDemo",
  "distinctWithMultipleKeysDemo",
  "employeeInformation",
  "filterArray",
  "findAllDuplicateKeyDocumentDemo",
  "findByMultipleArrayDemo",
  "findDuplicateByKeyDemo",
  "findDuplicateRecordsDemo",
  "findSpecificValue",
  "findValueInArrayWithMultipleCriteriaDemo",
  "getLastNRecordsDemo",
  "getParticularElementFromArrayDemo",
  "getPartuclarElement",
  "getSizeOfArray",
  "groupByDateDemo",
  "incrementValueInNestedArrayDemo",
  "insertIfNotExistsDemo",
  "nestedArrayDemo",
  "notLikeOpeartorDemo",
  "regExpOnIntegerDemo",
  "removeArrayDemo",
  "removeArrayElement",
  "removeArrayElements",
  "removeDuplicateDocumentDemo",
  "removeElementFromDoublyNestedArrayDemo",
  "removeFieldCompletlyDemo",
  "removeObject",
  "renameFieldDemo",
  "reverseRegexDemo",
  "searchArrayDemo",
  "selectSingleFieldDemo",
  "singleFieldDemo",
  "sortDemo",
  "sortInnerArrayDemo",
  "sourceCollection",
  "stringFieldLengthDemo",
  "test.js",
  "uniqueIndexOnArrayDemo",
  "unwindOperatorDemo",
  "updateExactField",
  "updateIdDemo",
  "updateObjects"
]

2. show collections 명령어로 컬렉션 목록 조회

두 번째 방법은 MongoDB 셸에서 기본적으로 제공하는 헬퍼 명령어인 show collections를 사용하는 것입니다.

> show collections;

실행 결과는 다음과 같으며, 앞서 본 함수와 동일한 컬렉션 목록을 한 줄씩 출력합니다.

ConvertStringToDateDemo
IdUpdateDemo
ProductsInformation
addFieldDemo
addNewFieldToEveryDocument
arrayInnerElementsDemo
...
uniqueIndexOnArrayDemo
unwindOperatorDemo
updateExactField
updateIdDemo
updateObjects

두 방법의 차이점과 활용 팁

  • getCollectionNames(): 결과를 자바스크립트 배열로 반환하므로, 스크립트 안에서 반복문으로 각 컬렉션을 순회하거나 조건에 따라 필터링하는 등 프로그래밍 방식의 활용에 적합합니다.
  • show collections: 대화형 환경에서 빠르게 목록을 눈으로 확인할 때 편리한 헬퍼 명령어입니다.
  • 두 방법 모두 use 데이터베이스명으로 현재 선택된 데이터베이스를 기준으로 동작하므로, 먼저 대상 데이터베이스를 선택한 후 실행해야 합니다.