MongoDB에서 문서 내 하위 배열(sub-array)에 포함된 값들 중 가장 높은 값을 찾으려면 애그리게이션 프레임워크(Aggregation Framework)를 활용하는 것이 가장 효과적입니다. 이 글에서는 실제 예제를 통해 단계별로 살펴보겠습니다.
1. 샘플 컬렉션 생성하기
먼저 학생 정보와 수학 점수를 담고 있는 문서들을 포함한 컬렉션을 생성합니다. 각 문서는 여러 학생의 이름과 점수를 배열 형태로 가지고 있습니다.
> db.findHighestValueDemo.insertOne(
... {
... _id: 10001,
... "StudentDetails": [
... { "StudentName": "Chris", "StudentMathScore": 56},
... { "StudentName": "Robert", "StudentMathScore":47 },
... { "StudentName": "John", "StudentMathScore": 98 }]
... }
... );
{ "acknowledged" : true, "insertedId" : 10001 }
> db.findHighestValueDemo.insertOne(
... {
... _id: 10002,
... "StudentDetails": [
... { "StudentName": "Ramit", "StudentMathScore": 89},
... { "StudentName": "David", "StudentMathScore":76 },
... { "StudentName": "Bob", "StudentMathScore": 97 }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : 10002 }2. 저장된 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.
> db.findHighestValueDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{
"_id" : 10001,
"StudentDetails" : [
{
"StudentName" : "Chris",
"StudentMathScore" : 56
},
{
"StudentName" : "Robert",
"StudentMathScore" : 47
},
{
"StudentName" : "John",
"StudentMathScore" : 98
}
]
}
{
"_id" : 10002,
"StudentDetails" : [
{
"StudentName" : "Ramit",
"StudentMathScore" : 89
},
{
"StudentName" : "David",
"StudentMathScore" : 76
},
{
"StudentName" : "Bob",
"StudentMathScore" : 97
}
]
}3. 애그리게이션으로 최댓값 찾기
이제 하위 배열에서 가장 높은 값을 찾는 핵심 쿼리입니다. 애그리게이션 파이프라인은 다음 네 단계로 구성됩니다.
- $project: 필요한 필드(학생 이름, 수학 점수)만 선택하여 출력 형태를 정의합니다.
- $unwind:
StudentDetails배열을 개별 문서로 분해합니다. - $sort: 수학 점수를 기준으로 내림차순(-1) 정렬합니다.
- $limit: 정렬된 결과 중 첫 번째 문서, 즉 최댓값만 반환합니다.
> db.findHighestValueDemo.aggregate([
... {$project:{"StudentDetails.StudentName":1, "StudentDetails.StudentMathScore":1}},
... {$unwind:"$StudentDetails"},
... {$sort:{"StudentDetails.StudentMathScore":-1}},
... {$limit:1}
... ]).pretty();4. 실행 결과
위 애그리게이션 쿼리를 실행하면 전체 데이터 중 가장 높은 수학 점수를 가진 학생이 출력됩니다.
{
"_id" : 10001,
"StudentDetails" : {
"StudentName" : "John",
"StudentMathScore" : 98
}
}결과를 보면 두 번째 문서의 Bob(97점)보다 높은 98점을 받은 John이 최종 선택된 것을 확인할 수 있습니다. 이처럼 $unwind와 $sort, $limit를 조합하면 여러 문서에 흩어져 있는 하위 배열의 값들까지 하나의 기준으로 비교하여 최댓값을 손쉽게 찾을 수 있습니다.