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

facet (MongoDB Search 연산자)

facet

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

facet을(를) $search, $searchMeta 단계 모두에 사용할 수 있습니다. MongoDB는 facet을(를) $searchMeta 단계와 함께 사용하여 쿼리에 대한 메타데이터 결과만 검색할 것을 권장합니다. 메타데이터 결과와 쿼리 결과를 $search 단계를 사용하여 검색하려면 $$SEARCH_META 집계 변수를 사용해야 합니다. SEARCH_META 집계 변수를 참조하세요.

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.

The memory that a facet query requires depends on the number of unique values in the field that you facet on, not the number of buckets that you request using numBuckets or boundaries. For example, a facet that requests 20 buckets on a field with five million unique values still counts every unique value to determine the top 20 buckets.

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 tracks bucket counts separately for each query, so total memory use scales with the number of concurrent facet queries. On a sharded cluster, MongoDB Search also requires memory to merge the buckets from each shard, which scales with the number of shards and the number of buckets.

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

중요

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

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

String facets allow you to narrow down MongoDB Search results based on the most frequent string values in the specified string field. The string field must be indexed as token. To facet on string fields in embedded documents, you must also index the parent fields as the document type. When you facet on strings in arrays or embedded documents, MongoDB Search returns facet counts based on the number of matching root documents.

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

{
"$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

Maximum number of facet categories to return in the results. Value must be less than or equal to 10000. If specified, MongoDB Search may return fewer categories than requested if the data is grouped into fewer categories than your requested number. If omitted, defaults to 10, which means that MongoDB Search returns only the top 10 facet categories by count.

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

숫자 배열

버킷의 경계를 지정하는 오름차순의 숫자 값 목록입니다. 경계 값은 2개에서 10,000개([2, 10000])사이로 지정해야 합니다. 각 인접한 값 쌍은 포과적 하한과 배타적 상한을 갖는 버킷을 정의합니다. 다음 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"
}
]
}
}
}

The query uses the $searchMeta stage to search the year field in the movies collection for movies between the years 1980 and 2000 and retrieve metadata results for the query. The query specifies three buckets:

  • 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"
}
]
}
}
}

The query uses the $searchMeta stage to search the released field in the movies collection for movies between the years 2000 and 2015 and retrieve metadata results for the query. The query specifies four buckets:

  • 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 (오래됨)

정규화 지원: token 유형은 패싯 버킷을 변환하는 정규화 도구를 지원합니다. 예시 들어 normalizer: lowercase의 경우 'ADIDAS'와 'adidas'는 동일한 버킷으로 계산되고, stringFacet 는 이를 별도의 버킷으로 취급합니다.

숫자

numberFacet (오래됨)

배열 지원: number 유형은 패싯 버킷에 대한 배열 내의 값을 고려합니다. 예시 를 들어 배열 값이 [0, 10] 인 문서 버킷 [1, 5] 과 [6, 10] 모두에 포함되는 반면 numberFacet 는 배열 값을 완전히 무시합니다.

날짜

dateFacet (오래됨)

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

참고

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

Each facet definition can include an optional embeddedDocument field that scopes the facet's bucket counts to only the child documents in an embeddedDocuments array that match a query predicate. If you omit the embeddedDocument field, the facet is document-indexed.

Without embeddedDocument, a root document counts in a bucket if it has any child document that falls into that bucket, even if that child doesn't match the query defined in the facet.operator block. The embeddedDocument field restricts bucket contributions to only the children that match the specified embeddedDocument.operator. It counts each root document at most once per bucket.

The embeddedDocument field takes the following fields:

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

path

문자열

Indexed embeddedDocuments type field to scope the facet into. The facet's path must be a descendant of this field.

네

operator

객체

Operator to run against each child document in the embeddedDocuments array that you specify in path. Only child documents that match this operator contribute to the facet's bucket counts. Every path referenced in this operator must be a descendant of 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.

For each facet bucket, aggregations allows you to compute the following values:

  • 합계

  • 평균

  • minimum

  • maximum

  • first

  • last

When using aggregations, you must:

  • Index the field that you specify in the path for each metric as token, number, or date.

  • Explicitly include the count metric if you want the bucket count.

  • Only specify aggregations at the leaf-level of nested facets.

    If you want to compute metrics for an intermediate grouping, specify that grouping as a separate top-level facet with aggregations and no nested facet.

MongoDB Search computes aggregations over the data in the MongoDB Search index, which is eventually consistent.

참고

메모리 요구 사항

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>"
}
}
}
}
}
}
}

Each key in the aggregations document is an aggregation name that you specify. MongoDB Search returns each aggregation in the bucket documents under the name that you specify.

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

path

문자열

Field path to compute the metric over. This is required for all metric types except count, which doesn't accept a path. Every other metric type computes a value from a second field, so you must name that field. For example, to return the average rating of the documents in a bucket, specify avg with a path of rating. The count metric counts the documents in the bucket, so it doesn't need a second field.

조건부

type

문자열

Type of metric to compute. Value can be one of the following:

  • count

  • sum

  • avg

  • min

  • max

  • first

  • last

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

네

유형
Field Requirements
설명

count

none

Counts the documents in the bucket. Don't specify a path for this metric type. If you omit aggregations from a facet definition, MongoDB Search returns a count metric for the bucket. If you specify aggregations, MongoDB Search returns a count metric only if you specify count in the aggregations document.

sum

Adds the values of the specified field for the documents in the bucket.

avg

Returns the average of the values of the specified field for the documents in the bucket. If no document in the bucket has a value for the field, MongoDB Search returns null.

min

none

Returns the lowest value of the specified field for the documents in the bucket.

max

none

Returns the highest value of the specified field for the documents in the bucket.

first

none

Returns the value of the specified field for the first document in the bucket, according to the order that the query sort option defines. If the query doesn't specify a sort, the order is arbitrary. To learn how to specify a sort, see Sort MongoDB Search Results.

last

none

Returns the value of the specified field for the last document in the bucket, according to the order that the query sort option defines. If the query doesn't specify a sort, the order is arbitrary. To learn how to specify a sort, see Sort MongoDB Search Results.

중요

min and max support all field types, including token. When MongoDB Search computes these metrics, it skips any document in which the field resolves to an unsupported type. MongoDB Search doesn't return an error when it skips a document. To determine whether MongoDB Search skipped documents in a bucket, add a count metric to the same aggregations document and compare it to the number of documents that you expect.

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.

Each metric type handles a field that resolves to more than one value, such as an array, differently:

  • sum and avg skip the document.

  • min and max select the lowest and highest value in the array to use as a representative element for the document.

  • first and last return all of the values as an array.

For first and last, the returned array differs from the source document in the following ways:

  • The order of the values might differ. MongoDB Search reads the values from the index, which doesn't preserve the order of the source document. For example, if a document contains ["red", "blue", "green"], MongoDB Search might return ["blue", "green", "red"].

  • MongoDB Search returns only one instance of a duplicate value.

  • MongoDB Search returns every value at the path, including values of a type that you can't facet on. For example, if an array contains both strings and a boolean, MongoDB Search returns the boolean with the strings.

To return the values exactly as the source document contains them, define storedSource for the field in your index definition and set returnStoredSource to true in your query.

중요

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. You can nest facets without limit on the number of levels. However, the following restrictions apply:

  • You can specify aggregations only on a leaf facet in a nested facet tree. A facet definition that specifies facets can't also specify aggregations. To compute metrics for an intermediate grouping, specify that grouping as a separate top-level facet with aggregations and no nested facet.

  • The total number of unique buckets that a query can return can't exceed 100000. To calculate the buckets that one facet tree produces, multiply the number of buckets at each level of its nesting branch. The number of buckets at a level is numBuckets for a string facet or the number of buckets that boundaries and default define for a number or date facet. For example, a facet that requests 20 buckets and contains a nested facet that requests 20 buckets produces 400 unique buckets. Because each level multiplies this total, requesting more buckets at each level reduces the number of levels that you can nest.

패싯 쿼리 의 경우 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 facet field with 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

Each bucket has its own result count. When you search for the moderate cancellation_policy, the counts for the four other buckets go to 0. Additionally, the counts for buckets in the room_type and accommodates facets reduce to the number of results in each bucket that also have a flexible cancellation_policy.

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

You can specify doesNotAffect in the following operators:

To exclude multiple facets, specify an array of facet names. Most use cases exclude only the facet that shares a path with the filter. For example, an equals filter on the rating field specifies the name of the facet that uses rating as its path.

참고

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

예시

Consider a query against the sample_airbnb.listingsAndReviews collection for documents with a moderate cancellation_policy. If you specify a doesNotAffect value of cancellation_policy, the counts for buckets in the cancellation_policy facet don't change, but the result counts for the buckets of other facets reduce to the number of results in each bucket that also have a 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 속성에서 패싧을 지정함으로써 이 작업을 수행할 수 있습니다. 이를 통해 어떤 선택이 옵션의 폭을 더 많이 또는 더 적게 족히는지 한눈에 확인할 수 있습니다.

예시

Consider a query against the sample_airbnb.listingsAndReviews collection for documents with an accommodates value of 3. If you specify a doesNotAffect value of cancellation_policy, the result counts for the room_type buckets reduce to the number of results in each bucket that also accommodate 3 people, but the result counts for the buckets in cancellation_policy are unaffected.

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

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:

  • You can't combine a top-level returnScope option with an embeddedDocument-scoped facet in the same query.

  • An embeddedDocument-scoped facet returns only a count.

  • You can't combine drill-sideways faceting (doesNotAffect) with an embeddedDocument-scoped facet in the same query.

The following limitations apply to Facet Aggregations:

  • You can't use the following options with 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.

튜토리얼의 이전 단계를 완료한 후 종속성을 설치합니다.

sample_mflix.movies 컬렉션의 인덱스 정의는 인덱싱할 필드에 대해 다음을 지정합니다.

필드 이름
데이터 유형

directors

year

released

{
"mappings": {
"dynamic": false,
"fields": {
"directors": {
"type": "token"
},
"year": {
"type": "number"
},
"released": {
"type": "date"
}
}
}
}

The following query searches for movies released between January 01, 2000 and January 31, 2015. It requests metadata on the directors and year fields.

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 "directorsFacet": {
14 "type": "string",
15 "path": "directors",
16 "numBuckets" : 7
17 },
18 "yearFacet" : {
19 "type" : "number",
20 "path" : "year",
21 "boundaries" : [2000,2005,2010, 2015]
22 }
23 }
24 }
25 }
26 }
27])

결과는 sample_mflix.movies 컬렉션에 있는 다음과 같은 것들의 개수를 표시합니다.

  • 2000년(하한 포함)부터 2015(상한 제외)까지 MongoDB Search가 쿼리 에 대해 반환한 영화 수

  • MongoDB Search가 쿼리 에 대해 반환한 각 감독의 영화 수

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

$검색를 사용하여 검색하고 $$검색_META 변수를 사용하여 검색 결과와 메타데이터 결과를 모두 조회합니다.

sample_mflix.movies 컬렉션의 인덱스 정의는 인덱싱할 필드에 대해 다음을 지정합니다.

필드 이름
데이터 유형

genres

released

{
"mappings": {
"dynamic": false,
"fields": {
"genres": {
"type": "token"
},
"released": {
"type": "date"
}
}
}
}

다음 쿼리는 $search 단계를 사용하여 1999년 7월 01일 경에 개봉된 영화를 검색합니다. 쿼리에는 다음 하위 파이프라인 단계를 사용하여 입력 문서를 처리하는 $facet 단계가 포함됩니다.

  • $project 단계에서 docs 출력 필드의 title 및 released 필드를 제외한 문서의 모든 필드를 제외합니다.

  • $limit 단계를 사용하여 다음을 수행합니다.

    • $search 단계 출력을 2개 문서로 제한합니다.

    • meta 출력 필드에 있는 1개 문서로 출력을 제한합니다.

    참고

    결과를 16MB 문서에 맞추려면 제한이 작아야 합니다.

  • $replaceWith 스테이지를 사용하여 $$SEARCH_META 변수에 저장된 메타데이터 결과를 meta 출력 필드에 포함시킵니다.

쿼리에는 meta 필드를 추가하는 $set 단계도 포함되어 있습니다.

참고

다음 쿼리 에 대한 메타데이터 결과 를 보려면 MongoDB Search 에서 쿼리 와 일치 하는 문서 를 반환 해야 합니다 .

1db.movies.aggregate([
2 {
3 "$search": {
4 "facet": {
5 "operator": {
6 "near": {
7 "path": "released",
8 "origin": ISODate("1999-07-01T00:00:00.000+00:00"),
9 "pivot": 7776000000
10 }
11 },
12 "facets": {
13 "genresFacet": {
14 "type": "string",
15 "path": "genres"
16 }
17 }
18 }
19 }
20 },
21 { "$limit": 2 },
22 {
23 "$facet": {
24 "docs": [
25 { "$project":
26 {
27 "title": 1,
28 "released": 1
29 }
30 }
31 ],
32 "meta": [
33 {"$replaceWith": "$$SEARCH_META"},
34 {"$limit": 1}
35 ]
36 }
37 },
38 {
39 "$set": {
40 "meta": {
41 "$arrayElemAt": ["$meta", 0]
42 }
43 }
44 }
45])

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

embeddedDocuments의 자식 필드에 대한 패싯과 패싯을 사용하여 검색합니다

sample_training.companies 컬렉션의 인덱스 정의는 funding_rounds 필드를 embeddedDocuments 유형으로 인덱싱합니다. funding_rounds 객체 배열의 모든 필드를 동적으로 인덱싱하고 raised_currency_code 및 raised_amount 필드를 storedSource 옵션을 사용하여 funding_rounds 객체 배열에 저장합니다.

{
"mappings": {
"dynamic": false,
"fields": {
"funding_rounds": {
"type": "embeddedDocuments",
"dynamic": true,
"storedSource": {
"include": [
"raised_currency_code",
"raised_amount"
]
}
}
}
}
}

다음 쿼리입니다:

  • Uses the text (MongoDB Search Operator) to search for funds raised in USD.

  • returnScope 옵션을 사용하여 embeddedDocuments 필드 funding_rounds에 쿼리 컨텍스트를 설정합니다. returnScope 를 사용하려면 다음 쿼리를 입력합니다.

    • 저장된 소스 필드를 반환하는 데 필요한 ReturnSoredSource 옵션을 지정합니다.
  • funding_rounds 객체 배열의 raised_amount 필드에 패싯합니다. 쿼리는 3개의 버킷을 지정합니다.

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

    • 5250000, 5000000 버킷의 상한 제외 및 이 버킷의 하한 포함

    • 5500000, 5250000 버킷의 배타적 상한선

1db.companies.aggregate([
2 {
3 "$searchMeta": {
4 "returnStoredSource": true,
5 "returnScope": {
6 "path": "funding_rounds"
7 },
8 "facet": {
9 "operator": {
10 "text": {
11 "path": "funding_rounds.raised_currency_code",
12 "query": "USD"
13 }
14 },
15 "facets": {
16 "raisedAmountFacet": {
17 "type": "number",
18 "path": "funding_rounds.raised_amount",
19 "boundaries": [5000000, 5250000, 5500000]
20 }
21 }
22 }
23 }
24 }
25])

이전 MongoDB 검색 결과에서 패싯 수는 상위 문서가 아닌 내장된 하위 문서를 기반으로 합니다.

Facet on only the matching children of an embeddedDocuments array.

The index definition on the sample_training.companies collection indexes the funding_rounds field as the embeddedDocuments type, with the round_code and raised_currency_code fields in each funding round indexed as token.

{
"mappings": {
"dynamic": false,
"fields": {
"name": {
"type": "token"
},
"funding_rounds": {
"type": "embeddedDocuments",
"dynamic": false,
"fields": {
"round_code": {
"type": "token"
},
"raised_currency_code": {
"type": "token"
}
}
}
}
}
}

KickApps, Topix, and StumbleUpon each have several funding rounds, only some of which were raised in USD:

// KickApps
{ "name": "KickApps",
"funding_rounds": [
{ "round_code": "a", "raised_currency_code": "USD" },
{ "round_code": "b", "raised_currency_code": "USD" },
{ "round_code": "c", "raised_currency_code": "GBP" }
]
}
// Topix
{ "name": "Topix",
"funding_rounds": [
{ "round_code": "a", "raised_currency_code": null },
{ "round_code": "b", "raised_currency_code": "USD" }
]
}
// StumbleUpon
{ "name": "StumbleUpon",
"funding_rounds": [
{ "round_code": "seed", "raised_currency_code": "USD" },
{ "round_code": "a", "raised_currency_code": null },
{ "round_code": "b", "raised_currency_code": "USD" },
{ "round_code": "angel", "raised_currency_code": null }
]
}

The following query uses the in operator to restrict the facet to these three companies, then facets on funding_rounds.round_code. The roundFacet definition specifies an embeddedDocument block that scopes the facet to only the funding rounds where raised_currency_code is USD.

1db.companies.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "in": {
7 "path": "name",
8 "value": ["KickApps", "Topix", "StumbleUpon"]
9 }
10 },
11 "facets": {
12 "roundFacet": {
13 "type": "string",
14 "path": "funding_rounds.round_code",
15 "embeddedDocument": {
16 "path": "funding_rounds",
17 "operator": {
18 "equals": {
19 "path": "funding_rounds.raised_currency_code",
20 "value": "USD"
21 }
22 }
23 }
24 }
25 }
26 }
27 }
28 }
29])

Each company counts once per round code for which it has at least one funding round raised in USD:

  • b counts 3: KickApps, Topix, and StumbleUpon each have a b round raised in USD.

  • a counts 1: only KickApps has an a round raised in USD. Topix's and StumbleUpon's a rounds have no recorded currency, so they don't match.

  • seed counts 1: StumbleUpon's seed round was raised in USD.

KickApps' c round doesn't contribute to a c bucket because it was raised in GBP, not USD. Without the embeddedDocument block, faceting on funding_rounds.round_code requires indexing funding_rounds as the document type instead, and an unscoped facet would also count KickApps in a c bucket, because the root document has a matching child in that bucket regardless of its currency.

패싯 필터링을 보다 세분화하여 제어하려면 dosNotAffect로 검색하세요.

sample_airbnb.listingsAndReviews 컬렉션에 대한 다음 인덱스 정의는 동적으로 인덱싱할 수 있는 모든 필드의 인덱스를 자동으로 생성하고 패싯 검색을 위해 cancellation_policy, room_type, price 필드를 구성합니다.

{
"mappings": {
"dynamic": true,
"fields": {
"cancellation_policy": {
"type": "token"
},
"room_type": {
"type": "token"
},
"accommodates": {
"type": "number"
}
}
}
}

다음 쿼리는 $searchMeta 단계를 사용하여 다음 작업을 수행합니다.

  • Facet on the cancellation_policy, roomType, and accommodates fields.

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

    • "strict_14_with_grace_period"

    • "moderate"

    • "flexible"

    • "super_strict_30"

    • "super_strict_60"

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

    • "Entire home/apt"

    • "Private room"

    • "Shared room"

    쿼리 accommodates 패싯 다음에 대한 버킷으로 나눕니다.

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

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

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

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

  • 연산자 검색 에 compound 텍스트를 포함해야 new york city 하는 목록에 description 대해 수행하고 이 포함된 목록에 대한 결과를 moderate cancellation_policy 필터링합니다. doesNotAffect 설정은 moderate cancellation_policy 로 필터링해도 패싯 에 있는 다른 버킷의 개수가 변경되지 않도록 합니다. "strict_14_with_grace_period", "flexible", "super_strict_30", "super_strict_60" 의 개수는 0이 아닌 값입니다.

1db.listingsAndReviews.aggregate([
2 {
3 $searchMeta: {
4 facet: {
5 facets: {
6 accommodatesFacet: {
7 path: "accommodates",
8 type: "number",
9 boundaries: [1,2,4,8]
10 },
11 cancellationFacet: {
12 path: "cancellation_policy",
13 type: "string"
14 },
15 roomTypeFacet: {
16 path: "room_type",
17 type: "string"
18 }
19 },
20 operator: {
21 compound: {
22 must: [
23 {
24 text: {
25 path: "description",
26 query: "new york city"
27 },
28 },
29 ],
30 filter: [
31 {
32 equals: {
33 path: "cancellation_policy",
34 value: "moderate",
35 doesNotAffect:
36 "cancellationFacet"
37 }
38 }
39 ]
40 }
41 }
42 }
43 }
44 }
45])

The counts for buckets in cancellationFacet are not reduced to zero even though the query filters on a value of moderate.

쿼리된 필드 이외의 다른 패싯에서 doesNotAffect를 사용하여 검색합니다.

sample_airbnb.listingsAndReviews 컬렉션 에 대한 다음 인덱스 정의는 cancellation_policy, room_type 및 price 필드를 인덱싱하여 패싯 검색 활성화합니다.

{
"mappings": {
"dynamic": true,
"fields": {
"cancellation_policy": {
"type": "token"
},
"room_type": {
"type": "token"
},
"accommodates": {
"type": "number"
}
}
}
}

다음 쿼리입니다:

  • Search for listings that include the text new york city in their description and that have a cancellation_policy of moderate.

  • Facet on the cancellation_policy, roomType, and accommodates fields.

    Each of the cancellation_policy and roomType facets has three buckets, corresponding to the three unique values of these fields across the collection. The query breaks the accommodates facet into buckets for:

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

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

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

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

  • Set the doesNotAffect property in the equals operator of the compound.filter to accommodatesFacet. This excludes the buckets within the accommodates facet from filtering. As a result, filtering on the moderate cancellation_policy reduces the counts of other buckets in the cancellation_policy facet to 0, and reduces the counts of buckets in the roomType facet, but the counts of buckets in the accommodates facet are unchanged. This allows you to compare the impact of filtering on different facets.

1db.listingsAndReviews.aggregate([
2 {
3 $searchMeta: {
4 facet: {
5 facets: {
6 accommodatesFacet: {
7 path: "accommodates",
8 type: "number",
9 boundaries: [1,2,4,8],
10 },
11 cancellationFacet: {
12 path: "cancellation_policy",
13 type: "string",
14 },
15 roomTypeFacet: {
16 path: "room_type",
17 type: "string",
18 }
19 },
20 operator: {
21 compound: {
22 must: [
23 {
24 text: {
25 path: "description",
26 query: "new york city",
27 },
28 },
29 ],
30 filter: [
31 {
32 equals: {
33 path: "cancellation_policy",
34 value: "moderate",
35 doesNotAffect:
36 "accommodatesFacet",
37 },
38 },
39 ],
40 },
41 },
42 },
43 },
44 },
45]

Search with facet aggregations.

The following example uses an index named default on the sample_airbnb.listingsAndReviews collection. The property_type and amenities fields in the collection are indexed as the token type and the accommodates field is indexed as the number type.

{
"mappings": {
"dynamic": false,
"fields": {
"property_type": [
{
"type": "token"
}
],
"amenities": [
{
"type": "token"
}
],
"accommodates": [
{
"type": "number"
}
]
}
}
}

The query uses the $searchMeta stage to find the listings that offer at least one of the specified amenities and group them by property_type. For each property type, the query computes the number of listings and the smallest and largest number of guests that a listing accommodates.

1db.listingsAndReviews.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "in": {
7 "path": "amenities",
8 "value": ["Wifi", "Pets allowed", "Wheelchair accessible"]
9 }
10 },
11 "facets": {
12 "propertyTypeFacet": {
13 "type": "string",
14 "path": "property_type",
15 "aggregations": {
16 "listingCount": {
17 "type": "count"
18 },
19 "minAccommodates": {
20 "type": "min",
21 "path": "accommodates"
22 },
23 "maxAccommodates": {
24 "type": "max",
25 "path": "accommodates"
26 }
27 }
28 }
29 }
30 }
31 }
32 }
33])

Search with nested facets.

The following example uses an index named default on the sample_airbnb.listingsAndReviews collection. The property_type field in the collection is indexed as the token type and the bedrooms and accommodates fields are indexed as the number type.

{
"mappings": {
"dynamic": false,
"fields": {
"property_type": [
{
"type": "token"
}
],
"bedrooms": [
{
"type": "number"
}
],
"accommodates": [
{
"type": "number"
}
]
}
}
}

The query groups the listings by property_type, and then groups the listings in each property type by number of bedrooms. The query computes the number of listings and the largest number of guests that a listing accommodates for each bedroom range.

1db.listingsAndReviews.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "facets": {
6 "propertyTypeFacet": {
7 "type": "string",
8 "path": "property_type",
9 "facets": {
10 "bedroomsFacet": {
11 "type": "number",
12 "path": "bedrooms",
13 "boundaries": [0, 2, 4],
14 "default": "other",
15 "aggregations": {
16 "listingCount": {
17 "type": "count"
18 },
19 "maxAccommodates": {
20 "type": "max",
21 "path": "accommodates"
22 }
23 }
24 }
25 }
26 }
27 }
28 }
29 }
30 }
31])

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

교육 과정과 동영상을 통해 MongoDB Search의( MongoDB Search facet 연산자)에 대해자세히 학습 수 있습니다.

MongoDB Search에서 패싯을 사용하는 방법에 대해 자세히 학습하려면 MongoDB University 의 Intro To MongoDB 과정의 단원 9 을 수강하세요. 1.5 시간 단위로, MongoDB Search에 대한 개요와 MongoDB Search 인덱스 만들기, 복합 연산자를 사용한 $search 쿼리 실행, facet를 사용한 결과 그룹화에 대한 강의가 포함되어 있습니다.

이 동영상을 보고 쿼리에서 숫자와 string facet (MongoDB Search 연산자) 를 만들고 사용하여 결과를 그룹하고 그룹 내 결과의 개수를 조회하는 방법을 학습합니다.

소요 시간: 11분