Docs Menu
Docs Home
/ /

queryString Operador

queryString

El operador queryString permite consultar una combinación de campos y valores indexados. Puede realizar búsquedas de texto, comodín, expresiones regulares, difusas y de rango en campos string utilizando el operador queryString.

queryString tiene la siguiente sintaxis:

1{
2 "$search": {
3 "index": <index name>, // optional, defaults to "default"
4 "queryString": {
5 "defaultPath": "<default-field-to-search>",
6 "query": "(<field-to-search>: (<search-values>) AND|OR (<search-values>)) AND|OR (<search-values>)"
7 }
8 }
9}

queryString utiliza los siguientes términos para construir una consulta:

Campo
Tipo
Descripción
Necesidad

defaultPath

string

El campo indexado que se buscará de forma predeterminada. MongoDB Search solo busca el campo en defaultPath si omite el campo de búsqueda en query.

query

string

Uno o más campos y valores indexados para buscar. Los campos y valores se delimitan con dos puntos. Por ejemplo, para buscar la cadena baseball en el campo plot, utilice plot:baseball. Los siguientes operadores permiten combinar varios criterios de búsqueda:

Puede combinar los campos y valores utilizando lo siguiente:

AND

Indica AND operador booleano. Todos los valores de búsqueda deben estar presentes para que un documento se incluya en los resultados.

OR

Indica el operador booleano OR. Al menos uno de los valores de búsqueda debe estar presente para que un documento se incluya en los resultados.

NOT

Indica el operador booleano NOT. El valor de búsqueda especificado debe estar ausente para que un documento se incluya en los resultados.

TO

Indica el rango de búsqueda. Puede usar [] para un rango inclusivo, {} para un rango exclusivo, o {] y [} para un rango semiabierto. Cualquier valor dentro del rango especificado debe estar presente para que un documento se incluya en los resultados.

()

Delimitadores para subconsultas. Use los paréntesis para agrupar campos y valores en la búsqueda.

Puede ejecutar consultas de expresiones regulares y comodines utilizando lo siguiente:

?

Indica cualquier carácter individual que coincida.

*

Indica 0 o más caracteres para coincidir.

El operador queryString no admite consultas con comodines cuyo primer carácter sea *. El operador queryString considera cualquier carácter que preceda a * como prefijo o como caracteres que deben coincidir exactamente.

/

Delimitador para expresión regular.

~

Indica una búsqueda difusa para encontrar cadenas similares al término de búsqueda hasta el número especificado de ediciones. Por ejemplo, { "query":"foo":"stop"~2 } equivale a lo siguiente:

{ "defaultPath": "foo", "query": "stop", "maxEdits": 2 }

El operador queryString solo admite la búsqueda difusa para un máximo de 2 ediciones. Las distancias mayores no son útiles, ya que los resultados pueden coincidir con muchos términos del diccionario.

Si usa ~ con varios términos en una cadena, el operador queryString realiza una búsqueda de proximidad para los términos dentro del número especificado. Por ejemplo, { "query":"foo":"New York"~2 } es igual a lo siguiente:

{ "defaultPath": "foo", "query": "New York", "slop": 2 }

score

Objeto

La puntuación asignada a los resultados de búsqueda coincidentes. Puede modificar la puntuación predeterminada con las siguientes opciones:

  • boost:multiplica la puntuación del resultado por el número dado.

  • constant:reemplace la puntuación del resultado con el número dado.

  • function:reemplace la puntuación del resultado con la expresión dada.

Al consultar valores de una matriz, MongoDB Search asigna puntuaciones más altas si más valores en la matriz coinciden con la consulta.

Para obtener información sobre el uso de score en su consulta, consulte Califica los documentos en los resultados.

no

De forma predeterminada, el El operadorqueryString utiliza el bm25 algoritmo de similitud para puntuar los documentos según su relevancia para la consulta.

Puede cambiar el algoritmo de similitud utilizado especificando uno diferente en la similarity.type propiedad para los string campos de la definición del índice de MongoDB Search. Para aprender a configurar un índice de MongoDB Search para el string tipo, consulte Cómo indexar campos de cadena.

Para obtener más información sobre los algoritmos de similitud admitidos, consulta Detalles de la puntuación.

Los siguientes ejemplos utilizan la movies colección en la sample_mflix base de datos. Si tiene el conjunto de datos de ejemplo en su clúster, puede crear el índice de búsqueda de MongoDB llamado default con asignaciones dinámicas y ejecutar las consultas de ejemplo en su clúster.

El siguiente ejemplo utiliza el queryString operador para consultar películas con el título Rocky IV4y, o Four title en la ruta de la movies colección. En la siguiente consulta, se especifica un campo defaultPath en, pero no se especifica ninguno query en. La consulta incluye una etapa para excluir todos los $project campos title excepto.

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "Rocky AND (IV OR 4 OR Four)"
7 }
8 }
9 },
10 {
11 $project: {
12 "_id": 0,
13 "title": 1
14 }
15 }
16])

Para esta consulta, MongoDB Search realiza una búsqueda en defaultPath porque no hay campos en query. Devuelve los siguientes resultados:

{ "title" : "Rocky IV" }

El siguiente ejemplo utiliza el queryString operador para consultar películas con el título Rocky y ninguna de las formas de 2 los3 4números,, o 5 en la ruta title de la movies colección. En la siguiente consulta, se especifica un campo defaultPath en, pero no se especifica ningún campo query en. La consulta incluye una etapa para excluir todos los $project campos title excepto.

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "Rocky AND NOT ((II OR 2 OR Two) OR (III OR 3 OR Three) OR (IV OR 4 OR Four) OR (V OR 5 OR Five))"
7 }
8 }
9 },
10 {
11 $project: {
12 "_id": 0,
13 "title": 1
14 }
15 }
16])
[
{ title: 'Rocky' },
{ title: 'Rocky Marciano' },
{ title: 'Rocky Balboa' },
{ title: 'The Rocky Horror Picture Show' },
{ title: 'The Adventures of Rocky & Bullwinkle' }
]

El siguiente ejemplo utiliza el operador queryString para consultar una combinación de campos de películas con el título The Italian en el género Drama. El campo plot del defaultPath se buscará solo si no se encuentran resultados coincidentes en ninguno de los campos especificados en el campo query. El campo query contiene comillas dobles de escape como delimitadores de la frase a buscar.

La consulta incluye una etapa $project para:

  • Excluir todos los campos excepto _id, title, plot y genres

  • Agregue un campo llamado score

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "plot",
6 "query": "title:\"The Italian\" AND genres:Drama"
7 }
8 }
9 },
10 {
11 $project: {
12 "_id": 1,
13 "title": 1,
14 "plot": 1,
15 "genres": 1,
16 score: { $meta: "searchScore" }
17 }
18 }
19])
{
"_id" : ObjectId("573a1390f29313caabcd56df"),
"plot" : "An immigrant leaves his sweetheart in Italy to find a better life across the sea in the grimy slums of New York. They are eventually reunited and marry. But life in New York is hard and ...",
"genres" : [ "Drama" ],
"title" : "The Italian",
"score" : 4.975106716156006
}
{
"_id" : ObjectId("573a13b3f29313caabd3e36c"),
"plot" : "Set in 2002, an abandoned 5-year-old boy living in a rundown orphanage in a small Russian village is adopted by an Italian family.",
"genres" : [ "Drama" ],
"title" : "The Italian",
"score" : 4.975106716156006
}
{
"_id" : ObjectId("573a13c7f29313caabd756ee"),
"plot" : "A romantic fairy tale about a 19-year old orphan girl who, as her sole inheritance, gets an antique key that unlocks both an old Italian villa and the secrets of her family history.",
"genres" : [ "Comedy", "Drama", "Romance" ],
"title" : "The Italian Key",
"score" : 4.221206188201904
}
{
"_id" : ObjectId("573a13caf29313caabd7d1e4"),
"plot" : "A chronicle of the 1969 bombing at a major national bank in Milan and its aftermath.",
"genres" : [ "Drama" ],
"title" : "Piazza Fontana: The Italian Conspiracy",
"score" : 3.4441356658935547
}

El siguiente ejemplo utiliza el queryString operador para consultar una combinación de términos, captain o kirk enterprisey, en el plot campo. Incluye una etapa para limitar la salida $limit a 3 resultados y una etapa $project para:

  • Excluir todos los campos excepto title, plot y fullplot

  • Agregue un campo llamado score

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "fullplot",
6 "query": "plot:(captain OR kirk) AND enterprise"
7 }
8 }
9 },
10 {
11 $limit: 3
12 },
13 {
14 $project: {
15 "_id": 0,
16 "title": 1,
17 "plot": 1,
18 "fullplot": 1,
19 score: { $meta: "searchScore" }
20 }
21 }
22])
{
"plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.",
"fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.",
"title" : "Star Trek: Generations",
"score" : 11.274821281433105
}
{
"plot" : "Captain Kirk and his crew must deal with Mr. Spock's long-lost half-brother who hijacks the Enterprise for an obsessive search for God at the center of the galaxy.",
"fullplot" : "When the newly-christened starship Enterprise's shakedown cruise goes poorly, Captain Kirk and crew put her into Spacedock for repairs. But an urgent mission interrupts their Earth-bound shore leave. A renegade Vulcan named Sybok has taken three ambassadors hostage on Nimbus III, the Planet of Galactic Peace. This event also attracts the attention of a Klingon captain who wants to make a name for himself and sets out to pursue the Enterprise. Sybok's ragtag army captures the Enterprise and takes her on a journey to the center of the galaxy in search of the Supreme Being.",
"title" : "Star Trek V: The Final Frontier",
"score" : 9.889547348022461
}
{
"plot" : "When an alien spacecraft of enormous power is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine and hopefully stop the intruder.",
"fullplot" : "A massive alien spacecraft of enormous power is approaching Earth, destroying everything in its path. The only star ship in range is the USS Enterprise still in dry-dock after a major overhaul. As Captain Willard Decker readies his ship and his crew to face this menace, Admiral James T. Kirk arrives with orders to take command of the Enterprise and intercept the alien intruder. But it has been three years since Kirk last commanded the Enterprise on its historic five year mission... is he up to the task of saving the Earth?",
"title" : "Star Trek: The Motion Picture",
"score" : 8.322310447692871
}

Los documentos en los resultados coinciden porque:

  • En el primer documento, el campo plot, que corresponde a la búsqueda según query, contiene captain y kirk, aunque solo se requiere uno de ellos para cumplir los criterios de coincidencia. Para el término enterprise, MongoDB Search busca en el campo fullplot, que corresponde al defaultPath, ya que el campo plot no contiene enterprise, y encuentra enterprise en el campo fullplot.

  • En el segundo documento, el campo plot contiene los tres términos de búsqueda.

  • En el tercer documento, el campo plot contiene kirk y enterprise.

Los ejemplos de esta sección utilizan el operador queryString para buscar argumentos de películas que contengan los términos captain, kirk y chess. Este ejemplo muestra cómo la agrupación de los mismos términos de búsqueda entre paréntesis puede dar lugar a la inclusión de diferentes documentos en los resultados.

La consulta también incluye una etapa $project para:

  • Excluir todos los campos excepto title, plot y fullpath

  • Agregue un campo llamado score

La siguiente consulta busca chess y captain o kirk en el campo plot.

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "fullplot",
6 "query": "plot:(captain OR kirk) AND chess"
7 }
8 }
9 },
10 {
11 $project: {
12 "_id": 0,
13 "title": 1,
14 "plot": 1,
15 "fullplot": 1,
16 score: { $meta: "searchScore" }
17 }
18 }
19])
{
"fullplot" : "When the crew of the Enterprise is called back home, they find an unstoppable force of terror from within their own organization has detonated the fleet and everything it stands for, leaving our world in a state of crisis. With a personal score to settle, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction. As our heroes are propelled into an epic chess game of life and death, love will be challenged, friendships will be torn apart, and sacrifices must be made for the only family Kirk has left: his crew.",
"plot" : "After the crew of the Enterprise find an unstoppable force of terror from within their own organization, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction.",
"title" : "Star Trek Into Darkness",
"score" : 7.968792915344238
}

El documento en los resultados es una coincidencia porque plot contiene los términos captain y kirk, aunque solo se necesita uno para cumplir los criterios de coincidencia, y el término chess, aunque no está en plot, aparece en fullplot, que es defaultPath.

La siguiente consulta busca captain o kirk y chess en el campo plot.

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "fullplot",
6 "query": "plot:captain OR (kirk AND chess)"
7 }
8 }
9 },
10 {
11 $limit: 5
12 },
13 {
14 $project: {
15 "_id": 0,
16 "title": 1,
17 "plot": 1,
18 "fullplot": 1,
19 score: { $meta: "searchScore" }
20 }
21 }
22])
{
"fullplot" : "When the crew of the Enterprise is called back home, they find an unstoppable force of terror from within their own organization has detonated the fleet and everything it stands for, leaving our world in a state of crisis. With a personal score to settle, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction. As our heroes are propelled into an epic chess game of life and death, love will be challenged, friendships will be torn apart, and sacrifices must be made for the only family Kirk has left: his crew.",
"plot" : "After the crew of the Enterprise find an unstoppable force of terror from within their own organization, Captain Kirk leads a manhunt to a war-zone world to capture a one-man weapon of mass destruction.",
"title" : "Star Trek Into Darkness",
"score" : 9.227973937988281
}
{
"plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.",
"title" : "Star Trek: Generations",
"fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.",
"score" : 3.3556222915649414
}
{
"plot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every ...",
"title" : "Scent of a Woman",
"fullplot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every situation, nicknames the youth Ciccio (\"Babyfat\"), and spends the next few days ordering him about and generally behaving badly in public. In Rome, Fausto summons a priest to ask for his blessing; in Naples, where Fausto joins a blind lieutenant for drinking and revelry, the two soldiers talk quietly and seriously about \"going through with it.\" Also in Naples is Sara, in love with Fausto, but treated cruelly by him. What do the blind soldiers plan? Can Sara soften Fausto's hardened heart?",
"score" : 3.2553727626800537
}
{
"plot" : "A seductive woman falls in love with a mysterious ship's captain.",
"title" : "Pandora and the Flying Dutchman",
"fullplot" : "Albert Lewin's interpretation of the legend of the Flying Dutchman. In a little Spanish seaport named Esperanza, during the 30s, appears Hendrick van der Zee, the mysterious captain of a yacht (he is the only one aboard). Pandora is a beautiful woman (who men kill and die for). She's never really fallen in love with any man, but she feels very attracted to Hendrick... We are soon taught that Hendrick is the Flying Dutchman, this sailor of the 17th century that has been cursed by God to wander over the seas until the Doomsday... unless a woman is ready to die for him...",
"score" : 3.2536067962646484
}
{
"plot" : "The adventures of pirate Captain Red and his first mate Frog.",
"title" : "Pirates",
"fullplot" : "Captain Red runs a hardy pirate ship with the able assistance of Frog, a dashing young French sailor. One day Capt. Red is captured and taken aboard a Spanish galleon, but thanks to his inventiveness, he raises the crew to mutiny, takes over the ship, and kidnaps the niece of the governor of Maracaibo. The question is, can he keep this pace up?",
"score" : 3.2536067962646484
}

Los documentos de los resultados coinciden porque el campo plot contiene el término captain. El primer documento obtiene una puntuación más alta porque MongoDB Search también encuentra los términos kirk y chess en el campo fullplot, aunque no es necesario que estén presentes para cumplir los criterios de coincidencia.

El siguiente ejemplo utiliza el operador queryString para query los títulos de películas, cubriendo un rango de valores textuales desde los caracteres count hasta cualquier carácter (definido usando el carácter comodín *), en orden alfabético ascendente.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "plot",
6 "query": "title:[count TO *]"
7 }
8 }
9 },
10 {
11 "$limit": 10
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1
17 }
18 }
19])
1[
2 { title: 'Blacksmith Scene' },
3 { title: 'The Great Train Robbery' },
4 { title: 'The Land Beyond the Sunset' },
5 { title: 'A Corner in Wheat' },
6 { title: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics' },
7 { title: 'Traffic in Souls' },
8 { title: 'Gertie the Dinosaur' },
9 { title: 'In the Land of the Head Hunters' },
10 { title: 'The Perils of Pauline' },
11 { title: 'The Birth of a Nation' }
12]

Los resultados de MongoDB Search incluyen películas con los títulos Blacksmith Scene y A Corner in Wheat, aunque el rango de la consulta comienza a partir de los caracteres count. Al indexar con el analizador predeterminado, lucene.standard, MongoDB Search crea tokens separados para los términos del campo title y relaciona el término de consulta con los tokens individuales. En concreto, MongoDB Search crea los siguientes tokens, de los cuales al menos uno (indicado con √) coincide con los criterios de la consulta:

Título
Tokens de analizador estándar

Escena del herrero

blacksmith, scene

A Corner in Wheat (Una esquina en el trigo)

a, corner, in, wheat

Si indexa utilizando el analizador lucene.keyword, MongoDB Search creará un único token para toda la cadena en el campo title, lo que generará resultados similares a los siguientes para la misma consulta:

[
{ title: 'è Nous la Libertè' },
{ title: 'tom thumb' },
{ title: 'è nos amours' },
{ title: 'èke och hans vèrld' },
{ title: 'èdipussi' },
{ title: 's/y Glèdjen' },
{ title: 'èAy, Carmela!' },
{ title: 'èlisa' },
{ title: 'èxtasis' },
{ title: 'eXistenZ' }
]

El siguiente ejemplo utiliza el operador queryString para consultar los géneros de películas para drama y los títulos para un rango de valores textuales entre man y men, incluidos ambos, en orden alfabético ascendente.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "plot",
6 "query": "title:[man TO men] AND genres: Drama"
7 }
8 }
9 },
10 {
11 "$limit": 10
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1,
17 "genres": 1
18 }
19 }
20])
1[
2 { genres: [ 'Drama' ], title: 'The Wedding March' },
3 { genres: [ 'Drama' ], title: 'Maria Chapdelaine' },
4 { genres: [ 'Drama' ], title: 'Of Mice and Men' },
5 { genres: [ 'Drama' ], title: 'All the King's Men' },
6 { genres: [ 'Drama' ], title: 'Wuya yu maque' },
7 { genres: [ 'Drama' ], title: 'The Men' },
8 { genres: [ 'Drama' ], title: 'The Member of the Wedding' },
9 { genres: [ 'Drama' ], title: 'The Great Man' },
10 { genres: [ 'Drama' ], title: 'A Matter of Dignity' },
11 { genres: [ 'Drama' ], title: 'The Last Angry Man' }
12]

Los documentos en los resultados coinciden porque el campo genres contiene el término drama y el campo de película title contiene términos entre Man y Men en orden alfabético (Man, Maque, March, Maria, Matter, Member y Men en los resultados).

Los siguientes ejemplos utilizan el queryString operador para consultar títulos de películas mediante expresiones difusas, comodín y regulares. Las consultas incluyen una etapa para excluir todos los $project campos title excepto.

La siguiente consulta utiliza una búsqueda difusa (~) para realizar una búsqueda difusa en el campo title de títulos de películas que contengan términos similares a catch con una variación de hasta dos caracteres.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "catch~2"
7 }
8 }
9 },
10 {
11 "$limit": 10
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1
17 }
18 }
19])
1[
2 { title: 'Catch-22' },
3 { title: 'Catch That Girl' },
4 { title: 'Catch That Kid' },
5 { title: 'Catch a Fire' },
6 { title: 'Catch Me Daddy' },
7 { title: 'Death Watch' },
8 { title: 'Patch Adams' },
9 { title: "Batch '81" },
10 { title: 'Briar Patch' },
11 { title: 'Night Watch' }
12]

La siguiente consulta utiliza una expresión comodín para buscar en el campo title títulos de películas que contengan los caracteres cou*t?*, donde * indica cualquier número adicional de caracteres y ? indica cualquier carácter individual.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "cou*t?*"
7 }
8 }
9 },
10 {
11 "$limit": 5
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1
17 }
18 }
19])
1[
2 { title: 'A Day in the Country' },
3 { title: 'Diary of a Country Priest' },
4 { title: 'Cry, the Beloved Country' },
5 { title: 'The Country Girl' },
6 { title: 'Raintree County' }
7]

Los documentos en los resultados coinciden porque el campo title contiene el término Country o County, que coincide con los criterios de consulta para caracteres que comienzan con cou seguido de cualquier número de caracteres (n en los resultados) y luego t seguido de al menos uno o muchos caracteres (r como en country o y como en county en los resultados).

La siguiente consulta utiliza una expresión regular para buscar en el campo title títulos de películas que contengan caracteres que comiencen con cualquier carácter seguido de los caracteres tal y y o ian después de tal.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "/.tal(y|ian)/"
7 }
8 }
9 },
10 {
11 "$limit": 5
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1
17 }
18 }
19])
1[
2 { title: 'The Italian' },
3 { title: 'Journey to Italy' },
4 { title: 'Divorce Italian Style' },
5 { title: 'Marriage Italian Style' },
6 { title: 'Jealousy, Italian Style' }
7]

Los documentos en los resultados coinciden porque el campo title contiene el término Italy o Italian, que coincide con los criterios de consulta para cualquier carácter (I en los resultados) seguido de tal con y (como en Italy en los resultados) o ian (como en Italian en los resultados).

La siguiente consulta busca en el campo title de la colección movies Marvel, Avengers, Iron Man o Captain America.

La siguiente consulta devuelve películas en los siguientes grupos (años) que coinciden con los criterios de búsqueda:

  • 2000, límite inferior inclusivo para este depósito

  • 2005, límite superior exclusivo para el cubo 2000 y límite inferior inclusivo para este cubo

  • 2010, límite superior exclusivo para el cubo 2005 y límite inferior inclusivo para este cubo

  • 2015, límite superior exclusivo para el cubo 2010 y límite inferior inclusivo para este cubo

  • 2020, límite superior exclusivo para el depósito 2015

1db.movies.aggregate([
2 {
3 "$searchMeta": {
4 "facet": {
5 "operator": {
6 "queryString": {
7 "defaultPath": "title",
8 "query": "\"Marvel\" OR \"Avengers\" OR \"Iron Man\" OR \"Captain America\""
9 }
10 },
11 "facets": {
12 "yearFacet": {
13 "type": "number",
14 "path": "year",
15 "boundaries": [1990, 2000, 2005, 2010, 2015, 2020 ]
16 }
17 }
18 }
19 }
20 }
21])
[
{
count: { lowerBound: Long('16') },
facet: {
yearFacet: {
buckets: [
{ _id: 1990, count: Long('1') },
{ _id: 2000, count: Long('0') },
{ _id: 2005, count: Long('4') },
{ _id: 2010, count: Long('10') },
{ _id: 2015, count: Long('1') }
]
}
}
}
]

La siguiente consulta devuelve películas que coinciden con los criterios de búsqueda y que se encuentran en los siguientes grupos (años):

  • 2000, límite inferior inclusivo para este depósito

  • 2005, límite superior exclusivo para el cubo 2000 y límite inferior inclusivo para este cubo

  • 2010, límite superior exclusivo para el cubo 2005 y límite inferior inclusivo para este cubo

  • 2015, límite superior exclusivo para el cubo 2010 y límite inferior inclusivo para este cubo

  • 2020, límite superior exclusivo para el depósito 2015

1db.movies.aggregate([
2 {
3 "$search": {
4 "facet": {
5 "operator": {
6 "queryString": {
7 "defaultPath": "title",
8 "query": "\"Marvel\" OR \"Avengers\" OR \"Iron Man\" OR \"Captain America\""
9 }
10 },
11 "facets": {
12 "yearFacet": {
13 "type": "number",
14 "path": "year",
15 "boundaries": [1990, 2000, 2005, 2010, 2015, 2020 ]
16 }
17 }
18 }
19 }
20 },
21 {
22 "$facet": {
23 "docs": [
24 { "$project":
25 {
26 "title": 1,
27 "year": 1
28 }
29 }
30 ],
31 "meta": [
32 {"$replaceWith": "$$SEARCH_META"},
33 {"$limit": 1}
34 ]
35 }
36 },
37 {
38 "$set": {
39 "meta": {
40 "$arrayElemAt": ["$meta", 0]
41 }
42 }
43 }
44])
[
{
docs: [
{
_id: ObjectId('573a13f3f29313caabddecf8'),
title: 'Iron Man and Captain America: Heroes United',
year: 2014
},
{
_id: ObjectId('573a13adf29313caabd2bf71'),
title: 'Iron Man',
year: 2008
},
{
_id: ObjectId('573a13c1f29313caabd659d3'),
title: 'Iron Man 2',
year: 2010
},
{
_id: ObjectId('573a13c3f29313caabd69c74'),
title: 'Iron Man 3',
year: 2013
},
{
_id: ObjectId('573a13b4f29313caabd4011f'),
title: 'Captain America: The First Avenger',
year: 2011
},
{
_id: ObjectId('573a13d2f29313caabd91d33'),
year: 2014,
title: 'Captain America: The Winter Soldier'
},
{
_id: ObjectId('573a13bbf29313caabd53752'),
title: 'The Invincible Iron Man',
year: 2007
},
{
_id: ObjectId('573a139af29313caabcf075d'),
title: 'The Avengers',
year: 1998
},
{
_id: ObjectId('573a13b6f29313caabd47da7'),
title: 'Ultimate Avengers',
year: 2006
},
{
_id: ObjectId('573a13baf29313caabd506e4'),
year: 2012,
title: 'The Avengers'
},
{
_id: ObjectId('573a13e0f29313caabdba876'),
title: 'Iron Man: Rise of Technovore',
year: 2013
},
{
_id: ObjectId('573a13b8f29313caabd4ca34'),
title: 'Ultimate Avengers II',
year: 2006
},
{
_id: ObjectId('573a13dcf29313caabdb2759'),
title: 'Avengers: Age of Ultron',
year: 2015
},
{
_id: ObjectId('573a13d9f29313caabda9807'),
title: 'Marvel One-Shot: Item 47',
year: 2012
},
{
_id: ObjectId('573a13e6f29313caabdc59ff'),
title: 'Marvel One-Shot: Agent Carter',
year: 2013
},
{
_id: ObjectId('573a13ecf29313caabdd271a'),
title: 'Avengers Confidential: Black Widow & Punisher',
year: 2014
}
],
meta: {
count: { lowerBound: Long('16') },
facet: {
yearFacet: {
buckets: [
{ _id: 1990, count: Long('1') },
{ _id: 2000, count: Long('0') },
{ _id: 2005, count: Long('4') },
{ _id: 2010, count: Long('10') },
{ _id: 2015, count: Long('1') }
]
}
}
}
}
]

Volver

frase

En esta página