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

MongoDB에서 점(.) 표기법으로 중첩 문자열 배열 쿼리하는 방법

MongoDB에서 중첩된 문자열 배열을 조회하려면 점(.) 표기법(dot notation)을 사용하면 됩니다. 이번 글에서는 실제 예제를 통해 문서를 생성하고, 점 표기법으로 중첩 배열 내부의 값을 쿼리하는 방법을 단계별로 살펴보겠습니다.

1. 샘플 컬렉션 생성하기

먼저 insertOne() 메서드를 사용해 고객 정보를 담은 문서 두 개를 'nestedStringDemo' 컬렉션에 삽입합니다.

> db.nestedStringDemo.insertOne(
    {
       "CustomerName": "John",
       "CustomerOtherDetails": [ { "Age":29, "CountryName": "US" },
       { "CompanyName": "Amazon",
       "Salary": 150000, "ProjectName": ["Online Library Management System", "Pig Dice Game"]
     } ] }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cea4629ef71edecf6a1f690")
}
> db.nestedStringDemo.insertOne(
{
   "CustomerName": "Chris",
   "CustomerOtherDetails": [ { "Age":27, "CountryName": "AUS" },
   { "CompanyName": "Google",
      "Salary": 250000, "ProjectName": ["Chat Application", "Game Design"]
   } ] }
);
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cea466eef71edecf6a1f691")
}

2. 전체 문서 조회하기

find() 메서드와 pretty()를 함께 사용하면 컬렉션의 모든 문서를 보기 좋게 출력할 수 있습니다.

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

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

{
   "_id" : ObjectId("5cea4629ef71edecf6a1f690"),
   "CustomerName" : "John",
   "CustomerOtherDetails" : [
      {
         "Age" : 29,
         "CountryName" : "US"
      },
      {
         "CompanyName" : "Amazon",
         "Salary" : 150000,
         "ProjectName" : [
            "Online Library Management System",
            "Pig Dice Game"
         ]
      }
   ]
}
{
   "_id" : ObjectId("5cea466eef71edecf6a1f691"),
   "CustomerName" : "Chris",
   "CustomerOtherDetails" : [
      {
         "Age" : 27,
         "CountryName" : "AUS"
      },
      {
         "CompanyName" : "Google",
         "Salary" : 250000,
         "ProjectName" : [
            "Chat Application",
            "Game Design"
         ]
      }
   ]
}

3. 점 표기법으로 중첩 문자열 배열 쿼리하기

이제 'CustomerOtherDetails' 필드 안에 있는 'ProjectName' 배열에서 특정 프로젝트 이름을 가진 문서를 찾아보겠습니다. 상위 필드와 하위 필드를 마침표(.)로 연결한 경로를 조건으로 지정하면 됩니다.

> db.nestedStringDemo.find({"CustomerOtherDetails.ProjectName":"Chat Application"}).pretty();

쿼리를 실행하면 'Chat Application'이라는 프로젝트 이름을 포함하고 있는 Chris의 문서만 반환되는 것을 확인할 수 있습니다.

{
   "_id" : ObjectId("5cea466eef71edecf6a1f691"),
   "CustomerName" : "Chris",
   "CustomerOtherDetails" : [
      {
         "Age" : 27,
         "CountryName" : "AUS"
      },
      {
         "CompanyName" : "Google",
         "Salary" : 250000,
         "ProjectName" : [
            "Chat Application",
            "Game Design"
         ]
      }
   ]
}

정리

MongoDB에서는 점 표기법을 활용하면 배열 내부에 중첩된 필드나 문자열 값도 복잡한 연산자 없이 간단하게 조회할 수 있습니다. '상위필드.배열요소필드' 형태로 조건을 지정하면, 해당 배열 안에 일치하는 값이 하나라도 존재하는 문서가 결과로 반환됩니다. 이 방식은 깊게 중첩된 문서 구조에서도 유연하게 적용할 수 있어 실무에서 매우 자주 활용됩니다.