MongoDB에서 aggregate()와 $unwind 연산자를 함께 사용하면 여러 단계로 중첩된 하위 목록(sub-list)을 하나로 펼쳐 연결할 수 있습니다. 이번 글에서는 실제 예제를 바탕으로 그 과정을 단계별로 살펴보겠습니다.
1. 샘플 컬렉션 생성하기
먼저 중첩된 배열 구조를 가진 문서를 삽입하여 컬렉션을 만들어 보겠습니다.
> db.demo70.insertOne(
... {
... "first" : [
... {
... "details" : {
... "second" : [
... {
... "StudentDetails" : {
... "Score" : 10
... }
... },
... {
... "StudentDetails" : {
... "Score" : 20
... }
... },
... {
... "StudentDetails" : {
... "Score" : 30
... }
... }
... ]
... }
... },
... {
... "details" : {
... "second" : [
... {
... "StudentDetails" : {
... "Score" : 11
... }
... },
... {
... "StudentDetails" : {
... "Score" : 18
... }
... },
... {
... "StudentDetails" : {
... "Score" : 29
... }
... }
... ]
... }
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e29ad4d0912fae76b13d76d")
}
2. 저장된 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.
> db.demo70.find().pretty();
위 명령을 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : ObjectId("5e29ad4d0912fae76b13d76d"),
"first" : [
{
"details" : {
"second" : [
{
"StudentDetails" : {
"Score" : 10
}
},
{
"StudentDetails" : {
"Score" : 20
}
},
{
"StudentDetails" : {
"Score" : 30
}
}
]
}
},
{
"details" : {
"second" : [
{
"StudentDetails" : {
"Score" : 11
}
},
{
"StudentDetails" : {
"Score" : 18
}
},
{
"StudentDetails" : {
"Score" : 29
}
}
]
}
}
]
}
3. 깊은 하위 목록을 연결하는 집계 쿼리
이제 $unwind를 두 번 적용해 중첩 배열을 모두 펼친 뒤, 점수(Score)를 기준으로 정렬하고 상위 3개의 결과만 추출하는 집계 파이프라인을 작성합니다.
> db.demo70.aggregate([
... { $unwind: "$first" },
... { $unwind: "$first.details.second" },
... { $sort: { "first.details.second.StudentDetails.Score": -1 } },
... { $limit: 3 },
... { $replaceRoot: { newRoot: "$first.details.second.StudentDetails" } },
... { $sort: { "Score": 1 } }
... ]);
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{ "Score" : 20 }
{ "Score" : 29 }
{ "Score" : 30 }
쿼리 동작 방식 살펴보기
- $unwind: "$first" — first 배열의 각 요소를 개별 문서로 분리합니다.
- $unwind: "$first.details.second" — second 배열을 한 번 더 펼쳐 모든 StudentDetails 객체를 독립적인 문서로 만듭니다.
- $sort + $limit — Score를 내림차순으로 정렬한 뒤 상위 3개 문서만 남깁니다.
- $replaceRoot — StudentDetails 객체를 새로운 루트 문서로 지정합니다.
- $sort: { "Score": 1 } — 최종 결과를 점수 오름차순으로 정렬하여 반환합니다.
이처럼 $unwind를 단계적으로 적용하면 아무리 깊게 중첩된 배열이라도 손쉽게 평탄화(flatten)하여 원하는 형태의 데이터를 추출할 수 있습니다.