Para agentes de IA: hay un índice de documentación disponible en https://www.mongodb.com/es/docs/llms.txt — versiones en markdown de todas las páginas están disponibles agregando .md a cualquier ruta URL.
Docs Menu

embeddedDocument Operador

embeddedDocument

The embeddedDocument operator is similar to $elemMatch operator. It constrains multiple query predicates to be satisfied from a single element of an array of embedded documents. embeddedDocument can be used only for queries over fields of the embeddedDocuments type.

embeddedDocument tiene la siguiente sintaxis:

{
"embeddedDocument": {
"path": "<path-to-field>",
"operator": { <operator-specification> },
"score": { <score-options> }
}
}

embeddedDocument utiliza las siguientes opciones para construir una query:

Campo
Tipo
DescripciĂłn
Necesidad

operator

Objeto

Operador que se utilizarĂĄ para consultar cada documento en el arreglo de documentos que se especifique en el path. El operador moreLikeThis no estĂĄ soportado.

Requerido

path

string

Campo indexado de tipo embeddedDocuments para bĂșsqueda. El campo especificado debe ser el campo padre de todos los operadores y campos especificados usando la opciĂłn operator.

Requerido

score

Objeto

Score to assign to matching search results. You can use the embedded scoring option to configure scoring options. To learn more, see Scoring Behavior.

Opcional

No puedes usar resaltar en consultas dentro del operador embeddedDocument.

Nota

MongoDB Search deja de replicar cambios para Ă­ndices mayores a 2,100,000,000 objetos de Ă­ndice por particiĂłn, en un set de rĂ©plicas o en una sola particiĂłn, donde cada documento principal incrustado indexado cuenta como un Ășnico objeto. Si se supera este lĂ­mite, pueden generarse resultados de query obsoletos.

Using the embeddedDocuments field type can result in indexing objects over this index size limit, because each indexed embedded document is counted as a single object. If you create a MongoDB Search index that has or will soon have more than 2.1 billion index objects, use the numPartitions index option to partition your index (supported only on Search Nodes deployments) or shard your cluster.

Cuando usted consulta documentos incrustados en arreglos utilizando el operador embeddedDocument, MongoDB Search evalĂșa y califica las condiciones de query del operador en diferentes etapas de la ejecuciĂłn de la query. MongoDB Search:

  1. EvalĂșa cada documento incrustado en el arreglo de forma independiente.

  2. Combina las puntuaciones de los resultados coincidentes segĂșn lo configurado utilizando la opciĂłn embedded, o puntĂșa sumando las puntuaciones de los resultados coincidentes si no se especifica una opciĂłn de puntuaciĂłn de embedded.

  3. Une los resultados coincidentes con el documento principal si se especifican otros predicados de query a través del compuesto.

De forma predeterminada, el operador embeddedDocument utiliza la estrategia de agregaciĂłn predeterminada, sum, para combinar puntuaciones de coincidencias de documentos incrustados. La opciĂłn embeddedDocument operador score le permite anular lo por defecto y configurar la puntuaciĂłn de los resultados coincidentes mediante la opciĂłn embedded.

Para ordenar los documentos parent por un campo de documento incrustado, debes realizar lo siguiente:

  • Indexa los padres del campo de documento incrustado como el tipo documento.

  • Indexa el campo secundario con valores de string dentro del documento incrustado como el tipo de token. Para los campos secundarios con valores numĂ©ricos y de fecha, habilita la asignaciĂłn dinĂĄmica para indexar esos campos automĂĄticamente.

MongoDB Search ordena solo en documentos principales. No ordena los campos hijo dentro de un arreglo de documentos. Para un ejemplo, consulte Ejemplo de clasificaciĂłn.

Puedes resaltar en campos si los campos estĂĄn indexados bajo un campo principal de tipo documento para predicados de query especificados dentro del operador embeddedDocument. Para ver un ejemplo, consulte el tutorial.

To learn about the embeddedDocument operator limitations, see embeddedDocument Operator Limitations.

The following examples use the sample_supplies.sales collection in the sample dataset.

Estas consultas de ejemplo utilizan la siguiente definiciĂłn de Ă­ndice en la colecciĂłn:

{
"mappings": {
"dynamic": true,
"fields": {
"items": [
{
"dynamic": true,
"type": "embeddedDocuments"
},
{
"dynamic": true,
"fields": {
"tags": {
"type": "token"
}
},
"type": "document"
}
],
"purchaseMethod": {
"type": "token"
}
}
}
}

The following query searches the collection for items tagged school with a preference for items named backpack. MongoDB Search scores the results in descending order based on the average (arithmetic mean) score of all matching embedded documents. The query includes a $limit stage to limit the output to 5 documents and a $project stage to:

  • Excluye todos los campos excepto los campos items.name y items.tags

  • Añade un campo llamado score

1db.sales.aggregate({
2 "$search": {
3 "embeddedDocument": {
4 "path": "items",
5 "operator": {
6 "compound": {
7 "must": [{
8 "text": {
9 "path": "items.tags",
10 "query": "school"
11 }
12 }],
13 "should": [{
14 "text": {
15 "path": "items.name",
16 "query": "backpack"
17 }
18 }]
19 }
20 },
21 "score": {
22 "embedded": {
23 "aggregate": "mean"
24 }
25 }
26 }
27 }
28},
29{
30 $limit: 5
31},
32{
33 $project: {
34 "_id": 0,
35 "items.name": 1,
36 "items.tags": 1,
37 "score": { $meta: "searchScore" }
38 }
39})
[
{
items: [ {
name: 'backpack',
tags: [ 'school', 'travel', 'kids' ]
} ],
score: 1.2907354831695557
},
{
items: [ {
name: 'envelopes',
tags: [ 'stationary', 'office', 'general' ]
},
{
name: 'printer paper',
tags: [ 'office', 'stationary' ]
},
{
name: 'backpack',
tags: [ 'school', 'travel', 'kids' ]
} ],
score: 1.2907354831695557
},
{
items: [ {
name: 'backpack',
tags: [ 'school', 'travel', 'kids' ]
} ],
score: 1.2907354831695557
},
{
items: [ {
name: 'backpack',
tags: [ 'school', 'travel', 'kids' ]
} ],
score: 1.2907354831695557
},
{
items: [ {
name: 'backpack',
tags: [ 'school', 'travel', 'kids' ]
} ],
score: 1.2907354831695557
}
]

La siguiente query busca elementos etiquetados con school dando preferencia a los elementos llamados backpack. Solicita informaciĂłn de facetas en el campo purchaseMethod.

1db.sales.aggregate({
2 "$searchMeta": {
3 "facet": {
4 "operator": {
5 "embeddedDocument": {
6 "path": "items",
7 "operator": {
8 "compound": {
9 "must": [
10 {
11 "text": {
12 "path": "items.tags",
13 "query": "school"
14 }
15 }
16 ],
17 "should": [
18 {
19 "text": {
20 "path": "items.name",
21 "query": "backpack"
22 }
23 }
24 ]
25 }
26 }
27 }
28 },
29 "facets": {
30 "purchaseMethodFacet": {
31 "type": "string",
32 "path": "purchaseMethod"
33 }
34 }
35 }
36 }
37})
[
{
count: { lowerBound: Long("2309") },
facet: {
purchaseMethodFacet: {
buckets: [
{ _id: 'In store', count: Long("2751") },
{ _id: 'Online', count: Long("1535") },
{ _id: 'Phone', count: Long("578") }
]
}
}
}
]

The following query searches for items named laptop and it sorts the results by the items.tags field. The query includes a $limit stage to limit the output to 5 documents and a $project stage to:

  • Excluir todos los campos salvo items.name y items.tags

  • Añade un campo llamado score

1db.sales.aggregate({
2 "$search": {
3 "embeddedDocument": {
4 "path": "items",
5 "operator": {
6 "text": {
7 "path": "items.name",
8 "query": "laptop"
9 }
10 }
11 },
12 "sort": {
13 "items.tags": 1
14 }
15 }
16},
17{
18 "$limit": 5
19},
20{
21 "$project": {
22 "_id": 0,
23 "items.name": 1,
24 "items.tags": 1,
25 "score": { "$meta": "searchScore" }
26 }
27})
1[
2 {
3 items: [
4 { name: 'envelopes', tags: [ 'stationary', 'office', 'general' ] },
5 { name: 'binder', tags: [ 'school', 'general', 'organization' ] },
6 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
7 { name: 'laptop', tags: [ 'electronics', 'school', 'office' ] },
8 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
9 { name: 'printer paper', tags: [ 'office', 'stationary' ] },
10 { name: 'backpack', tags: [ 'school', 'travel', 'kids' ] },
11 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
12 { name: 'envelopes', tags: [ 'stationary', 'office', 'general' ] }
13 ],
14 score: 1.168686032295227
15 },
16 {
17 items: [
18 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
19 { name: 'binder', tags: [ 'school', 'general', 'organization' ] },
20 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
21 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
22 { name: 'printer paper', tags: [ 'office', 'stationary' ] },
23 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
24 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
25 { name: 'backpack', tags: [ 'school', 'travel', 'kids' ] },
26 { name: 'laptop', tags: [ 'electronics', 'school', 'office' ] }
27 ],
28 score: 1.168686032295227
29 },
30 {
31 items: [
32 { name: 'backpack', tags: [ 'school', 'travel', 'kids' ] },
33 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
34 { name: 'binder', tags: [ 'school', 'general', 'organization' ] },
35 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
36 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
37 { name: 'envelopes', tags: [ 'stationary', 'office', 'general' ] },
38 { name: 'laptop', tags: [ 'electronics', 'school', 'office' ] }
39 ],
40 score: 1.168686032295227
41 },
42 {
43 items: [
44 { name: 'laptop', tags: [ 'electronics', 'school', 'office' ] },
45 { name: 'binder', tags: [ 'school', 'general', 'organization' ] },
46 { name: 'binder', tags: [ 'school', 'general', 'organization' ] },
47 { name: 'backpack', tags: [ 'school', 'travel', 'kids' ] },
48 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
49 { name: 'printer paper', tags: [ 'office', 'stationary' ] },
50 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
51 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
52 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
53 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] }
54 ],
55 score: 1.168686032295227
56 },
57 {
58 items: [
59 { name: 'envelopes', tags: [ 'stationary', 'office', 'general' ] },
60 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
61 { name: 'notepad', tags: [ 'office', 'writing', 'school' ] },
62 { name: 'backpack', tags: [ 'school', 'travel', 'kids' ] },
63 { name: 'envelopes', tags: [ 'stationary', 'office', 'general' ] },
64 { name: 'pens', tags: [ 'writing', 'office', 'school', 'stationary' ] },
65 { name: 'binder', tags: [ 'school', 'general', 'organization' ] },
66 { name: 'laptop', tags: [ 'electronics', 'school', 'office' ] },
67 { name: 'printer paper', tags: [ 'office', 'stationary' ] },
68 { name: 'binder', tags: [ 'school', 'general', 'organization' ] }
69 ],
70 score: 1.168686032295227
71 }
72]

The following query returns only the nested documents that match the query. The query uses MongoDB Search compound operator clauses in the $search stage to find matching documents and then the aggregation operators in the $project stage to return only matching embedded documents. Specifically, the query specifies the following pipeline stages:

Especifica los siguientes criterios en la clĂĄusula must del operador compuesto:

  • Verificar si el campo items.price existe en la colecciĂłn.

  • Busca los Ă­tems etiquetados como school en el campo items.tags.

  • Coincide solo si el valor es superior a 2 para el campo items.quantity.

Limita la salida a 5 documentos.

Realiza las siguientes acciones:

  • Excluya el campo _id e incluya solo los campos items y storeLocation.

  • Use $filter to return only elements of the items input array that match the condition specified using the $and operator. The and operator uses the following operators:

    • $ifNull to determine if items.price contains null values and replace null values, if present, with the replacement expression false.

    • $gt verificar si la cantidad es mayor a 2.

    • $in to check if office exists in the tags array.

1db.sales.aggregate(
2 {
3 "$search": {
4 "embeddedDocument": {
5 "path": "items",
6 "operator": {
7 "compound": {
8 "must": [
9 {
10 "range": {
11 "path": "items.quantity",
12 "gt": 2
13 }
14 },
15 {
16 "exists": {
17 "path": "items.price"
18 }
19 },
20 {
21 "text": {
22 "path": "items.tags",
23 "query": "school"
24 }
25 }
26 ]
27 }
28 }
29 }
30 }
31 },
32 {
33 "$limit": 2
34 },
35 {
36 "$project": {
37 "_id": 0,
38 "storeLocation": 1,
39 "items": {
40 "$filter": {
41 "input": "$items",
42 "cond": {
43 "$and": [
44 {
45 "$ifNull": [
46 "$$this.price", "false"
47 ]
48 },
49 {
50 "$gt": [
51 "$$this.quantity", 2
52 ]
53 },
54 {
55 "$in": [
56 "office", "$$this.tags"
57 ]
58 }
59 ]
60 }
61 }
62 }
63 }
64 }
65)
1[
2 {
3 storeLocation: 'Austin',
4 items: [
5 {
6 name: 'laptop',
7 tags: [ 'electronics', 'school', 'office' ],
8 price: Decimal128('753.04'),
9 quantity: 3
10 },
11 {
12 name: 'pens',
13 tags: [ 'writing', 'office', 'school', 'stationary' ],
14 price: Decimal128('19.09'),
15 quantity: 4
16 },
17 {
18 name: 'notepad',
19 tags: [ 'office', 'writing', 'school' ],
20 price: Decimal128('30.23'),
21 quantity: 5
22 },
23 {
24 name: 'pens',
25 tags: [ 'writing', 'office', 'school', 'stationary' ],
26 price: Decimal128('20.05'),
27 quantity: 4
28 },
29 {
30 name: 'notepad',
31 tags: [ 'office', 'writing', 'school' ],
32 price: Decimal128('22.08'),
33 quantity: 3
34 },
35 {
36 name: 'notepad',
37 tags: [ 'office', 'writing', 'school' ],
38 price: Decimal128('21.67'),
39 quantity: 4
40 }
41 ]
42 },
43 {
44 storeLocation: 'Austin',
45 items: [
46 {
47 name: 'notepad',
48 tags: [ 'office', 'writing', 'school' ],
49 price: Decimal128('24.16'),
50 quantity: 5
51 },
52 {
53 name: 'notepad',
54 tags: [ 'office', 'writing', 'school' ],
55 price: Decimal128('28.04'),
56 quantity: 5
57 },
58 {
59 name: 'notepad',
60 tags: [ 'office', 'writing', 'school' ],
61 price: Decimal128('21.42'),
62 quantity: 5
63 },
64 {
65 name: 'laptop',
66 tags: [ 'electronics', 'school', 'office' ],
67 price: Decimal128('1540.63'),
68 quantity: 3
69 },
70 {
71 name: 'pens',
72 tags: [ 'writing', 'office', 'school', 'stationary' ],
73 price: Decimal128('29.43'),
74 quantity: 5
75 },
76 {
77 name: 'pens',
78 tags: [ 'writing', 'office', 'school', 'stationary' ],
79 price: Decimal128('28.48'),
80 quantity: 5
81 }
82 ]
83 }
84]

Para obtener mĂĄs informaciĂłn, consulta CĂłmo ejecutar queries de bĂșsqueda de MongoDB en campos de documentos incrustados.