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

MongoDB에서 특정 필드를 가진 모든 컬렉션 찾기 – getCollectionNames() 활용법

MongoDB에서 특정 필드가 존재하는 컬렉션 전체 조회하기

여러 개의 컬렉션이 있는 데이터베이스에서 특정 필드(예: "StudentFirstName")를 포함하고 있는 컬렉션이 어떤 것들인지 한 번에 확인하고 싶은 경우가 있습니다. 이럴 때 db.getCollectionNames()$exists 연산자를 조합하면 손쉽게 해결할 수 있습니다.

먼저 기본 문법부터 살펴보겠습니다.

db.getCollectionNames().forEach(function(myCollectionName) {
    var frequency = db[myCollectionName].find({"필드명": {$exists: true}}).count();
    if (frequency > 0) {
        print(myCollectionName);
    }
});

위 문법의 동작 방식은 다음과 같습니다.

  • getCollectionNames()로 현재 데이터베이스의 모든 컬렉션 이름을 가져옵니다.
  • 각 컬렉션에 대해 $exists: true 조건으로 해당 필드가 존재하는 문서 수를 계산합니다.
  • 문서 수가 0보다 크면, 즉 해당 필드를 가진 컬렉션이면 컬렉션 이름을 출력합니다.

실제 예제: "StudentFirstName" 필드 찾기

이제 위 문법을 실제로 적용하여 "StudentFirstName"이라는 필드를 포함한 모든 컬렉션을 조회해 보겠습니다.

> db.getCollectionNames().forEach(function(myCollectionName) {
...     var frequency = db[myCollectionName].find({"StudentFirstName": {$exists: true}}).count();
...     if (frequency > 0) {
...         print(myCollectionName);
...     }
... });

실행 결과는 다음과 같습니다. 세 개의 컬렉션이 해당 필드를 포함하고 있는 것으로 확인됩니다.

multiDimensionalArrayProjection
removeKeyFieldsDemo
stringOrIntegerQueryDemo

결과 검증하기

조회된 컬렉션 중 하나인 removeKeyFieldsDemo에 실제로 "StudentFirstName" 필드가 존재하는지 직접 확인해 보겠습니다.

> db.removeKeyFieldsDemo.find({"StudentFirstName":{$exists:true}});

아래 출력 결과에서 볼 수 있듯이, 두 개의 문서 모두 "StudentFirstName" 필드를 정상적으로 포함하고 있습니다.

{ "_id" : ObjectId("5cc6c8289cb58ca2b005e672"), "StudentFirstName" : "John", "StudentLastName" : "Doe" }
{ "_id" : ObjectId("5cc6c8359cb58ca2b005e673"), "StudentFirstName" : "John", "StudentLastName" : "Smith" }

마무리

이처럼 getCollectionNames()$exists 연산자를 함께 사용하면, 대량의 컬렉션이 있더라도 특정 필드를 가진 컬렉션만 빠르게 필터링할 수 있습니다. 스키마가 유연한 MongoDB 환경에서 데이터 구조를 파악하거나 마이그레이션 작업 전 사전 점검을 할 때 매우 유용하게 활용할 수 있는 패턴입니다.