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

MongoDB에서 값으로 중첩된 사전(Dictionary) 구조 검색하는 방법

MongoDB에서 값으로 사전 구조 찾기

MongoDB에서는 find() 메서드를 사용하여 중첩된 문서(사전과 유사한 구조) 내부의 특정 값을 기준으로 데이터를 손쉽게 조회할 수 있습니다. 이 글에서는 실제 예제를 통해 컬렉션을 생성하고, 점 표기법(dot notation)을 활용해 원하는 값을 검색하는 방법을 단계별로 살펴보겠습니다.

1. 샘플 컬렉션 생성하기

먼저 고객 정보가 중첩된 문서 형태로 저장된 컬렉션을 만들어 보겠습니다. insertOne() 메서드를 사용하여 두 개의 문서를 삽입합니다.

> db.findInDictionaryDemo.insertOne(
...     {
...        "_id":101,
...        "AllCustomerDetails":
...        {
...           "SomeCustomerDetail1":
...           {
...              "CustomerName1":"John Doe",
...              "CustomerName2":"John Smith"
...           },
...           "SomeCustomerDetail2":
...           {
...              "CustomerName1":"Carol Taylor",
...              "CustomerName2":"David Miller"
...           }
...        }
...     }
... );
{ "acknowledged" : true, "insertedId" : 101 }

같은 방식으로 두 번째 문서도 추가합니다.

> db.findInDictionaryDemo.insertOne(
...     {
...        "_id":102,
...        "AllCustomerDetails":
...        {
...           "SomeCustomerDetail1":
...           {
...              "CustomerName1":"Sam Wiliams",
...              "CustomerName2":"Bob Johnson"
...           },
...           "SomeCustomerDetail2":
...           {
...              "CustomerName1":"Chris Brown",
...              "CustomerName2":"Mike Wilson"
...           }
...        }
...     }
... );
{ "acknowledged" : true, "insertedId" : 102 }

2. 저장된 전체 문서 확인하기

find() 메서드에 pretty()를 함께 사용하면 저장된 모든 문서를 가독성 좋게 출력할 수 있습니다.

> db.findInDictionaryDemo.find().pretty();

위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.

{
    "_id" : 101,
    "AllCustomerDetails" : {
       "SomeCustomerDetail1" : {
          "CustomerName1" : "John Doe",
          "CustomerName2" : "John Smith"
       },
       "SomeCustomerDetail2" : {
          "CustomerName1" : "Carol Taylor",
          "CustomerName2" : "David Miller"
       }
    }
}
{
    "_id" : 102,
    "AllCustomerDetails" : {
       "SomeCustomerDetail1" : {
          "CustomerName1" : "Sam Wiliams",
          "CustomerName2" : "Bob Johnson"
       },
       "SomeCustomerDetail2" : {
          "CustomerName1" : "Chris Brown",
          "CustomerName2" : "Mike Wilson"
       }
    }
}

3. 값으로 사전 구조 검색하기

이제 핵심인 조회 방법입니다. MongoDB에서는 점 표기법(dot notation)을 사용하여 중첩된 필드 경로를 지정하고, 해당 위치의 값과 일치하는 문서를 찾을 수 있습니다. 예를 들어 AllCustomerDetails.SomeCustomerDetail2.CustomerName2 필드의 값이 "Mike Wilson"인 문서를 검색하려면 다음과 같이 작성합니다.

> db.findInDictionaryDemo.find({"AllCustomerDetails.SomeCustomerDetail2.CustomerName2":"Mike Wilson"}).pretty();

실행 결과는 다음과 같습니다.

{
    "_id" : 102,
    "AllCustomerDetails" : {
       "SomeCustomerDetail1" : {
          "CustomerName1" : "Sam Wiliams",
          "CustomerName2" : "Bob Johnson"
       },
       "SomeCustomerDetail2" : {
          "CustomerName1" : "Chris Brown",
          "CustomerName2" : "Mike Wilson"
       }
    }
}

정리 및 참고 사항

점 표기법을 활용하면 몇 단계로 중첩되어 있더라도 정확한 필드 경로만 지정하면 원하는 값을 가진 문서를 빠르게 찾을 수 있습니다. 다만 몇 가지 주의할 점이 있습니다.

  • 따옴표 사용: 점 표기법으로 작성된 필드 경로는 반드시 문자열로 감싸야 합니다. 예: {"a.b.c": value}
  • 정확한 경로 지정: 필드 이름이 하나라도 다르면 일치하는 결과가 반환되지 않으므로, 스키마 구조를 미리 파악하는 것이 좋습니다.
  • 인덱스 활용: 중첩 필드에 인덱스를 생성하면 대량의 데이터에서도 검색 성능을 크게 향상시킬 수 있습니다. 예: db.collection.createIndex({"AllCustomerDetails.SomeCustomerDetail2.CustomerName2": 1})

이처럼 MongoDB의 find()와 점 표기법을 조합하면 복잡하게 중첩된 사전형 구조 안에서도 특정 값을 기준으로 간단하고 직관적으로 문서를 조회할 수 있습니다.