Menu Docs
Página inicial do Docs
/
MongoDB Atlas
/ / / /

String de query

Nesta página

  • Definição
  • Sintaxe
  • Opções
  • Exemplos
  • Queries de operadores booleanos
  • Queries de intervalo
  • Queries curinga
queryString

O operador queryString suporta fazer uma query de uma combinação de campos e valores indexados. Você pode executar pesquisas de texto, curinga, expressão regular, difusa e intervalo em campos do string utilizando o operador queryString.

queryString tem a seguinte sintaxe:

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 usa os seguintes termos para construir uma consulta:

Campo
Tipo
Descrição
necessidade
defaultPath
string
O campo indexado para pesquisar por padrão. O Atlas Search pesquisa somente o campo no defaultPath se você omitir o campo para pesquisar no query.
sim
query
string

Um ou mais campos e valores indexados para pesquisar. Campos e valores são delimitados por ponto e vírgula. Por exemplo, para pesquisar o campo plot para a string baseball, use plot:baseball. Os seguintes operadores estão disponíveis para combinar vários critérios de pesquisa:

Você pode combinar os campos e valores utilizando o seguinte:

AND
Indica o operador booleano AND . Todos os valores de pesquisa devem estar presentes para que um documento seja incluído nos resultados.
OR
Indica o operador booleano OR . Pelo menos um dos valores de pesquisa deve estar presente para que um documento seja incluído nos resultados.
NOT
Indica o operador booleano NOT. O valor de pesquisa especificado deve estar ausente para que um documento seja incluído nos resultados.
TO
Indica o intervalo a ser pesquisado. Você pode usar o(a) [] para uma faixa inclusiva, o(a) {} para uma faixa exclusiva ou o(a) {] e o(a) [} para uma faixa meio aberta. Qualquer valor que caia dentro do intervalo especificado deve estar presente para que um documento seja incluído nos resultados.
()
Delimitadores para subqueries. Use os parênteses para agrupar campos e valores para procurar.

Dica

Veja também:

Exemplos de alguns exemplos de queries que usam operadores e delimitadores para pesquisar a coleção de amostra movies .

Você pode executar queries de expressão regular e curinga utilizando o seguinte:

?
Indica a correspondência de qualquer caractere individual.
*
Indica 0 ou mais caracteres para corresponder.
/
Delimitador para expressão regular.
~

Indica a procurar difusa para encontrar strings semelhantes ao termo de pesquisa. Se você usar isso com vários termos em uma string, o operador queryString fará uma procurar de proximidade para os termos dentro do número especificado de termos.

Observação

Para pesquisas difusas, o operador queryString combina termos de até no máximo 2 edições. Distâncias maiores não são úteis, pois podem corresponder a uma quantidade significativa do termo do dicionário. Por exemplo, "foo":"stop"~2 é igual ao seguinte:

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

Para pesquisa de proximidade, o operador queryString corresponde aos termos utilizando a distância especificada entre palavras na frase de pesquisa. Por exemplo, "foo":"New York"~2 é igual ao seguinte:

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

Observação

O operador queryString não suporta uma query curinga com * como o primeiro caractere na query. O operador queryString trata qualquer caractere que antecede o * como prefixo ou como caracteres que devem corresponder exatamente.

sim
score
objeto

A pontuação atribuída aos resultados de pesquisa correspondentes. Você pode modificar a pontuação padrão usando as seguintes opções:

  • boost: multiplique a pontuação do resultado pelo número fornecido.

  • constant: substitui a pontuação do resultado pelo número fornecido.

  • function: substitua a pontuação do resultado pela expressão fornecida.

Para obter informações sobre como utilizar o score em sua consulta, consulte Classificar os documentos nos resultados.

Observação

Quando você faz query de valores em arrays, o Atlas Search não altera a pontuação dos resultados correspondentes com base no número de valores dentro da array que correspondeu à query. A pontuação seria igual a uma única correspondência, independentemente do número de correspondências dentro de uma array.

não

Os exemplos seguintes utilizam a coleção movies no banco de dados sample_mflix. Se você tiver o conjunto de dados de amostra no seu cluster, você poderá criar o índice Atlas Search denominado default com mapeamentos dinâmicos e executar as queries de exemplo no seu cluster.

O exemplo a seguir usa o operador queryString para consultar filmes com o título Rocky e ou IV, 4ou Four.

Exemplo

A consulta a seguir pesquisa a combinação de Rocky e ou IV, 4ou Four no caminho title na coleção movies . Na seguinte consulta, um campo é especificado no defaultPath, mas nenhum campo é especificado no query. A consulta inclui um estágio $project para excluir todos os campos, exceto title.

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, o Atlas Search executa uma pesquisa no defaultPath porque não há campos no query. Retorna os seguintes resultados:

{ "title" : "Rocky IV" }

O exemplo a seguir usa o operador queryString para consultar filmes com o título Rocky e não II, III, VI ou V.

Exemplo

A consulta a seguir procura a string Rocky e não qualquer forma dos números 2, 3, 4 ou 5 no caminho title na coleção movies . Na seguinte consulta, um campo é especificado no defaultPath, mas nenhum campo é especificado no query. A consulta inclui um estágio $project para excluir todos os campos, exceto title.

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])

Para esta consulta, o Atlas Search executa uma pesquisa no defaultPath porque não há campos no query. Retorna os seguintes resultados:

[
{ title: 'Rocky' },
{ title: 'Rocky Marciano' },
{ title: 'Rocky Balboa' },
{ title: 'The Rocky Horror Picture Show' },
{ title: 'The Adventures of Rocky & Bullwinkle' }
]

O exemplo a seguir usa o operador queryString para consultar filmes com o título The Italian no gênero Drama .

Exemplo

A consulta a seguir pesquisa uma combinação de campos para filmes com o título The Italian no gênero Drama . O campo plot no defaultPath será pesquisado somente se nenhum resultado correspondente puder ser encontrado em qualquer um dos campos especificados no campo query . O campo query contém aspas duplas como delimitadores da frase a ser pesquisada.

A query inclui um estágio do $project para:

  • Exclua todos os campos, exceto _id, title, plot e genres

  • Adicione um campo chamado 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])

Esta query retorna os seguintes resultados:

1{
2 "_id" : ObjectId("573a1390f29313caabcd56df"),
3 "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 ...",
4 "genres" : [ "Drama" ],
5 "title" : "The Italian",
6 "score" : 4.975106716156006
7}
8{
9 "_id" : ObjectId("573a13b3f29313caabd3e36c"),
10 "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.",
11 "genres" : [ "Drama" ],
12 "title" : "The Italian",
13 "score" : 4.975106716156006
14}
15{
16 "_id" : ObjectId("573a13c7f29313caabd756ee"),
17 "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.",
18 "genres" : [ "Comedy", "Drama", "Romance" ],
19 "title" : "The Italian Key",
20 "score" : 4.221206188201904
21}
22{
23 "_id" : ObjectId("573a13caf29313caabd7d1e4"),
24 "plot" : "A chronicle of the 1969 bombing at a major national bank in Milan and its aftermath.",
25 "genres" : [ "Drama" ],
26 "title" : "Piazza Fontana: The Italian Conspiracy",
27 "score" : 3.4441356658935547
28}

O exemplo seguinte utiliza o operador queryString para fazer uma query de gráficos de filme que contêm os termos captain ou kirk e enterprise.

Exemplo

A consulta a seguir procura uma combinação de termos, captain ou kirk e enterprise, no campo plot . Inclui um estágio do $limit para limitar o resultado para 3 resultados e um estágio do $project para:

  • Exclua todos os campos, exceto title, plot e fullplot

  • Adicione um campo chamado 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])

Esta query retorna os seguintes resultados:

1{
2 "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.",
3 "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.",
4 "title" : "Star Trek: Generations",
5 "score" : 11.274821281433105
6}
7{
8 "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.",
9 "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.",
10 "title" : "Star Trek V: The Final Frontier",
11 "score" : 9.889547348022461
12}
13{
14 "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.",
15 "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?",
16 "title" : "Star Trek: The Motion Picture",
17 "score" : 8.322310447692871
18}

Os documentos nos resultados acima correspondem porque:

  • No primeiro documento, o campo plot , que é o campo a ser pesquisado pelo query, contém captain e kirk, embora apenas um seja necessário para atender aos critérios de uma correspondência. Para o termo enterprise, o Atlas Search pesquisa o campo fullplot , que é o defaultPath, porque o campo plot não contém enterprise e localiza enterprise no campo fullplot .

  • No segundo documento, o campo plot contém os três termos de pesquisa.

  • No terceiro documento, o campo plot contém kirk e enterprise.

O exemplo seguinte utiliza o operador queryString para fazer uma query de gráficos de filme que contêm os termos captain, kirk e chess. Este exemplo mostra como o cluster diferente dos mesmos termos de pesquisa usando parênteses pode resultar em documentos diferentes a serem incluídos nos resultados da pesquisa.

Exemplo

As queries a seguir procuram uma combinação dos termos, captain, kirk e chess no campo plot. Cada query retorna um resultado diferente dependendo de como os termos de pesquisa são agrupados.

As queries também incluem um estágio do $project para:

  • Exclua todos os campos, exceto title, plot e fullpath

  • Adicione um campo chamado score

A consulta a seguir procura chess e captain ou kirk no 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])

Esta query retorna os seguintes resultados:

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

O documento nos resultados acima é uma correspondência, pois o plot contém os termos captain e kirk, embora apenas um seja necessário para atender aos critérios para uma correspondência, e o termo chess, embora não esteja no plot, aparece no fullplot, que é o defaultPath.

A consulta a seguir procura captain ou kirk e chess no campo plot .

db.movies.aggregate([
{
$search: {
"queryString": {
"defaultPath": "fullplot",
"query": "plot:captain OR (kirk AND chess)"
}
}
},
{
$limit: 5
},
{
$project: {
"_id": 0,
"title": 1,
"plot": 1,
"fullplot": 1,
score: { $meta: "searchScore" }
}
}
])

Esta query retorna os seguintes resultados:

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

Os documentos nos resultados acima correspondem porque o campo plot contém o termo captain. O primeiro documento obtém uma pontuação maior porque o Atlas Search também encontra os termos kirk e chess no campo fullplot , embora os termos não precisem estar presentes para atender aos critérios de uma correspondência.

O exemplo a seguir usa o operador queryString para consultar os títulos de filme um intervalo de valores textuais dos caracteres count para qualquer caractere (definido usando o caractere curinga *) em ordem alfabética crescente.

Exemplo

1 db.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]

Os resultados do Atlas Search incluem filmes com títulos Blacksmith Scene e A Corner in Wheat, embora o intervalo na consulta comece com os caracteres count. Quando você indexa com o analisador padrão, lucene.standard, o Atlas Search cria tokens separados para os termos no campo title e faz a correspondência entre o termo da consulta e os tokens individuais. Especificamente, o Atlas Search cria os seguintes tokens, dos quais pelo menos um (indicado por √) corresponde aos critérios de consulta:

Título
Tokens de analisador padrão
Cena de ferreiro
blacksmith, scene
Um Cantinho no Trigo
a, corner, in, wheat

Se você indexar usando o analisador de lucene.keyword , o Atlas Search criará um único token para toda a cadeia de caracteres no campo title , resultando em resultados semelhantes aos seguintes para a mesma 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' }
]

O exemplo a seguir usa o operador queryString para consultar os gêneros de filme drama e os títulos de uma faixa de valores textuais entre man e men, incluindo ambos, em ordem alfabética crescente.

Exemplo

1 db.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]

Os documentos nos resultados correspondem porque o campo genres contém o termo drama e o campo de filme title contém termos entre Man e Men em ordem alfabética (Man, Maque, March, Maria, Matter, Member e Men nos resultados).

Os exemplos seguintes utilizam o operador queryString para fazer uma query títulos de filmes utilizando expressões difusas, curingas e regulares. As queries incluem um estágio $project para excluir todos os campos, exceto title.

A consulta a seguir usa fuzzy (~) para fazer uma pesquisa fuzzy no campo title para títulos de filmes que contêm termos semelhantes a catch com uma variação de até dois 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]

A query a seguir usa uma expressão curinga para o Atlas Search no campo title para títulos de filmes que contenham caracteres cou*t?*, em que * indica qualquer número adicional de caracteres e ? indica qualquer caractere único.

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]

Os documentos nos resultados correspondem porque o campo title contém o termo Country ou County, que corresponde aos critérios da query para caracteres que começam com cou seguidos por qualquer número de caracteres (n nos resultados) e em seguida, t seguido por pelo menos um ou muitos caracteres (r como em country ou y como em county nos resultados).

A query a seguir usa uma expressão regular para pesquisar no campo title títulos de filmes que contenham caracteres que comecem com qualquer caractere seguido pelos caracteres tal e y ou ian após 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]

Os documentos nos resultados correspondem porque o campo title contém o termo Italy ou Italian, que corresponde aos critérios de query para qualquer caractere (I nos resultados) seguido por tal com y (como em Italy nos resultados) ou ian (como em Italian nos resultados).

Voltar

frase

Próximo

faixa