Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Node.js 드라이버
/ /

Retrieve Distinct Values

컬렉션 전체에서 지정된 필드에 대한 모든 고유 값을 검색하려면 distinct() 메서드를 사용합니다.

이 가이드의 예제를 수행하려면 다음 코드 스니펫을 사용하여 레스토랑을 설명하는 문서를 myDB.restaurants collection에 삽입하세요.

const myDB = client.db("myDB");
const myColl = myDB.collection("restaurants");
await myColl.insertMany([
{ "_id": 1, "restaurant": "White Bear", "borough": "Queens", "cuisine": "Chinese" },
{ "_id": 2, "restaurant": "Via Carota", "borough": "Manhattan", "cuisine": "Italian" },
{ "_id": 3, "restaurant": "Borgatti's", "borough": "Bronx", "cuisine": "Italian" },
{ "_id": 4, "restaurant": "Tanoreen", "borough": "Brooklyn", "cuisine": "Middle Eastern" },
{ "_id": 5, "restaurant": "Äpfel", "borough": "Queens", "cuisine": "German" },
{ "_id": 6, "restaurant": "Samba Kitchen", "borough": "Manhattan", "cuisine": "Brazilian" },
]);

참고

쿼리 작업은 일치하는 문서가 포함된 커서 에 대한 참조를 반환할 수 있습니다. 커서에 저장된 데이터를 검사하는 방법을 학습하려면 커서에서 데이터 액세스 페이지를 참조하세요.

distinct() 메서드에서는 문서 필드를 매개 변수로 사용해야 합니다. 다음과 같은 선택적 매개변수를 지정하여 메서드 출력을 조정할 수 있습니다.

  • 결과를 구체화하는 query 매개변수

  • 데이터 정렬 규칙을 설정하는 options 매개변수

문서 필드의 이름을 전달하여 필드의 고유 값 목록을 반환합니다.

"Queens""Manhattan" 자치구 값은 샘플 문서에 각각 두 번 이상 표시됩니다. 그러나 다음 예제에서는 borough 필드의 고유 값을 조회합니다.

// specify "borough" as the field to return values for
const cursor = myColl.distinct("borough");
for await (const doc of cursor) {
console.dir(doc);
}

이 코드는 다음과 같은 borough 값을 출력합니다.

[ "Bronx", "Brooklyn", "Manhattan", "Queens" ]

쿼리 매개변수를 지정하여 쿼리와 일치하는 문서에 대해 고유한 값을 반환할 수 있습니다.

쿼리 필터 구성에 대한 자세한 내용은 쿼리 지정을 참조하세요.

다음 예제에서는 cuisine 필드의 고유 값을 출력하지만 "Brooklyn" 의 레스토랑은 제외합니다.

// exclude Brooklyn restaurants from the output
const query = { borough: { $ne: "Brooklyn" }};
// find the filtered distinct values of "cuisine"
const cursor = myColl.distinct("cuisine", query);
for await (const doc of cursor) {
console.dir(doc);
}

이 경우 쿼리 필터는 "Brooklyn" 제외한 모든 자치구 값과 일치합니다. 이렇게 하면 distinct() 이(가) cuisine 값인 "Middle Eastern" 하나를 출력하는 것을 방지할 수 있습니다. 이 코드는 다음 값을 출력합니다.

[ "Brazilian", "Chinese", "German", "Italian" ]

collation 필드를 options 매개 변수로 정의하여 distinct() 메서드에 대한 데이터 정렬을 지정할 수 있습니다. 이 필드에서는 문자열 순서 및 비교에 대한 리전 규칙을 설정할 수 있습니다.

데이터 정렬 적용에 대한 지침은 CRUD 작업 구성 가이드 의 데이터 정렬 섹션을 참조하세요.

참고

options 매개변수를 사용하는 경우 query 매개변수도 지정해야 합니다. 쿼리 필터를 사용하지 않으려면 쿼리를 {} 로 정의합니다.

다음 예에서는 고유한 restaurant 값을 출력할 때 collation 필드를 사용하여 독일어 순서 규칙을 지정합니다.

// define an empty query document
const query = {};
// specify German string ordering conventions
const options = { collation: { locale: "de" }};
const cursor = myColl.distinct("restaurant", query, options);
for await (const doc of cursor) {
console.dir(doc);
}

이 경우 독일어 문자열 순서 지정 규칙은 "A"로 시작하는 단어를 "B"로 시작하는 단어 앞에 배치합니다. 이 코드는 다음을 출력합니다:

[ "Äpfel", "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear" ]

collation 필드를 지정하지 않으면 출력 순서는 기본 바이너리 데이터 정렬 규칙을 따릅니다. 이 규칙은 'A'로 시작하는 단어를 액센트가 없는 첫 글자가 있는 단어 뒤에 배치합니다:

[ "Borgatti's", "Samba Kitchen", "Tanoreen", "Via Carota", "White Bear", "Äpfel" ]

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 학습하려면 MongoDB 에 연결 가이드를 참조하세요. moviessample_mflix 예시 Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기 가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 스니펫은 movies 컬렉션 에서 year 문서 필드 에 대한 고유 값 목록을 검색합니다. 쿼리 문서 사용하여 director 배열 에 "Barbara Streisand" 가 포함된 영화를 일치시킵니다.

1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8async function run() {
9 try {
10
11 // Get the database and collection on which to run the operation
12 const database = client.db("sample_mflix");
13 const movies = database.collection("movies");
14
15 // Specify the document field to find distinct values for
16 const fieldName = "year";
17
18 // Specify an optional query document to narrow results
19 const query = { directors: "Barbra Streisand" };
20
21 // Execute the distinct operation
22 const distinctValues = await movies.distinct(fieldName, query);
23
24 // Print the result
25 console.log(distinctValues);
26 } finally {
27 await client.close();
28 }
29}
30run().catch(console.dir);
1import { MongoClient } from "mongodb";
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri = "<connection string uri>";
5
6const client = new MongoClient(uri);
7
8interface Movie {
9 directors: string;
10 year: number;
11}
12
13async function run() {
14 try {
15 // define a database and collection on which to run the method
16 const database = client.db("sample_mflix");
17 const movies = database.collection<Movie>("movies");
18
19 const distinctValues = await movies.distinct("year", {
20 directors: "Barbra Streisand",
21 });
22
23 console.log(distinctValues);
24 } finally {
25 await client.close();
26 }
27}
28run().catch(console.dir);

앞의 예시 실행하면 다음과 같은 결과가 출력됩니다.

[ 1983, 1991, 1996 ]

이 가이드에서 설명하는 유형 또는 메서드에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.

돌아가기

문서 수 계산

이 페이지의 내용