Computer >> 컴퓨터 >  >> 프로그래밍 >> MongoDB

MongoDB에서 여러 키 조합으로 고유(distinct) 값을 효율적으로 조회하는 방법

MongoDB에서 여러 키로 고유(distinct) 값 구하기

MongoDB의 집계 프레임워크(Aggregation Framework)를 활용하면 여러 개의 키를 조합하여 고유(distinct)한 값을 손쉽게 추출할 수 있습니다. 일반적인 distinct() 메서드는 단일 필드에 대한 고유 값만 지원하지만, $group 연산자를 사용하면 복수 필드의 조합 기준으로 중복을 제거할 수 있습니다.

개념을 이해하기 위해 먼저 샘플 문서가 포함된 컬렉션을 생성해 보겠습니다. 아래 쿼리는 distinctWithMultipleKeysDemo 컬렉션에 학생 정보 문서를 삽입하는 예제입니다.

> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7f74488d10a061296a3c53")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Mike","StudentAge":22,"StudentMathMarks":56});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7f744b8d10a061296a3c54")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7f74598d10a061296a3c55")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Bob","StudentAge":23,"StudentMathMarks":45});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7f745e8d10a061296a3c56")
}
> db.distinctWithMultipleKeysDemo.insertOne({"StudentName":"Carol","StudentAge":27,"StudentMathMarks":54});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c7f74688d10a061296a3c57")
}

컬렉션의 전체 문서 확인

find() 메서드를 사용하여 컬렉션에 저장된 모든 문서를 조회할 수 있습니다.

> db.distinctWithMultipleKeysDemo.find().pretty();

위 쿼리의 실행 결과는 다음과 같습니다. Mike와 Bob의 데이터가 각각 두 번씩 중복되어 저장된 것을 확인할 수 있습니다.

{
    "_id" : ObjectId("5c7f74488d10a061296a3c53"),
    "StudentName" : "Mike",
    "StudentAge" : 22,
    "StudentMathMarks" : 56
}
{
    "_id" : ObjectId("5c7f744b8d10a061296a3c54"),
    "StudentName" : "Mike",
    "StudentAge" : 22,
    "StudentMathMarks" : 56
}
{
    "_id" : ObjectId("5c7f74598d10a061296a3c55"),
    "StudentName" : "Bob",
    "StudentAge" : 23,
    "StudentMathMarks" : 45
}
{
    "_id" : ObjectId("5c7f745e8d10a061296a3c56"),
    "StudentName" : "Bob",
    "StudentAge" : 23,
    "StudentMathMarks" : 45
}
{
    "_id" : ObjectId("5c7f74688d10a061296a3c57"),
    "StudentName" : "Carol",
    "StudentAge" : 27,
    "StudentMathMarks" : 54
}

$group 연산자로 여러 키의 고유 조합 조회

이제 aggregate() 파이프라인과 $group 연산자를 사용하여 StudentName과 StudentAge 두 키의 조합을 기준으로 고유한 결과를 추출해 보겠습니다.

> c = db.distinctWithMultipleKeysDemo;
test.distinctWithMultipleKeysDemo
> myResult = c.aggregate( [ {"$group": { "_id": { StudentName:"$StudentName", StudentAge: "$StudentAge" } } } ] );

실행 결과는 다음과 같습니다. 이름과 나이가 동일한 중복 문서는 하나로 그룹화되어, 세 가지 고유한 조합만 반환됩니다.

{ "_id" : { "StudentName" : "Carol", "StudentAge" : 27 } }
{ "_id" : { "StudentName" : "Bob", "StudentAge" : 23 } }
{ "_id" : { "StudentName" : "Mike", "StudentAge" : 22 } }

정리

MongoDB에서 여러 키를 기준으로 고유한 값을 얻으려면 aggregate()$group 단계에서 _id 필드에 원하는 키들을 객체 형태로 지정하면 됩니다. 이 방식은 단순히 중복을 제거하는 것뿐만 아니라, 그룹별 카운트($sum)나 평균($avg) 등 추가 집계 연산과 결합하여 더욱 강력하게 활용할 수 있습니다.