문서 메뉴
문서 홈
/ / /
Node.js
/

필드의 고유 값 가져오기

collection.distinct() 메서드를 사용하여 컬렉션 전체에서 필드에 대한 고유 값 목록을 메서드. 문서 필드 이름 매개 변수를 String 로 사용하여 Collection 객체에서 distinct() 메서드를 호출하면 아래와 같이 지정된 문서 필드에 있는 다양한 값 중 하나가 포함된 목록이 생성됩니다.

const distinctValues = myColl.distinct("countries", query);

내장된 문서 내에서 점 표기법 을 사용하여 문서 필드를 지정할 수 있습니다. 배열이 포함된 문서 필드에서 distinct() 를 호출하면 메서드는 각 요소를 별도의 값으로 처리합니다. awards 하위 문서의 wins 필드에 대한 메서드 호출의 다음 예를 참조하세요.

const distinctValues = myColl.distinct("awards.wins", query);

distinct() 메서드에 세 번째 매개변수로 전달된 options 객체를 사용하여 추가 쿼리 옵션을 지정할 수 있습니다. 쿼리 매개변수에 대한 자세한 내용 은 API 문서의 distinct() 메서드를 참조하세요.

String 유형이 아닌 문서 필드 이름 값 (예: Document, Array, Number 또는 null)을 지정하면 메서드가 실행되지 않고 다음과 유사한 메시지와 함께 TypeMismatch 오류가 반환됩니다.

'키'의 유형이 잘못되었습니다. 예상 문자열, 찾음 <non-string type>

distinct() 메서드에 대한 자세한 내용은 고유 값 조회를 참조하세요.

다음 스니펫은 movies 컬렉션에서 year 문서 필드에 대한 고유 값 목록을 검색합니다. 쿼리 문서를 사용하여 director의 값에 '바브라 스트라이샌드(Barbara Streisand)'가 포함된 영화를 일치시킵니다.

참고

이 예시를 사용하여 MongoDB 인스턴스에 연결하고 샘플 데이터가 포함된 데이터베이스와 상호 작용할 수 있습니다. MongoDB 인스턴스에 연결하고 샘플 데이터 세트를 로드하는 방법에 대해 자세히 알아보려면 사용 예제 가이드를 참조하세요.

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 ]

돌아가기

문서 수 계산