MongoDB의 집계(aggregation) 기능에서 문서를 오름차순으로 정렬하려면 $sort 스테이지를 사용하면 됩니다. 이 글에서는 실제 예제를 통해 컬렉션을 생성하고, 집계 파이프라인을 구성하여 데이터를 오름차순으로 정렬하는 과정을 단계별로 살펴보겠습니다.
1. 샘플 컬렉션 생성하기
먼저 insertOne() 메서드를 사용해 demo652라는 이름의 컬렉션에 문서 두 개를 삽입합니다. 각 문서는 value 필드와 상품 정보가 담긴 details 배열 필드로 구성되어 있습니다.
> db.demo652.insertOne({
value:10,
"details" : [{
"ProductName" : "Product-1",
"ProductQuantity" : 8,
"ProductPrice" : 500
}, {
"ProductName" : "Product-2",
"ProductQuantity" : 7,
"ProductPrice" : 500
}]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62")
}
>
> db.demo652.insertOne({
value:5,
"details" : [{
"ProductName" : "Product-1",
"ProductQuantity" : 8,
"ProductPrice" : 500
}, {
"ProductName" : "Product-2",
"ProductQuantity" : 7,
"ProductPrice" : 500
}]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63")
}2. 저장된 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.
> db.demo652.find();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{ "_id" : ObjectId("5e9f0730e3c3cd0dcff36a62"), "value" : 10, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }
{ "_id" : ObjectId("5e9f0740e3c3cd0dcff36a63"), "value" : 5, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }현재 문서들은 value 값이 10, 5 순서로 저장되어 있어 정렬되지 않은 상태입니다.
3. 집계 파이프라인으로 오름차순 정렬하기
이제 aggregate() 메서드와 여러 스테이지를 조합하여 문서를 오름차순으로 정렬해 보겠습니다. 사용된 주요 스테이지는 다음과 같습니다.
- $unwind:
details배열을 개별 문서로 분해합니다. - $match: 모든 문서를 통과시키는 빈 조건입니다.
- $group:
_id를 기준으로 그룹화하면서$first로 value 값을 가져오고,$push로 상품 이름을 배열로 재구성합니다. - $sort:
ProductPrice필드를 기준으로 1(오름차순) 정렬합니다. 내림차순이 필요하다면 값을 -1로 지정하면 됩니다. - $project: 출력 결과에서 필요한 필드만 선택적으로 노출합니다.
> db.demo652.aggregate([{
"$unwind": "$details"
}, {
"$match": {}
}, {
"$group": {
"ProductPrice": {
"$first": "$value"
},
"details": {
"$push": {
"ProductName": "$details.ProductName"
}
},
"_id": "$_id"
}
}, {
"$sort": {
"ProductPrice": 1
}
}, {
"$project": {
"_id": 0,
"ProductPrice": 1,
"details": 1
}
}]).pretty()4. 실행 결과 확인
위 집계 쿼리를 실행하면 다음과 같이 ProductPrice(원래의 value) 값이 작은 것부터 큰 것 순서, 즉 오름차순으로 정렬된 결과를 확인할 수 있습니다.
{
"ProductPrice" : 5,
"details" : [
{
"ProductName" : "Product-1"
},
{
"ProductName" : "Product-2"
}
]
}
{
"ProductPrice" : 10,
"details" : [
{
"ProductName" : "Product-1"
},
{
"ProductName" : "Product-2"
}
]
}마무리
이처럼 MongoDB에서는 $sort 스테이지를 활용하면 집계 파이프라인 내에서 손쉽게 문서를 오름차순 또는 내림차순으로 정렬할 수 있습니다. $sort 값으로 1을 지정하면 오름차순, -1을 지정하면 내림차순으로 동작한다는 점만 기억하면 됩니다. 대량의 데이터를 처리할 때는 인덱스를 함께 활용하면 정렬 성능을 더욱 향상시킬 수 있습니다.