MongoDB에서 고유(distinct) 값 개수 세기
MongoDB에서 특정 필드의 고유한 값이 몇 개인지 확인하려면 distinct() 메서드와 length 속성을 함께 사용하면 됩니다. 기본 문법은 다음과 같습니다.
db.yourCollectionName.distinct("yourFieldName").length;먼저 예제로 사용할 컬렉션을 만들어 보겠습니다. 아래 명령으로 여러 개의 문서를 삽입합니다.
> db.countDistinctDemo.insertOne({"StudentName":"John"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6166de8cc557214c0dfa")
}
> db.countDistinctDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd616ade8cc557214c0dfb")
}
> db.countDistinctDemo.insertOne({"StudentName":"Chris"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd616cde8cc557214c0dfc")
}
> db.countDistinctDemo.insertOne({"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6170de8cc557214c0dfd")
}
> db.countDistinctDemo.insertOne({"StudentName":"David"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6175de8cc557214c0dfe")
}
> db.countDistinctDemo.insertOne({"StudentName":"Carol"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cbd6181de8cc557214c0dff")
}find() 메서드를 사용해 컬렉션에 저장된 모든 문서를 조회해 보겠습니다.
> db.countDistinctDemo.find().pretty();
위 쿼리를 실행하면 다음과 같은 결과가 출력됩니다.
{ "_id" : ObjectId("5cbd6166de8cc557214c0dfa"), "StudentName" : "John" }
{ "_id" : ObjectId("5cbd616ade8cc557214c0dfb"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cbd616cde8cc557214c0dfc"), "StudentName" : "Chris" }
{ "_id" : ObjectId("5cbd6170de8cc557214c0dfd"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5cbd6175de8cc557214c0dfe"), "StudentName" : "David" }
{ "_id" : ObjectId("5cbd6181de8cc557214c0dff"), "StudentName" : "Carol" }총 6개의 문서가 저장되어 있지만, 학생 이름을 보면 John, Chris, Carol, David로 중복된 값이 포함되어 있습니다. 이제 고유한 값의 개수를 세는 쿼리를 실행해 보겠습니다.
> db.countDistinctDemo.distinct("StudentName").length;실행 결과는 다음과 같습니다.
4
결과 설명
distinct("StudentName")은 StudentName 필드에서 중복을 제거한 값 목록인 ["John", "Chris", "Carol", "David"]를 반환합니다. 여기에 .length를 붙이면 배열의 길이, 즉 고유한 값의 개수인 4가 출력됩니다.
참고: 대량 데이터 처리 시 주의점
distinct() 메서드는 결과를 배열로 메모리에 로드하기 때문에 데이터 양이 매우 많은 경우 성능 문제가 발생할 수 있습니다. 이럴 때는 집계 파이프라인(aggregate)의 $group과 $sum 연산자를 활용하는 것이 더 효율적입니다.
> db.countDistinctDemo.aggregate([
{ $group: { _id: "$StudentName" } },
{ $count: "distinctCount" }
]);이 방식은 서버 측에서 집계를 수행하므로 대용량 컬렉션에서도 안정적으로 고유 값 개수를 구할 수 있습니다.