MongoDB에서 집계 결과를 정렬하려면 aggregate() 메서드와 $sort 연산자를 함께 사용하면 됩니다. 개념을 쉽게 이해할 수 있도록, 문서가 포함된 컬렉션을 먼저 만들어 보겠습니다.
1. 샘플 컬렉션 생성하기
아래 쿼리를 사용해 문서를 포함한 컬렉션을 생성합니다.
> db.aggregationSortDemo.insertOne({"StudentId":98,"StudentFirstName":"John","StudentLastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90140c5705caea966c5587")
}
> db.aggregationSortDemo.insertOne({"StudentId":128,"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90141b5705caea966c5588")
}
> db.aggregationSortDemo.insertOne({"StudentId":110,"StudentFirstName":"David","StudentLastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90142f5705caea966c5589")
}
> db.aggregationSortDemo.insertOne({"StudentId":139,"StudentFirstName":"Chris","StudentLastName":"Brown"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90146a5705caea966c558a")
}
> db.aggregationSortDemo.insertOne({"StudentId":125,"StudentFirstName":"Sam","StudentLastName":"Williams"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9015695705caea966c558b")
}
> db.aggregationSortDemo.insertOne({"StudentId":139,"StudentFirstName":"Mike","StudentLastName":"Wilson"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c90158e5705caea966c558c")
}2. 저장된 문서 확인하기
find() 메서드를 사용하면 컬렉션의 모든 문서를 조회할 수 있습니다.
> db.aggregationSortDemo.find().pretty();
실행 결과는 다음과 같습니다.
{
"_id" : ObjectId("5c90140c5705caea966c5587"),
"StudentId" : 98,
"StudentFirstName" : "John",
"StudentLastName" : "Smith"
}
{
"_id" : ObjectId("5c90141b5705caea966c5588"),
"StudentId" : 128,
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor"
}
{
"_id" : ObjectId("5c90142f5705caea966c5589"),
"StudentId" : 110,
"StudentFirstName" : "David",
"StudentLastName" : "Miller"
}
{
"_id" : ObjectId("5c90146a5705caea966c558a"),
"StudentId" : 139,
"StudentFirstName" : "Chris",
"StudentLastName" : "Brown"
}
{
"_id" : ObjectId("5c9015695705caea966c558b"),
"StudentId" : 125,
"StudentFirstName" : "Sam",
"StudentLastName" : "Williams"
}
{
"_id" : ObjectId("5c90158e5705caea966c558c"),
"StudentId" : 139,
"StudentFirstName" : "Mike",
"StudentLastName" : "Wilson"
}3. 집계 파이프라인에서 $sort로 정렬하기
이제 MongoDB 집계에서 정렬을 수행하는 실제 쿼리를 살펴보겠습니다. 먼저 $group 단계로 StudentId별 등장 횟수를 집계한 뒤, $sort 단계에서 원하는 순서대로 정렬합니다.
Case 1 — 내림차순(DESC) 정렬
결과를 내림차순으로 정렬하고 싶다면 $sort 값에 -1을 지정합니다.
> db.aggregationSortDemo.aggregate( {$group: {_id: '$StudentId',"TotalOccurrences": {$sum: 1}}}, {$sort: {_id: -1}} ).pretty();실행 결과는 다음과 같습니다. StudentId가 큰 값부터 출력되는 것을 확인할 수 있습니다.
{ "_id" : 139, "TotalOccurrences" : 2 }
{ "_id" : 128, "TotalOccurrences" : 1 }
{ "_id" : 125, "TotalOccurrences" : 1 }
{ "_id" : 110, "TotalOccurrences" : 1 }
{ "_id" : 98, "TotalOccurrences" : 1 }Case 2 — 오름차순(ASC) 정렬
반대로 오름차순으로 정렬하고 싶다면 $sort 값에 1을 지정합니다.
> db.aggregationSortDemo.aggregate( {$group: {_id: '$StudentId', "TotalOccurrences": {$sum: 1}}}, {$sort: {_id: 1}} ).pretty();실행 결과는 다음과 같습니다. StudentId가 작은 값부터 순서대로 출력됩니다.
{ "_id" : 98, "TotalOccurrences" : 1 }
{ "_id" : 110, "TotalOccurrences" : 1 }
{ "_id" : 125, "TotalOccurrences" : 1 }
{ "_id" : 128, "TotalOccurrences" : 1 }
{ "_id" : 139, "TotalOccurrences" : 2 }정리
MongoDB의 집계 파이프라인에서 정렬은 $sort 연산자 하나로 간단히 처리할 수 있습니다. 핵심은 정렬 기준 필드에 대해 오름차순은 1, 내림차순은 -1을 지정한다는 점입니다. $group으로 데이터를 요약한 후 $sort를 이어 붙이면, 그룹화된 통계 결과도 손쉽게 원하는 순서로 정렬할 수 있습니다.