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

MongoDB에서 점(.) 표기법으로 중첩 배열의 특정 요소 추출하기

MongoDB 중첩 배열에서 특정 요소 추출하기

MongoDB에서는 점(.) 표기법(dot notation)을 사용하면 여러 겹으로 중첩된 배열 안에서도 원하는 특정 요소를 손쉽게 추출할 수 있습니다. 이 글에서는 실제 예제를 통해 그 과정을 단계별로 살펴보겠습니다.

1단계: 샘플 컬렉션 생성

먼저 insertOne() 메서드를 사용해 문서가 포함된 컬렉션을 생성합니다.

> db.extractParticularElementDemo.insertOne(
... {
... "_id" : 101,
... "StudentName" : "John",
... "StudentInformation" : [
... {
... "Age" : 21,
... "StudentPersonalInformation" : [
... {
... "StudentNickName" : "Mike",
... "StudentFamilyDetails" : [
... {
... "FatherName" : "Carol"
... }
... ]
... },
... {
... "StudentAnotherName" : "David",
... "StudentFamilyDetails" : [
... {
... "FatherName" : "Robert"
... }
... ]
... }
... ]
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 101 }

2단계: 전체 문서 조회하기

find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.

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

위 쿼리는 다음과 같은 결과를 출력합니다.

{
"_id" : 101,
"StudentName" : "John",
"StudentInformation" : [
{
"Age" : 21,
"StudentPersonalInformation" : [
{
"StudentNickName" : "Mike",
"StudentFamilyDetails" : [
{
"FatherName" : "Carol"
}
]
},
{
"StudentAnotherName" : "David",
"StudentFamilyDetails" : [
{
"FatherName" : "Robert"
}
]
}
]
}
]
}

3단계: 점 표기법으로 특정 요소 추출하기

다음 쿼리는 점 표기법으로 필드 경로를 지정하여 FatherName이 'Carol'인 문서를 찾습니다. 두 번째 인자인 프로젝션(projection)에서 해당 필드에 1을 지정해 반환 대상에 포함하고, _id는 0으로 설정해 결과에서 제외했습니다.

> db.extractParticularElementDemo.find(
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':'Carol'},
... {'StudentInformation.StudentPersonalInformation.StudentFamilyDetails.FatherName':1,"_id":0}
... ).pretty();

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

{
"StudentInformation" : [
{
"StudentPersonalInformation" : [
{
"StudentFamilyDetails" : [
{
"FatherName" : "Carol"
}
]
},
{
"StudentFamilyDetails" : [
{
"FatherName" : "Robert"
}
]
}
]
}
]
}

참고: 배열 요소를 더 정밀하게 필터링하는 방법

위 프로젝션 방식은 조건에 일치하는 문서를 찾아 해당 경로의 전체 배열 구조를 반환합니다. 만약 일치하는 배열 요소만 정확히 골라내고 싶다면 위치 연산자($)나 애그리게이션의 $filter 연산자를 함께 사용하는 것이 좋습니다. 이를 통해 불필요한 요소까지 함께 출력되는 것을 방지하고, 원하는 데이터만 깔끔하게 추출할 수 있습니다.