MongoDB에서 특정 필드의 중복을 제거한 고유한 값(distinct)을 추출하면서 동시에 정렬된 결과까지 얻고 싶다면, distinct() 메서드와 자바스크립트 배열의 sort() 메서드를 조합하면 아주 간단하게 해결할 수 있습니다.
기본 문법
컬렉션에서 고유한 값을 정렬하여 가져오는 쿼리 구문은 다음과 같습니다.
db.yourCollectionName.distinct("yourFieldName").sort();distinct() 메서드는 지정한 필드에서 중복을 제거한 값들을 배열 형태로 반환합니다. 이 배열은 일반적인 자바스크립트 배열이므로, 뒤에 .sort()를 붙이면 오름차순으로 정렬된 결과를 얻을 수 있습니다.
예제 컬렉션 생성
실습을 위해 먼저 학생 정보가 담긴 컬렉션을 만들고 문서를 삽입해 보겠습니다. 중복 제거 효과를 확인할 수 있도록 StudentId 10, 20, 40에 해당하는 중복 데이터를 의도적으로 포함시켰습니다.
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e3315e86fd1496b38c3")
}
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e3e15e86fd1496b38c4")
}
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":10,"StudentName":"John","StudentAge":23});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e4415e86fd1496b38c5")
}
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":30,"StudentName":"Chris","StudentAge":22});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e5115e86fd1496b38c6")
}
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":20,"StudentName":"Carol","StudentAge":21});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e5715e86fd1496b38c7")
}
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e6515e86fd1496b38c8")
}
> db.getDistinctWithSortedDataDemo.insertOne({"StudentId":40,"StudentName":"Bob","StudentAge":20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9b1e6d15e86fd1496b38c9")
}저장된 문서 확인하기
find() 메서드를 사용하면 컬렉션에 저장된 모든 문서를 확인할 수 있습니다.
> db.getDistinctWithSortedDataDemo.find().pretty();
위 쿼리를 실행하면 다음과 같이 총 7개의 문서가 출력됩니다.
{
"_id" : ObjectId("5c9b1e3315e86fd1496b38c3"),
"StudentId" : 10,
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9b1e3e15e86fd1496b38c4"),
"StudentId" : 20,
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9b1e4415e86fd1496b38c5"),
"StudentId" : 10,
"StudentName" : "John",
"StudentAge" : 23
}
{
"_id" : ObjectId("5c9b1e5115e86fd1496b38c6"),
"StudentId" : 30,
"StudentName" : "Chris",
"StudentAge" : 22
}
{
"_id" : ObjectId("5c9b1e5715e86fd1496b38c7"),
"StudentId" : 20,
"StudentName" : "Carol",
"StudentAge" : 21
}
{
"_id" : ObjectId("5c9b1e6515e86fd1496b38c8"),
"StudentId" : 40,
"StudentName" : "Bob",
"StudentAge" : 20
}
{
"_id" : ObjectId("5c9b1e6d15e86fd1496b38c9"),
"StudentId" : 40,
"StudentName" : "Bob",
"StudentAge" : 20
}StudentName 필드의 고유한 값 정렬해서 조회하기
이제 “StudentName” 필드의 중복을 제거하고 이름순으로 정렬된 값을 조회해 보겠습니다.
> db.getDistinctWithSortedDataDemo.distinct("StudentName").sort();실행 결과는 다음과 같습니다.
[ "Bob", "Carol", "Chris", "John" ]
중복되었던 이름들이 모두 제거되고, 알파벳 오름차순으로 깔끔하게 정렬된 것을 확인할 수 있습니다.
StudentAge 필드의 고유한 값 정렬해서 조회하기
같은 방식으로 나이 필드인 “StudentAge”에도 적용해 보겠습니다.
> db.getDistinctWithSortedDataDemo.distinct("StudentAge").sort();실행 결과는 다음과 같습니다.
[ 20, 21, 22, 23 ]
숫자형 데이터 역시 중복 제거 후 오름차순으로 정상적으로 정렬되는 것을 볼 수 있습니다.
마무리 및 참고 사항
이처럼 MongoDB에서 distinct()와 sort()를 조합하면 복잡한 애그리게이션 파이프라인 없이도 고유한 값을 손쉽게 정렬하여 조회할 수 있습니다. 다만 이 방식은 셸(클라이언트) 측에서 반환된 배열을 정렬하는 것이므로, 결과 값이 매우 많은 경우에는 성능을 고려해야 합니다. 또한 자바스크립트의 기본 sort()는 요소를 문자열로 변환해 비교하므로, 두 자릿수 이상이 섞인 숫자 데이터를 정확히 정렬하려면 .sort((a, b) => a - b)처럼 비교 함수를 사용하는 것이 안전합니다. 내림차순이 필요하다면 .sort().reverse()를 활용하면 됩니다.