Definición
facetEl
facetcolector agrupa los resultados por valores o rangos en los campos facetados específicos y devuelve el conteo para cada uno de esos grupos.Puedes usar
facettanto en la etapa$searchcomo en la etapa$searchMeta. MongoDB recomienda utilizarfacetcon la$searchMetaetapa para recuperar sólo los resultados de metadatos de la query. Para recuperar resultados de metadatos y resultados de query utilizando la etapa$search, debes usar la variable de agregación$$SEARCH_META. VeaSEARCH_METAVariable de Agregación para obtener más información.Si defines storedSource en tu definición del tipo de campo embeddedDocuments, puedes usar returnScope junto con returnStoredSource para filtrar en campos anidados dentro de un arreglo de objetos. De lo contrario, solo puede crear facetas en el campo de tipo raíz embeddedDocuments. Para un ejemplo de faceteado activado:
Campos anidados dentro de un arreglo de objetos, consulta Ejemplo de returnScope.
Matching children of an
embeddedDocumentsarray usingembeddedDocument, see Embedded-Scoped Facet Example.Campo raíz de tipo
embeddedDocuments, ver Consulta de Facetas.
Sintaxis
facet tiene la siguiente sintaxis:
{ "$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 } }
Campos
Campo | Tipo | ¿Requerido? | Descripción |
|---|---|---|---|
| Documento | Sí | 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. |
| Documento | no | El operador que se debe usar para realizar la faceta. Si se omite, MongoDB Search realiza el facetado sobre todos los documentos de la colección. |
Requisitos de memoria
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.
Definición de faceta
El documento de definición de la faceta contiene el nombre de la faceta y las opciones específicas de un tipo de faceta. MongoDB Search admite los siguientes tipos de facetas:
String Facetas
Importante
stringFacet ahora está desfasado. Usa token en su lugar, lo que proporciona mejores facetas.
Para obtener más información sobre las diferencias entre los tipos de campo actualizados y obsoletos para faceta, consulte Comparar Tipos de Campo para Faceta.
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.
Sintaxis
Las facetas de String tienen la siguiente sintaxis:
{ "$searchMeta": { "facet":{ "operator": { <operator-specification> }, "facets": { "<facet-name>" : { "type" : "string", "path" : "<field-path>", "numBuckets" : <number-of-categories>, "embeddedDocument": { <embedded-document-scope> } // optional } } } } }
opciones
Opción | Tipo | Descripción | ¿Requerido? |
|---|---|---|---|
| Objeto | Scopes the facet's bucket counts to only the child documents of an | no |
| Int | Maximum number of facet categories to return in the results. Value must be less than or equal to | no |
| string | Ruta de campo para expresar facetas. Puede especificar un campo que tenga un índice como un token. | Sí |
| string | Tipo de faceta. El valor debe ser | Sí |
Ejemplo
Ejemplo
El siguiente ejemplo utiliza un índice llamado default en la colección sample_mflix.movies. El campo genres en la colección está indexado como el tipo token y el campo year está indexado como el tipo número.
{ "mappings": { "dynamic": false, "fields": { "genres": { "type": "token" }, "year": { "type": "number" } } } }
La etapa utiliza la $searchMeta para buscar year en el campo en la movies colección películas desde 2000 hasta 2015 y recuperar un recuento del número de películas en cada género.
1 db.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 ])
Para obtener más información sobre estos resultados, consulte Resultados de facetas.
Facetas numéricas
Importante
numberFacet ahora está desactualizado. Usa number en su lugar, que proporciona una mejor facetación.
Para obtener más información sobre las diferencias entre los tipos de campo actualizados y obsoletos para faceta, consulte Comparar Tipos de Campo para Faceta.
Las facetas numéricas permiten determinar la frecuencia de los valores numéricos en los resultados de búsqueda dividiendo los resultados en rangos separados de números. Cuando aplicas facetas a números en arreglos o documentos incrustados, MongoDB Search devuelve recuentos de facetas en función de la cantidad de documentos raíz coincidentes.
Sintaxis
Los facetas numéricas tienen la siguiente sintaxis:
{ "$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 } } } } }
opciones
Opción | Tipo | Descripción | ¿Requerido? |
|---|---|---|---|
| arreglo de números | Lista de valores numéricos en orden ascendente que especifican los límites de los contenedores. Debe especificar entre dos y diez mil (
| Sí |
| string | Nombre de un bucket adicional que cuenta los documentos devueltos por el operador que no se encuentran dentro de los límites especificados. Si se omite, MongoDB Search también incluye los resultados del operador de faceta que no caen en un segmento especificado, pero no los incluye en ningún recuento de segmentos. | no |
| Objeto | Scopes the facet's bucket counts to only the child documents of an | no |
| string | ruta de campo para facetar. Puedes especificar un campo que se indexe como tipo de número. | Sí |
| string | Tipo de faceta. El valor debe ser | Sí |
Ejemplo
Ejemplo
El ejemplo siguiente utiliza un índice llamado default en la colección sample_mflix.movies. El campo year en la colección está indexado como el tipo número.
{ "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_, límite inferior inclusivo para este cubo__1990el límite superior exclusivo para el depósito1980y el límite inferior inclusivo para este depósito2000límite superior exclusivo para el grupo1990
La query también especifica un default bucket llamado other para recuperar los resultados de la query que no se encuentren dentro de ninguno de los límites especificados.
1 db.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 ])
Para obtener más información sobre estos resultados, consulte Resultados de facetas.
Facetas de fecha
Importante
dateFacet está ahora obsoleto. Utiliza date en su lugar, lo que proporciona una mejor faceta.
Para obtener más información sobre las diferencias entre los tipos de campo actualizados y obsoletos para faceta, consulte Comparar Tipos de Campo para Faceta.
Las facetas de fecha te permiten limitar los resultados de búsqueda según una fecha. Cuando aplicas facetas por fechas en arreglos o documentos incrustados, MongoDB Search devuelve los recuentos de facetas según el número de documentos raíz coincidentes.
Sintaxis
Los facetas de fecha tienen la siguiente sintaxis:
{ "$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 } } } } }
opciones
Opción | Tipo | Descripción | ¿Requerido? |
|---|---|---|---|
| arreglo de números | Lista de valores de fecha que especifican los límites de cada franja. Debe especificar:
Cada par adyacente de valores actúa como el límite inferior inclusivo y el límite superior exclusivo para el contenedor. | Sí |
| string | Nombre de un bucket adicional que cuenta los documentos devueltos por el operador que no están dentro de los límites especificados. Si se omite, MongoDB Search también incluye los resultados del operador de faceta que no entran dentro de un bucket especificado, pero MongoDB Search no incluye estos resultados en ningún conteo de bucket. | no |
| Objeto | Scopes the facet's bucket counts to only the child documents of an | no |
| string | Ruta de campo para facetar. Se puede especificar un campo que se indexa como tipo fecha. | Sí |
| string | Tipo de faceta. El valor debe ser | Sí |
Ejemplo
Ejemplo
El ejemplo siguiente utiliza un índice llamado default en la colección sample_mflix.movies. El campo released en la colección se indexa como el tipo fecha.
{ "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_, límite inferior inclusivo para este cubo__2005-01-01el límite superior exclusivo para el depósito2000-01-01y el límite inferior inclusivo para este depósito2010-01-01el límite superior exclusivo para el depósito2005-01-01y el límite inferior inclusivo para este depósito2015-01-01límite superior exclusivo para el grupo2010-01-01
La query también especifica un default bucket llamado other para recuperar los resultados de la query que no se encuentren dentro de ninguno de los límites especificados.
1 db.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 ])
Para obtener más información sobre estos resultados, consulte Resultados de facetas.
Comparación de los tipos de campos para facetas
Los tipos de campo de MongoDB Search actualizados proporcionan una funcionalidad mejorada para soporte facetas en comparación con los tipos obsoletos (stringFacet, numberFacet, dateFacet). La siguiente tabla destaca las diferencias clave en la funcionalidad:
Categoría de faceta | Tipo de campo actualizado | Tipo de faceta anticuado | Diferencias clave |
|---|---|---|---|
String | stringFacet (desactualizado) | Soporte de normalizador: El tipo | |
Numeric | numberFacet (desactualizado) | Soporte de arreglos: El tipo | |
fecha | dateFacet (desactualizado) | Soporte de arreglos: El tipo |
Nota
Cuando tanto los tipos de campo obsoletos como los actualizados se definen para el mismo campo, los tipos de faceta obsoletos tienen prioridad. Por ejemplo, si token y stringFacet están definidos para un campo, el cálculo de facetas utiliza la asignación stringFacet.
Facet on Matching Children of an Embedded Documents Array
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:
Campo | Tipo | Descripción | ¿Requerido? |
|---|---|---|---|
| string | Indexed | Sí |
| Objeto | Operator to run against each child document in the | Sí |
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.
Importante
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
Importante
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:
suma
average
Mínimo
máximo
primero
último
When using aggregations, you must:
Index the field that you specify in the
pathfor each metric astoken,number, ordate.Explicitly include the
countmetric if you want the bucket count.Only specify
aggregationsat 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
aggregationsand no nested facet.
MongoDB Search computes aggregations over the data in the MongoDB Search index, which is eventually consistent.
Nota
Requisitos de memoria
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.
Sintaxis
aggregations tiene la siguiente sintaxis:
{ "$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.
opciones
Opción | Tipo | Descripción | ¿Requerido? |
|---|---|---|---|
| string | Field path to compute the metric over. This is required for all metric types except | Condicional |
| string | Type of metric to compute. Value can be one of the following:
To learn more about each metric type, see Metric Types. | Sí |
Metric Types
Tipo | Field Requirements | Descripción |
|---|---|---|
| Ninguno | Counts the documents in the bucket. Don't specify a |
| Adds the values of the specified field for the documents in the bucket. | |
| 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 | |
| Ninguno | Returns the lowest value of the specified field for the documents in the bucket. |
| Ninguno | Returns the highest value of the specified field for the documents in the bucket. |
| Ninguno | 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. |
| Ninguno | 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. |
Importante
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.
Consideraciones sobre arreglos
Each metric type handles a field that resolves to more than one value, such as an array, differently:
sumandavgskip the document.minandmaxselect the lowest and highest value in the array to use as a representative element for the document.firstandlastreturn 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
Importante
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
aggregationsonly on a leaf facet in a nested facet tree. A facet definition that specifiesfacetscan't also specifyaggregations. To compute metrics for an intermediate grouping, specify that grouping as a separate top-level facet withaggregationsand 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 isnumBucketsfor a string facet or the number of buckets thatboundariesanddefaultdefine for a number or date facet. For example, a facet that requests20buckets and contains a nested facet that requests20buckets produces400unique buckets. Because each level multiplies this total, requesting more buckets at each level reduces the number of levels that you can nest.
Resultados de Faceta
Para una consulta de faceta, MongoDB Search devuelve una asignación de los nombres de facetas definidos a un arreglo de buckets para esa faceta en los resultados. El documento de resultados de la faceta contiene la opción buckets, que es un arreglo de cubos resultantes para la faceta. Cada documento de agrupación por facetas en el arreglo tiene los siguientes campos:
Opción | Tipo | Descripción |
|---|---|---|
| Objeto | Identificador único que identifica este bucket de facetas. Este valor coincide con el tipo de faceta en la que se está aplicando. |
| Int | Cantidad de documentos en este bucket de facetas. Para obtener más información sobre el campo |
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.
Facetas de selección múltiple
MongoDB Search te permite ver y seleccionar múltiples "buckets" dentro de la misma faceta simultáneamente. Normalmente, seleccionar un bucket dentro de una faceta filtra los resultados de la búsqueda según esa selección y modifica los recuentos para todas las facetas.
Ejemplo
Suponga que una definición de índice para la colección sample_airbnb.listings especifica facetas para los siguientes campos:
cancellation_policyroom_typeaccommodates
La faceta cancellation_policy tiene los siguientes cubos:
flexiblemoderatestrict_14_with_grace_periodsuper_strict_30super_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.
En escenarios en los que necesita un control más granular sobre cómo los facetas afectan el conteo de resultados de búsqueda, active el faceting de selección múltiple con la propiedad doesNotAffect en sus consultas facetadas. Estas facetas siguen filtrando los resultados, pero la query no altera sus recuentos de resultados.
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.
Nota
The doesNotAffect option doesn't work with facets that specify aggregations. To learn more, see Limitations.
Ejemplo
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.
Para obtener más información, consulta el ejemplo de Selección múltiple por facetas.
You can't combine doesNotAffect with an embeddedDocument-scoped facet. To learn more, see Facet on Matching Children of an Embedded Documents Array.
Por último, para casos de uso con muchas facetas, puede limitar qué otros filtros afectan a una faceta determinada. Puede hacerlo especificando cualquier faceta en la propiedad doesNotAffect de cualquier filtro, incluidas las facetas en otros campos. Esto le permite observar de un vistazo qué selecciones reducen las opciones más o menos rápidamente.
Ejemplo
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.
Para más información, consulte el Ejemplo de exclusión de filtros entre facetas.
SEARCH_META Variable de agregación
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 recomienda usar la variable $$SEARCH_META solo si necesitas tanto los resultados de la búsqueda como los resultados de los metadatos. De lo contrario, utiliza la:
$searchetapa solo para los resultados de búsqueda.$searchMetaetapa solo para los resultados de los metadatos.
Limitaciones
Solo puedes ejecutar query de faceta en un único campo. No puedes ejecutar consultas de facetas sobre grupos de campos.
Limitations for Embedded-Scoped Facets
The following limitations apply to Facet on Matching Children of an Embedded Documents Array:
You can't combine a top-level
returnScopeoption with anembeddedDocument-scoped facet in the same query.An
embeddedDocument-scoped facet returns only a count.You can't combine drill-sideways faceting (
doesNotAffect) with anembeddedDocument-scoped facet in the same query.
Limitations for Facet Aggregations
The following limitations apply to Facet Aggregations:
You can't use the following options with
aggregations:doesNotAffectfor Multi-Select Facets
You can't facet or compute aggregations on the following BSON types:
binDatabooldecimalnullobjectIdtimestamp
To compute metrics over one of these types, use a view to convert the field to a supported type before you index it.
Ejemplos
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.
La definición del índice en la colección sample_mflix.movies especifica lo siguiente para los campos a indexar:
{ "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.
1 db.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 ])
Los resultados muestran un recuento de lo siguiente en la colección sample_mflix.movies:
Cantidad de películas del año 2000, límite inferior inclusivo, hasta 2015, límite superior exclusivo, que MongoDB Search devolvió para la query.
Número de películas para cada director que MongoDB Search devolvió para la query
Para obtener más información sobre estos resultados, consulte Resultados de facetas.
La definición del índice en la colección sample_mflix.movies especifica lo siguiente para los campos a indexar:
{ "mappings": { "dynamic": false, "fields": { "genres": { "type": "token" }, "released": { "type": "date" } } } }
La siguiente query busca películas lanzadas cerca del 01 de julio de 1999 usando la etapa $search. La query incluye una $facet etapa para procesar los documentos de entrada utilizando las siguientes etapas de sub-pipeline:
$projectetapa para excluir todos los campos de los documentos excepto los campostitleyreleaseden el campo de salidadocs$limitetapa para realizar lo siguiente:Limita la salida de la etapa
$searcha2documentosLimite la salida a
1documento en el campo de salidameta
Nota
El límite debe ser pequeño para que los resultados quepan en un documento de 16 MB.
$replaceWithetapa para incluir los resultados de metadatos almacenados en la variable$$SEARCH_METAen el campo de salidameta
La consulta también incluye una etapa $set para agregar el campo meta.
Nota
Para ver los resultados de metadatos de la siguiente query, MongoDB Search debe devolver documentos que coincidan con la query.
1 db.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 ])
Para obtener más información sobre estos resultados, consulte Resultados de facetas.
La definición del índice en la colección sample_training.companies indexa el campo funding_rounds como embeddedDocuments (documentos integrados). Indexa de forma dinámica todos los campos en el arreglo funding_rounds de objetos y almacena los campos raised_currency_code y raised_amount en el arreglo funding_rounds de objetos utilizando la opción storedSource.
{ "mappings": { "dynamic": false, "fields": { "funding_rounds": { "type": "embeddedDocuments", "dynamic": true, "storedSource": { "include": [ "raised_currency_code", "raised_amount" ] } } } } }
La siguiente query:
Uses the
text(MongoDB Search Operator) to search for funds raised inUSD.Utiliza las opciones returnScope para establecer el contexto de la consulta en el campo
embeddedDocumentsllamadofunding_rounds. Para utilizarreturnScope, la query:- Especifica la opción returnStoredSource, que es requerida, para devolver los campos de origen almacenados.
Facetas en el campo
raised_amountdel arreglofunding_roundsde objetos. La query especifica tres buckets:5000000, límite inferior inclusivo para este intervalo
5250000, límite superior exclusivo para el cubo 5000000 y límite inferior inclusivo para este cubo
5500000, límite superior exclusivo para el intervalo 5250000
1 db.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 ])
En los resultados anteriores de MongoDB Search, los recuentos de facetas se basan en los documentos secundarios incrustados y no en los principales.
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.
1 db.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:
bcounts3: KickApps, Topix, and StumbleUpon each have abround raised inUSD.acounts1: only KickApps has anaround raised inUSD. Topix's and StumbleUpon'sarounds have no recorded currency, so they don't match.seedcounts1: StumbleUpon'sseedround was raised inUSD.
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.
La siguiente definición de índice en la colección sample_airbnb.listingsAndReviews indexa automáticamente todos los campos indexables de manera dinámica y configura los campos cancellation_policy, room_type y price para búsquedas facetadas.
{ "mappings": { "dynamic": true, "fields": { "cancellation_policy": { "type": "token" }, "room_type": { "type": "token" }, "accommodates": { "type": "number" } } } }
La query siguiente utiliza la etapa $searchMeta para realizar las siguientes acciones:
Facet on the
cancellation_policy,roomType, andaccommodatesfields.La faceta
cancellation_policytiene los siguientes cubos:"strict_14_with_grace_period""moderate""flexible""super_strict_30""super_strict_60"
La faceta
room_typetiene los siguientes cubos:"Entire home/apt""Private room""Shared room"
La consulta divide la faceta
accommodatesen bloques para:1_, límite inferior inclusivo para este cubo__2límite superior exclusivo para el grupo1y límite inferior inclusivo para este grupo.4límite superior exclusivo para el grupo2y límite inferior inclusivo para este grupo.8límite superior exclusivo para el grupo4
Realice una búsqueda de
compoundOperador para listados que deben contener el textonew york cityen eldescriptiony filtrar los resultados para los listados con unmoderatecancellation_policy. La configuración dedoesNotAffectgarantiza que filtrar por unmoderatecancellation_policyno altere los recuentos de otros cubos en la faceta; los recuentos para"strict_14_with_grace_period","flexible","super_strict_30"y"super_strict_60"son valores distintos de cero.
1 db.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.
La siguiente definición de índice en la colección sample_airbnb.listingsAndReviews indexa los campos cancellation_policy, room_type y price, lo que permite la búsqueda facetada en ellos.
{ "mappings": { "dynamic": true, "fields": { "cancellation_policy": { "type": "token" }, "room_type": { "type": "token" }, "accommodates": { "type": "number" } } } }
La siguiente query:
Search for listings that include the text
new york cityin theirdescriptionand that have acancellation_policyofmoderate.Facet on the
cancellation_policy,roomType, andaccommodatesfields.Each of the
cancellation_policyandroomTypefacets has three buckets, corresponding to the three unique values of these fields across the collection. The query breaks theaccommodatesfacet into buckets for:1_, límite inferior inclusivo para este cubo__2límite superior exclusivo para el grupo1y límite inferior inclusivo para este grupo.4límite superior exclusivo para el grupo2y límite inferior inclusivo para este grupo.8límite superior exclusivo para el grupo4
Set the
doesNotAffectproperty in theequalsoperator of thecompound.filtertoaccommodatesFacet. This excludes the buckets within theaccommodatesfacet from filtering. As a result, filtering on themoderatecancellation_policyreduces the counts of other buckets in thecancellation_policyfacet to0, and reduces the counts of buckets in theroomTypefacet, but the counts of buckets in theaccommodatesfacet are unchanged. This allows you to compare the impact of filtering on different facets.
1 db.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 ]
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.
1 db.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 ])
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.
1 db.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 ])
Continuar Aprendiendo
Para obtener más información, se puede consultar Cómo utilizar facetas con la MongoDB Search.
Puede obtener más información sobre facet (Operador de búsqueda de MongoDB) en MongoDB Search con nuestro curso y video.
Aprende con cursos
Para aprender más sobre el uso de facetas en MongoDB Search, toma la Unidad 9 del Curso Introductorio a MongoDB en MongoDB University. La unidad de 1.5 horas incluye una visión general de MongoDB Search y lecciones sobre la creación de índices de MongoDB Search, ejecución de consultas de $search con operadores compuestos y agrupación de resultados mediante facet.
Aprende observando
Vea este vídeo para aprender cómo puede crear y utilizar un facet (MongoDB Search Operator) numérico y de string en su query para agrupar resultados y recuperar un recuento de los resultados en los grupos.
Duración: 11 minutos