문서 메뉴
문서 홈
/ / /
Java 동기화 드라이버
/

필드의 고유 값 가져오기

MongoCollection 객체에서 distinct() 메서드를 호출하여 컬렉션 전체에서 필드의 고유 값 목록을 검색할 수 있습니다. 아래와 같이 문서 필드 이름을 첫 번째 매개변수로 전달하고 결과를 변환하고자 하는 클래스를 두 번째 매개변수로 전달합니다.

collection.distinct("countries", String.class);

점 표기법을 사용하여 문서에 있는 필드 또는 포함된 문서 내에 있는 필드를 지정할 수 있습니다. 다음 메서드 호출은 awards 포함된 문서에 있는 wins 필드의 각 고유 값을 반환합니다.

collection.distinct("awards.wins", Integer.class);

선택적으로 메서드에 쿼리 필터를 전달하여 다음과 같이 MongoDB 인스턴스가 고유 값을 조회하는 문서 세트를 제한할 수 있습니다.

collection.distinct("type", Filters.eq("languages", "French"), String.class);

distinct() 메서드는 DistinctIterable 인터페이스를 구현하는 객체를 반환합니다. 이 인터페이스에는 결과를 액세스 및 구성하고 또 탐색하는 메서드가 포함되어 있습니다. 또한 첫 번째 결과를 반환하는 first(), MongoCursor의 인스턴스를 반환하는 cursor()와(과) 같이, 상위 인터페이스인 MongoIterable에서 메서드를 상속합니다.

다음 스니펫은 movies 컬렉션에서 year 문서 필드에 대한 고유 값 목록을 검색합니다. 쿼리 필터를 사용하여 directors 배열의 값에 'Carl Franklin'이 포함된 영화를 일치합니다.

참고

이 예제에서는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 알아보려면 연결 가이드를 참조하세요.

// Retrieves distinct values of a field by using the Java driver
package usage.examples;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.DistinctIterable;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
public class Distinct {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
try {
// Retrieves the distinct values of the "year" field present in documents that match the filter
DistinctIterable<Integer> docs = collection.distinct("year", Filters.eq("directors", "Carl Franklin"), Integer.class);
MongoCursor<Integer> results = docs.iterator();
// Prints the distinct "year" values
while(results.hasNext()) {
System.out.println(results.next());
}
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("An error occurred: " + me);
}
}
}
}

예제를 실행하면 Carl Franklin이 감독으로 포함된 모든 영화에 대해 각 연도를 보고하는 출력이 다음과 유사하게 표시되어야 합니다.

1992
1995
1998
...

레거시 API

레거시 API를 사용하는 경우 FAQ 페이지를 참조하여 코드 예제의 어떤 부분을 변경해야는지 확인하세요.

이 페이지에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 리소스를 참조하세요.

  • distinct() API 설명서

  • DistinctIterable API 설명서

  • 점 표기법으로 서버에 수동 입력

  • MongoIterable API 문서

← 문서 수 계산