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

MongoDB에서 고유한 레코드 값 조회하기 – distinct() 메서드 완벽 가이드

MongoDB에서 특정 필드의 값을 중복 없이 조회하고 싶다면 distinct() 메서드를 사용하면 됩니다. 이 메서드는 컬렉션 안에서 지정한 필드의 고유한 값만 모아 배열 형태로 반환해 주기 때문에, 등록된 이름의 종류나 카테고리 목록 등을 확인할 때 매우 유용합니다.

distinct() 기본 문법

기본적인 사용 방법은 아래와 같습니다.

db.yourCollectionName.distinct("yourFieldName");

예제용 컬렉션 생성

문법을 제대로 이해하기 위해 학생 정보를 담은 컬렉션을 만들고 문서를 하나씩 삽입해 보겠습니다.

> db.distinctRecordDemo.insertOne({"StudentId":1,"StudentName":"John","StudentAge":21});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a78299b97a65744c1b50")
}
> db.distinctRecordDemo.insertOne({"StudentId":2,"StudentName":"John","StudentAge":22});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a78b99b97a65744c1b51")
}
> db.distinctRecordDemo.insertOne({"StudentId":3,"StudentName":"Carol","StudentAge":21});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a79a99b97a65744c1b52")
}
> db.distinctRecordDemo.insertOne({"StudentId":4,"StudentName":"Carol","StudentAge":26});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a7a499b97a65744c1b53")
}
> db.distinctRecordDemo.insertOne({"StudentId":5,"StudentName":"Sam","StudentAge":24});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a7b499b97a65744c1b54")
}
> db.distinctRecordDemo.insertOne({"StudentId":6,"StudentName":"Mike","StudentAge":27});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a7c799b97a65744c1b55")
}
> db.distinctRecordDemo.insertOne({"StudentId":7,"StudentName":"Sam","StudentAge":28});
{
    "acknowledged" : true,
    "insertedId" : ObjectId("5c77a7d399b97a65744c1b56")
}

find()로 전체 문서 확인

삽입된 문서가 정상적으로 저장되었는지 find() 메서드로 전체 데이터를 출력해 확인해 보겠습니다.

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

실행 결과는 다음과 같습니다.

{
    "_id" : ObjectId("5c77a78299b97a65744c1b50"),
    "StudentId" : 1,
    "StudentName" : "John",
    "StudentAge" : 21
}
{
    "_id" : ObjectId("5c77a78b99b97a65744c1b51"),
    "StudentId" : 2,
    "StudentName" : "John",
    "StudentAge" : 22
}
{
    "_id" : ObjectId("5c77a79a99b97a65744c1b52"),
    "StudentId" : 3,
    "StudentName" : "Carol",
    "StudentAge" : 21
}
{
    "_id" : ObjectId("5c77a7a499b97a65744c1b53"),
    "StudentId" : 4,
    "StudentName" : "Carol",
    "StudentAge" : 26
}
{
    "_id" : ObjectId("5c77a7b499b97a65744c1b54"),
    "StudentId" : 5,
    "StudentName" : "Sam",
    "StudentAge" : 24
}
{
    "_id" : ObjectId("5c77a7c799b97a65744c1b55"),
    "StudentId" : 6,
    "StudentName" : "Mike",
    "StudentAge" : 27
}
{
    "_id" : ObjectId("5c77a7d399b97a65744c1b56"),
    "StudentId" : 7,
    "StudentName" : "Sam",
    "StudentAge" : 28
}

고유한 레코드 값 조회하기

이제 distinct() 메서드를 사용해 각 필드의 고유한 값을 조회해 보겠습니다.

케이스 1: StudentName 필드

학생 이름(StudentName) 필드의 중복을 제거한 값을 구하는 쿼리입니다.

> db.distinctRecordDemo.distinct("StudentName");

실행 결과, 중복이 제거된 4개의 이름만 배열로 반환됩니다.

[ "John", "Carol", "Sam", "Mike" ]

케이스 2: StudentAge 필드

나이(StudentAge) 필드도 동일한 방식으로 조회할 수 있습니다.

> db.distinctRecordDemo.distinct("StudentAge");

결과는 다음과 같습니다.

[ 21, 22, 26, 24, 27, 28 ]

조건을 추가한 distinct() 활용

distinct() 메서드는 두 번째 인자로 쿼리 조건을 전달할 수도 있습니다. 예를 들어 나이가 25세 이상인 학생들의 이름만 고유하게 조회하려면 다음과 같이 작성합니다.

> db.distinctRecordDemo.distinct("StudentName", { "StudentAge": { $gte: 25 } });

이 경우 Carol(26), Mike(27), Sam(28) 세 명의 이름이 반환됩니다. 이처럼 distinct()를 활용하면 원하는 조건에 맞는 고유한 값들을 손쉽게 추출할 수 있으며, 대량의 데이터에서 중복 항목을 정리하거나 통계성 목록을 만들 때 특히 효과적입니다.