AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

facet (MongoDB Search 연산자)

facet

facet 수집기는 지정된 패싯 필드의 값 또는 범위별로 결과를 그룹화하고 해당 그룹 각각의 개수를 반환합니다.

You can use facet with both the $search and $searchMeta stages. MongoDB recommends using facet with the $searchMeta stage to retrieve metadata results only for the query. To retrieve metadata results and query results using the $search stage, you must use the $$SEARCH_META aggregation variable. See SEARCH_META Aggregation Variable to learn more.

storedSource를 embeddedDocuments 필드 유형 정의에 정의하면, returnScope와 returnStoredSource를 사용하여 객체 배열 내부의 중첩 필드를 패싯으로 지정할 수 있습니다. 그렇지 않으면 루트 embeddedDocuments 유형 필드에서만 패싯할 수 있습니다. 패싯의 예시는 다음과 같습니다.

facet 의 구문은 다음과 같습니다:

{
"$searchMeta"|"$search": {
"index": <index name>, // optional, defaults to "default"
"facet": {
"operator": {
<operator-specifications>
},
"facets": {
<facet-definitions>
}
},
"returnScope": {
"path": "<embedded-documents-field-to-query>"
},
"returnStoredSource": true
}
}
필드
유형
필수 사항입니다.
설명

facets

문서

네

Information for bucketing the data for each facet. You must specify at least one Facet Definition. Each facet definition can also specify Facet Aggregations to compute metrics for each bucket.

operator

문서

no

패싯 을 수행하는 데 사용하는 연산자입니다. 생략하면 MongoDB Search는 컬렉션 의 모든 문서에 대해 패싯 을 수행합니다.

Facet queries are memory-intensive, regardless of your cluster tier. Queries that specify Facet Aggregations or nested facets require more memory and disk than other facet queries. Before you use facets in production, confirm that your cluster has enough memory for your workload. To learn more, see Search Memory Management. To get sizing guidance for your workload, request support.

패싯 쿼리에 필요한 메모리는 패싯할 필드의 고유 값 수에 따라 달라지며, numBuckets 또는 boundaries을(를) 사용하여 요청하는 버킷 수에 따라 달라지지 않습니다. 예시를 들어, 500만개의 고유값을 가진 필드에서 20 개의 버켓을 요청하는 패싿은 여전히 모든 고유값을 계산하여 상위 20 개의 버켓을 결정합니다.

For nested facets, the total unique values computed in a query multiply based on the unique values across each level of nesting. Even when each individual field has low cardinality, the combination of values across nested paths can produce a large number of unique buckets. To learn more about how nested facets multiply buckets, see Nested Facets.

MongoDB Search는 각 쿼리에 대해 버킷 수를 별도로 추적하므로 총 메모리 사용량은 동시 패싯 쿼리 수에 따라 확장됩니다. 샤딩된 클러스터에서 MongoDB Search는 각 샤드의 버킷을 병합하기 위해 메모리도 필요로 하며, 이는 샤드 수와 버킷 수에 따라 확장됩니다.

패싯 정의 문서 에는 패싯 이름과 패싯 유형별 옵션이 포함되어 있습니다. MongoDB Search는 다음 유형의 패싯을 지원합니다.

중요

stringFacet 은 이제 구식입니다. 대신 향상된 패싯을 제공하는 토큰을 사용합니다.

패싯에 대해 업데이트된 필드 유형과 오래된 필드 유형 간의 차이점에 대해 자세히 알아보려면 패싯의 필드 유형 비교를 참조하세요.

string 패싯을 사용하면 지정된 string 필드에서 가장 빈번한 string 값을 기준으로 MongoDB Search 결과의 범위를 좁힐 수 있습니다. string 필드는 토큰으로 인덱스되어야 합니다. 내장된 문서의 string 필드에 패싯을 수행하려면 상위 필드도 문서 유형으로 인덱싱해야 합니다. 배열 또는 내장된 문서의 문자열에 패싯을 적용할 때 MongoDB Search는 일치하는 루트 문서 수를 기반으로 패싯 개수를 반환합니다.

문자열 패싯의 구문은 다음과 같습니다:

{
"$searchMeta": {
"facet":{
"operator": {
<operator-specification>
},
"facets": {
"<facet-name>" : {
"type" : "string",
"path" : "<field-path>",
"numBuckets" : <number-of-categories>,
"embeddedDocument": { <embedded-document-scope> } // optional
}
}
}
}
}
옵션
유형
설명
필수 사항입니다.

embeddedDocument

객체

Scopes the facet's bucket counts to only the child documents of an embeddedDocuments array that match a query predicate. To learn more, see Facet on Matching Children of an Embedded Documents Array.

no

numBuckets

int

결과에 반환할 패싯 카테고리의 최대 개수입니다. 값은 10000보다 작거나 같아야 합니다. 지정한 경우, 데이터가 요청된 수보다 적은 카테고리로 그룹화되다면 MongoDB Search는 요청된 것보다 적은 카테고리를 반환할 수 있습니다. 생략하면 기본값은 10 으로, MongoDB Search는 개수 기준으로 상위 10 패싯 범주만 반환합니다.

no

path

문자열

패싯을 설정할 필드 경로입니다. 토큰으로 인덱싱되는 필드를 지정할 수 있습니다.

네

type

문자열

패싯의 유형입니다. 값은 string이어야 합니다.

네

예시

다음 예시는 sample_mflix.movies 컬렉션의 default라는 인덱스를 사용합니다. 컬렉션의 genres 필드는 토큰 유형으로 인덱싱되고 year 필드는 숫자 유형으로 인덱싱됩니다.

{
"mappings": {
"dynamic": false,
"fields": {
"genres": {
"type": "token"
},
"year": {
"type": "number"
}
}
}
}

이 쿼리는 $searchMeta 단계를 사용하여 movies 컬렉션의 year 필드에서 2000년부터 2015년까지의 영화를 검색하고 각 장르의 영화 수 개수를 검색합니다.

1db.movies.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "range": {
7 "path": "year",
8 "gte": 2000,
9 "lte": 2015
10 }
11 },
12 "facets": {
13 "genresFacet": {
14 "type": "string",
15 "path": "genres"
16 }
17 }
18 }
19 }
20 }
21])

이러한 결과에 대해 자세히 알아보려면 패싯 결과를 참조하세요.

중요

numberFacet 은 이제 구식입니다. 대신 숫자 를 사용하면 향상된 패싯을 제공합니다.

패싯에 대해 업데이트된 필드 유형과 오래된 필드 유형 간의 차이점에 대해 자세히 알아보려면 패싯의 필드 유형 비교를 참조하세요.

숫자 패싯을 사용하면 결과를 별도의 숫자 범위로 나누어 검색 결과에서 숫자 값의 빈도를 결정할 수 있습니다. 배열이나 내장된 문서의 숫자를 패싯 경우 MongoDB Search는 일치하는 루트 문서 수를 기준으로 패싯 수를 반환합니다.

숫자 패싯의 구문은 다음과 같습니다:

{
"$searchMeta": {
"facet":{
"operator": {
<operator-specification>
},
"facets": {
"<facet-name>" : {
"type" : "number",
"path" : "<field-path>",
"boundaries" : <array-of-numbers>,
"default": "<bucket-name>",
"embeddedDocument": { <embedded-document-scope> } // optional
}
}
}
}
}
옵션
유형
설명
필수 사항입니다.

boundaries

숫자 배열

List of numeric values in ascending order that specify the boundaries for your buckets. You must specify between two and ten thousand ([2, 10000]) boundary values. Each adjacent pair of values defines a bucket with an inclusive lower bound and an exclusive upper bound. You can specify any combination of values of the following BSON types:

  • 32비트 정수 (int32)

  • 64비트 정수 (int64)

  • 64비트 이진 부동 소수점(double)

네

default

문자열

지정된 경계에 속하지 않는 연산자 로부터 반환된 문서를 계산하는 추가 버킷의 이름입니다. 생략하면 MongoDB Search는 지정된 버킷에 속하지 않는 패싯 연산자 의 결과도 포함하지만 버킷 수에는 포함하지 않습니다.

no

embeddedDocument

객체

Scopes the facet's bucket counts to only the child documents of an embeddedDocuments array that match a query predicate. To learn more, see Facet on Matching Children of an Embedded Documents Array.

no

path

문자열

패싯을 설정할 필드 경로입니다. number 유형으로 인덱싱되는 필드를 지정할 수 있습니다.

네

type

문자열

패싯의 유형입니다. 값은 number이어야 합니다.

네

예시

다음 예시는 sample_mflix.movies 컬렉션의 default라는 인덱스를 사용합니다. 컬렉션의 year 필드는 number 유형으로 인덱싱됩니다.

{
"mappings": {
"dynamic": false,
"fields": {
"year": [
{
"type": "number"
}
]
}
}
}

이 쿼리는 $searchMeta 단계를 사용하여 movies 컬렉션의 year 필드에서 1980 년부터 2000 년 사이의 영화를 검색하고 쿼리에 대한 메타데이터 결과를 조회합니다. 쿼리는 3개의 버킷을 지정합니다.

  • 1980이 버킷에 대한 포괄적인 하한값

  • 19901980 버킷에 대한 배타적 상한과 이 버킷에 대한 포괄적 하한입니다.

  • 20001990 버킷에 대한 배타적 상한

이 쿼리는 또한 지정된 경계에 속하지 않는 쿼리 결과를 검색하기 위해 other이라는 이름의 default 버킷을 지정합니다.

1db.movies.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "range": {
7 "path": "year",
8 "gte": 1980,
9 "lte": 2000
10 }
11 },
12 "facets": {
13 "yearFacet": {
14 "type": "number",
15 "path": "year",
16 "boundaries": [1980,1990,2000],
17 "default": "other"
18 }
19 }
20 }
21 }
22 }
23])

이러한 결과에 대해 자세히 알아보려면 패싯 결과를 참조하세요.

중요

dateFacet 은 이제 구식입니다. 대신 날짜를 사용하여 향상된 패싯을 제공합니다.

패싯에 대해 업데이트된 필드 유형과 오래된 필드 유형 간의 차이점에 대해 자세히 알아보려면 패싯의 필드 유형 비교를 참조하세요.

날짜 패싯을 사용하면 날짜를 기준으로 검색 결과의 범위를 좁힐 수 있습니다. 배열이나 내장된 문서의 날짜를 패싯 경우 MongoDB Search는 일치하는 루트 문서 수를 기준으로 패싯 수를 반환합니다.

날짜 패싯의 구문은 다음과 같습니다:

{
"$searchMeta": {
"facet":{
"operator": {
<operator-specification>
},
"facets": {
"<facet-name>" : {
"type" : "date",
"path" : "<field-path>",
"boundaries" : <array-of-dates>,
"default": "<bucket-name>",
"embeddedDocument": { <embedded-document-scope> } // optional
}
}
}
}
}
옵션
유형
설명
필수 사항입니다.

boundaries

숫자 배열

각 버킷의 경계를 지정하는 날짜 값 목록입니다. 다음을 지정해야 합니다:

  • 만 이하인 경계 두 개 이상([2, 10000])

  • 값이 오름차순으로 표시되며 가장 빠른 날짜가 먼저 표시됩니다.

각 인접한 값 쌍은 버킷의 포괄적인 하한과 배타적인 상한으로 작용합니다.

네

default

문자열

지정된 경계에 속하지 않는 연산자 로부터 반환된 문서를 계산하는 추가 버킷의 이름입니다. 생략하면 MongoDB Search는 지정된 버킷에 속하지 않는 패싯 연산자 의 결과도 포함하지만, MongoDB 수에는 이러한 결과가 포함되지 않습니다.

no

embeddedDocument

객체

Scopes the facet's bucket counts to only the child documents of an embeddedDocuments array that match a query predicate. To learn more, see Facet on Matching Children of an Embedded Documents Array.

no

path

문자열

패싯을 설정할 필드 경로입니다. date 유형으로 인덱싱된 필드를 지정할 수 있습니다.

네

type

문자열

패싯의 유형입니다. 값은 date이어야 합니다.

네

예시

다음 예시는 sample_mflix.movies 컬렉션의 default라는 인덱스를 사용합니다. 컬렉션의 released 필드는 date 유형으로 인덱싱됩니다.

{
"mappings": {
"dynamic": false,
"fields": {
"released": [
{
"type": "date"
}
]
}
}
}

이 쿼리는 $searchMeta 단계를 사용하여 movies 컬렉션의 released 필드에서 2000 년부터 2015 년 사이의 영화를 검색하고 쿼리에 대한 메타데이터 결과를 조회합니다. 쿼리는 4개의 버킷을 지정합니다:

  • 2000-01-01이 버킷에 대한 포괄적인 하한값

  • 2005-01-012000-01-01 버킷에 대한 배타적 상한과 이 버킷에 대한 포괄적 하한입니다.

  • 2010-01-012005-01-01 버킷에 대한 배타적 상한과 이 버킷에 대한 포괄적 하한입니다.

  • 2015-01-012010-01-01 버킷에 대한 배타적 상한

이 쿼리는 또한 지정된 경계에 속하지 않는 쿼리 결과를 검색하기 위해 other이라는 이름의 default 버킷을 지정합니다.

1db.movies.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "range": {
7 "path": "released",
8 "gte": ISODate("2000-01-01T00:00:00.000Z"),
9 "lte": ISODate("2015-01-31T00:00:00.000Z")
10 }
11 },
12 "facets": {
13 "yearFacet": {
14 "type": "date",
15 "path": "released",
16 "boundaries": [ISODate("2000-01-01"), ISODate("2005-01-01"), ISODate("2010-01-01"), ISODate("2015-01-01")],
17 "default": "other"
18 }
19 }
20 }
21 }
22 }
23])

이러한 결과에 대해 자세히 알아보려면 패싯 결과를 참조하세요.

업데이트된 MongoDB 검색 필드 유형은 오래된 유형(stringFacet, numberFacet, dateFacet)에 비해 패싯을 지원하도록 개선된 기능을 제공합니다. 다음 표에는 기능의 주요 차이점이 간략하게 설명되어 있습니다.

패싯 범주
업데이트된 필드 유형
오래된 패싯 유형
주요 차이점

문자열

stringFacet (오래됨)

Normalizer Support: The token type supports normalizers that transform facet buckets. For example, with normalizer: lowercase, "ADIDAS" and "adidas" count toward the same bucket while stringFacet treats them as separate buckets.

숫자

numberFacet (오래됨)

Array Support: The number type considers values within arrays for facet buckets. For example, a document with an array value [0, 10] counts toward both buckets [1, 5] and [6, 10] while numberFacet ignores array values completely.

날짜

dateFacet (오래됨)

배열 지원: date 유형은 패싯 버킷에 대한 배열 내의 값을 고려합니다. 예시 를 들어 dateFacet 는 배열 값을 완전히 무시하는 반면 날짜가 포함된 배열 값은 여러 날짜 범위 버킷에 포함될 수 있습니다.

참고

오래된 필드 유형과 업데이트된 필드 유형이 모두 동일한 필드에 대해 정의된 경우 오래된 패싯 유형이 우선합니다. 예시 를 들어 token 및 stringFacet 가 필드 에 대해 모두 정의된 경우 패싯 계산은 stringFacet 매핑을 사용합니다.

각 패싯 정의에는 쿼리 조건자와 일치하는 embeddedDocuments 배열의 하위 문서로만 패싯의 버킷 수를 제한하는 선택 사항인 embeddedDocument 필드가 포함될 수 있습니다. embeddedDocument 필드를 생략하면 패싯이 문서 인덱스됩니다.

embeddedDocument이 없으면 루트 문서는 해당 버킷에 속하는 하위 문서가 하나라도 있는 경우, 해당 하위 문서가 facet.operator 블록에 정의된 쿼리와 일치하지 않더라도 버킷에 포함됩니다. embeddedDocument 필드는 버킷 기여를 지정된 embeddedDocument.operator와 일치하는 하위 문서로만 제한합니다. 각 루트 문서를 버킷당 최대 한 번만 계산합니다.

embeddedDocument 필드는 다음 필드를 사용합니다.

필드
유형
설명
필수 사항입니다.

path

문자열

패싯의 범위를 지정할 인덱스 embeddedDocuments 유형 필드입니다. 패싯의 path은 이 필드의 하위 항목이어야 합니다.

네

operator

객체

path에 지정하는 embeddedDocuments 배열의 각 하위 문서에 대해 실행할 연산자 입니다. 이 연산자와 일치하는 하위 문서만 패싯의 버킷 수에 기여합니다. 이 연산자에서 참조되는 모든 경로는 path의 하위 항목이어야 합니다.

네

For a number or date facet, a matching child whose value falls outside the configured boundaries counts in the default bucket, if you specify one, using the same rule as a document-indexed facet. A root document with no matching child doesn't contribute to the embeddedDocument-scoped facet, but can still contribute to any other, unscoped facet in the same query.

중요

You can't combine an embeddedDocument-scoped facet with several other faceting options. To learn more, see Limitations.

For an example, see the Embedded-Scoped Facet Example.

중요

Facet aggregations is in Preview. The feature and corresponding documentation might change at any time during the Preview period. To learn more, see Preview Features.

To compute metrics for each facet bucket, add an aggregations document to a facet definition. MongoDB Search computes the metrics from the MongoDB Search index, so it is much more efficient than running a $group stage later in your pipeline.

각 패싯 버킷에 대해, aggregations은 다음 값을 계산할 수 있습니다.

  • 합계

  • 평균

  • minimum

  • maximum

  • first

  • last

aggregations을 사용할 때는 다음을 수행해야 합니다.

  • 각 지표에 대해 path에 지정한 필드를 token, number 또는 date으로 인덱싱합니다.

  • 버킷 개수를 확인하려면 count 지표를 명시적으로 포함하세요.

  • 중첩된 패싯의 리프 수준에서만 aggregations을(를) 지정하세요.

    중간 그룹화에 대한 지표를 계산하려면 해당 그룹화를 aggregations이(가) 포함된 별도의 최상위 패싯으로 지정하고 중첩된 패싯은 지정하지 마세요.

MongoDB Search는 MongoDB Search 인덱스에 있는 데이터에 대해 aggregations을 계산합니다. 이는 결국적으로 일관적인.

참고

메모리 요구 사항

Facet queries that specify aggregations or nested facets increase the memory and disk that your MongoDB Search index requires beyond the requirements for other facet queries. To learn more, see Memory Requirements.

aggregations 의 구문은 다음과 같습니다:

{
"$searchMeta": {
"facet": {
"facets": {
"<facet-name>": {
"type": "<facet-type>",
"path": "<field-path>",
"aggregations": {
"<aggregation-name>": {
"type": "sum" | "min" | "max" | "avg" | "first" | "last",
"path": "<field-path>"
}
}
}
}
}
}
}

aggregations 문서의 각 키는 사용자가 지정하는 집계 이름입니다. MongoDB Search는 사용자가 지정한 이름으로 버킷 문서의 각 집계를 반환합니다.

옵션
유형
설명
필수 사항입니다.

path

문자열

지표를 계산할 필드 경로입니다. 이는 path을 허용하지 않는 count을 제외한 모든 지표 유형에 필요합니다. 다른 모든 지표 유형은 두 번째 필드에서 값을 계산하므로 해당 필드의 이름을 지정해야 합니다. 예시, 버킷에 있는 문서의 평균 평점을 반환하려면 rating의 path과 함께 avg를 지정합니다. count 지표는 버킷의 문서를 계산하므로 두 번째 필드가 필요하지 않습니다.

조건부

type

문자열

계산할 지표의 유형입니다. 값은 다음 중 하나일 수 있습니다:

  • count

  • sum

  • avg

  • min

  • max

  • first

  • last

To learn more about each metric type, see Metric Types.

네

유형
필드 요구 사항
설명

count

none

버킷에 있는 문서 개수를 셉니다. 이 지표 유형에는 path을(를) 지정하지 마세요. 패싯 정의에서 aggregations을(를) 생략하면 MongoDB Search는 버킷에 대해 count 지표를 반환합니다. aggregations을(를) 지정하면 MongoDB Search는 aggregations 문서에 count을(를) 지정한 경우에만 count 지표를 반환합니다.

sum

버킷에 있는 문서의 지정된 필드 값을 더합니다.

avg

버킷에 있는 문서에 대해 지정된 필드 값의 평균을 반환합니다. 버킷의 어떤 문서에도 필드에 대한 값이 없으면 MongoDB Search는 null을(를) 반환합니다.

min

none

버킷 내 문서에 대해 지정된 필드의 최솟값을 반환합니다.

max

none

버킷 내 문서에 대해 지정된 필드의 가장 높은 값을 반환합니다.

first

none

쿼리 정렬 옵션이 정의하는 순서에 따라 버킷의 첫 번째 문서에 대해 지정된 필드의 값을 반환합니다. 쿼리에 정렬이 지정되지 않은 경우 순서는 임의적입니다. 정렬을 지정하는 방법을 학습하려면 MongoDB Search 결과 정렬을 참조하세요.

last

none

쿼리 정렬 옵션에 정의된 순서에 따라 버킷의 마지막 문서에 대해 지정된 필드의 값을 반환합니다. 쿼리에 정렬이 지정되지 않은 경우 순서는 임의적입니다. 정렬을 지정하는 방법을 학습하려면 MongoDB Search 결과 정렬을 참조하세요.

중요

min 및 max은(는) token을(를) 포함한 모든 필드 유형을 지원합니다. MongoDB Search가 이러한 지표를 계산할 때 필드가 지원되지 않는 유형으로 확인되는 문서는 건너뜁니다. MongoDB Search는 문서를 건너뛸 때 오류를 반환하지 않습니다. MongoDB Search가 버킷의 문서를 건너뛰었는지 확인하려면 동일한 aggregations 문서에 count 지표를 추가하고 예상되는 문서 수와 비교하십시오.

For values that MongoDB Search doesn't skip, min selects the smallest value in the bucket and max selects the largest. If the values aren't all of the same type, MongoDB Search applies BSON type comparison order to determine which value is smallest or largest.

각 지표 유형은 배열과 같이 둘 이상의 값으로 확인되는 필드를 다르게 처리하다.

  • sum 그리고 avg 문서를 건너뛰세요.

  • min 그리고 max은(는) 문서의 대표 요소로 사용할 배열에서 가장 낮은 값과 가장 높은 값을 선택합니다.

  • first 그리고 last은(는) 모든 값을 배열로 반환합니다.

first 및 last의 경우, 반환된 배열은 다음 방식에서 원본 문서와 다릅니다.

  • 값의 순서는 다를 수 있습니다. MongoDB Search는 인덱스에서 값을 읽는데, 이는 원본 문서의 순서를 유지하지 않습니다. 예를 들어, 문서에 ["red", "blue", "green"]이 포함된 경우 MongoDB Search는 ["blue", "green", "red"]을 반환할 수 있습니다.

  • MongoDB Search는 중복된 값의 인스턴스를 하나만 반환합니다.

  • MongoDB Search는 패싯을 지정할 수 없는 유형의 값을 포함하여 경로의 모든 값을 반환합니다. 예를 들어, 배열에 문자열과 불리언이 모두 포함된 경우 MongoDB Search는 문자열과 함께 불리언을 반환합니다.

소스 문서에 포함된 그대로 값을 반환하려면 인덱스 정의에서 필드에 대해 storedSource를 정의하고 쿼리에서 returnStoredSource를 true (으)로 설정합니다.

중요

Nested facets is in Preview. The feature and corresponding documentation might change at any time during the Preview period. To learn more, see Preview Features.

To group the documents in each bucket by additional fields, add a facets document to an existing facet definition. Each nested facet definition uses the same syntax as a top-level facet definition, so you can nest facets to build a tree of groupings. MongoDB Search returns the buckets for a nested facet inside each bucket of its parent facet.

For each bucket of a facet that contains a nested facet, MongoDB Search also returns a count field with the number of documents in the bucket. You don't need to specify a count metric for these intermediate buckets.

You can nest facets without limit on the number of levels. However, the following restrictions apply:

  • 중첩된 패싯 트리에서 리프 패싯에만 aggregations을 지정할 수 있습니다. facets을 지정하는 패싯 정의는 aggregations도 지정할 수 없습니다. 중간 그룹화에 대한 지표를 계산하려면 해당 그룹화를 aggregations이 포함된 별도의 최상위 패싯으로 지정하고 중첩된 패싯은 지정하지 마세요.

  • You can't name a nested facet count. MongoDB Search reserves count for the document count of intermediate buckets.

  • 쿼리가 반환할 수 있는 고유 버킷의 총 개수는 100000개를 초과할 수 없습니다. 하나의 패싯 트리가 생성하는 버킷을 계산하려면 중첩 분기의 각 수준에 있는 버킷 수를 곱하십시오. 수준의 버킷 수는 string 패싯의 경우 numBuckets 이고, 숫자 또는 날짜 패싯의 경우 boundaries 및 default이 정의하는 버킷 수입니다. 예를 들어, 20 개의 버킷을 요청하고 20 개의 버킷을 요청하는 중첩 패싯을 포함하는 패싯은 400 개의 고유한 버킷을 생성합니다. 각 레벨이 이 합계를 곱하기 때문에 각 레벨에서 더 많은 버킷을 요청하면 중첩할 수 있는 레벨 수가 줄어듭니다.

패싯 쿼리 의 경우 MongoDB Search는 정의된 패싯 이름을 결과의 해당 패싯 에 대한 버킷 배열 에 매핑합니다. 패싯 결과 문서 에는 패싯 에 대한 결과 버킷의 배열 인 buckets 옵션이 포함되어 있습니다. 배열 의 각 패싯 버킷 문서 에는 다음과 같은 필드가 있습니다.

옵션
유형
설명

_id

객체

이 패싯 버킷을 식별하는 고유 식별자입니다. 이 값은 패싯 처리되는 데이터 형식과 일치합니다.

count

int

이 패싯 버킷에 있는 문서 수입니다. count 필드에 대해 자세히 학습하려면 MongoDB 검색 결과 집계를 참조하세요.

If the facet definition specifies Facet Aggregations, each bucket document contains the metrics that you name in the aggregations document instead of the count field. If the facet definition specifies nested facets, each bucket document contains a count field with the number of documents in the bucket, and the results for the nested facet.

MongoDB Search를 사용하면 동일한 패싯 내의 여러 버킷을 동시에 보고 선택할 수 있습니다. 일반적으로 패싯 내에서 버킷을 선택하면 해당 선택 항목에 따라 검색 결과가 필터링되고 모든 패싯의 개수가 변경됩니다.

예시

sample_airbnb.listings 컬렉션 에 대한 인덱스 정의가 다음 필드에 대한 패싯을 지정한다고 가정해 보겠습니다.

  • cancellation_policy

  • room_type

  • accommodates

cancellation_policy 패싯 에는 다음과 같은 버킷이 있습니다.

  • flexible

  • moderate

  • strict_14_with_grace_period

  • super_strict_30

  • super_strict_60

각 버킷에는 고유한 결과 개수가 있습니다. moderate cancellation_policy을(를) 검색하면 다른 4개 버킷의 개수가 0(으)로 이동합니다. 또한, room_type 및 accommodates 패슷의 버킷 개수는 각 버킷에 flexible cancellation_policy도 있는 결과의 수로 줄어들어요.

패싯이 검색 결과 수에 미치는 영향을 보다 세밀하게 제어해야 하는 시나리오에서는 패싯 쿼리에서 doesNotAffect 속성 사용하여 다중 선택 패싯을 활성화 . 이러한 패싯은 여전히 결과를 필터하다 하지만 쿼리 결과 수를 변경하지 않습니다.

다음 연산자에서 doesNotAffect을 지정할 수 있습니다.

여러 패싯을 제외하려면 패싯 이름의 배열을 지정합니다. 대부분의 사용 사례에서는 필터와 경로를 공유하는 패싯만 제외합니다. 예시, rating 필드의 equals 필터는 rating을(를) 경로로 사용하는 패싯의 이름을 지정합니다.

참고

The doesNotAffect option doesn't work with facets that specify aggregations. To learn more, see Limitations.

예시

sample_airbnb.listingsAndReviews 컬렉션에 대한 쿼리를 고려하여 moderate cancellation_policy를 가진 문서를 찾습니다. doesNotAffect 값을 cancellation_policy로 지정하면 cancellation_policy 패싯의 버킷 개수는 변경되지 않지만, 다른 패싯의 버킷 결과 개수는 각 버킷에 moderate cancellation_policy도 있는 결과의 수로 줄어듭니다.

자세한 내용은 다중 선택 패싯 예시참조하세요.

You can't combine doesNotAffect with an embeddedDocument-scoped facet. To learn more, see Facet on Matching Children of an Embedded Documents Array.

마지막으로 패싧이 많은 사용 사례의 경우, 특정 패싧에 영향을 미치는 다른 필터를 제한할 수 있습니다. 다른 필드의 패싧을 포함하여 모든 필터의 doesNotAffect 속성에서 패싧을 지정함으로써 이 작업을 수행할 수 있습니다. 이를 통해 어떤 선택이 옵션의 폭을 더 많이 또는 더 적게 족히는지 한눈에 확인할 수 있습니다.

예시

sample_airbnb.listingsAndReviews 컬렉션에 대한 쿼리를 고려하여 accommodates 값이 3인 문서를 찾습니다. doesNotAffect 값을 cancellation_policy로 지정하면 room_type 버킷의 결과 수는 3 명을 수용하는 각 버킷의 결과 수로 줄어들지만 cancellation_policy의 버킷에 대한 결과 수는 영향을 받지 않습니다.

자세한 내용은 패싯 간 필터 제외 예시를 참조하세요.

When you run your query using the $search stage, MongoDB Search stores the metadata results in the $$SEARCH_META variable and returns only the search results. You can use the $$SEARCH_META variable in all the supported aggregation pipeline stages to view the metadata results for your $search query. You can also use the $$SEARCH_META variable with facet.aggregations.

MongoDB는 검색 결과와 메타데이터 결과가 모두 필요한 경우에만 $$SEARCH_META 변수를 사용할 것을 권장합니다. 해당 경우가 아니면 다음을 사용하세요.

  • $search 검색 결과만 표시하는 단계.

  • $searchMeta 메타데이터 결과만 표시하는 단계.

단일 필드에 대해서만 패싯 쿼리를 실행할 수 있습니다. 필드 그룹에 대해서는 패싯 쿼리를 실행할 수 없습니다.

The following limitations apply to Facet on Matching Children of an Embedded Documents Array:

  • 동일 쿼리에서 최상위 returnScope 옵션과 embeddedDocument범위의 패슷을 결합할 수 없습니다.

  • embeddedDocument범위 패슷은 개수만 반환합니다.

  • 동일한 쿼리에서 드릴 사이드웨이 패싯(doesNotAffect)과 embeddedDocument범위의 패싯을 결합할 수 없습니다.

The following limitations apply to Facet Aggregations:

  • aggregations에서는 다음 옵션을 사용할 수 없습니다.

  • You can't facet or compute aggregations on the following BSON types:

    • binData

    • bool

    • decimal

    • null

    • objectId

    • timestamp

    To compute metrics over one of these types, use a view to convert the field to a supported type before you index it.

The following examples use the sample data. The metadata results example demonstrates how to run a $searchMeta query with facet to retrieve only the metadata in the results. The metadata and search results example demonstrates how to run a $search query with facet and the $SEARCH_META aggregation variable to retrieve both the search and metadata results. The returnScope example demonstrates how to facet on nested fields in an array of objects dynamically indexed using the embeddedDocuments type. The embedded-scoped facet example demonstrates how to facet on only the matching children of an embeddedDocuments array. The multi-select and inter-facet filter exclusion examples demonstrate how to use doesNotAffect to control how facets affect each other's counts. The aggregation example demonstrates how to compute metrics for each facet bucket, and the nested facet example demonstrates how to group results by a second field and compute metrics for each bucket.

자세한 학습은 MongoDB 검색에서 패싯을 사용하는 방법을 참조하세요.

You can learn more about facet (MongoDB Search Operator) in MongoDB Search with our course and video.

To learn more about using facets in MongoDB Search, take Unit 9 of the Intro To MongoDB Course on MongoDB University. The 1.5 hour unit includes an overview of MongoDB Search and lessons on creating MongoDB Search indexes, running $search queries using compound operators, and grouping results using facet.

Watch this video to learn about how you can create and use a numeric and string facet (MongoDB Search Operator) in your query to group results and retrieve a count of the results in the groups.

소요 시간: 11분