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

Etapa 2: Executar queries de pesquisa do Atlas

Nesta página

  • Procedimento
  • Próximos passos

➤ Use o menu suspenso Selecione sua linguagem para definir o idioma dos exemplos nesta página.


Importante

Recurso Indisponível em Instâncias sem Servidor

Neste momento, as instâncias sem servidor não permitem essa funcionalidade. Para saber mais, consulte Limitações de instância sem servidor.

Esta parte do tutorial guia você através da execução de queries no Atlas Search.

1
  1. Se ainda não estiver exibido, selecione a organização que contém o projeto desejado no Menu Organizations na barra de navegação.

  2. Se ainda não estiver exibido, selecione o projeto desejado no menu Projects na barra de navegação.

  3. Se a página Clusters ainda não estiver exibida, clique em Database na barra lateral.

2

Você pode acessar a página Atlas Search na barra lateral, o Data Explorer ou a página de detalhes do cluster.

  1. Na barra lateral, clique em Atlas Search sob o título Services .

  2. Na lista suspensa Select data source , selecione seu cluster e clique em Go to Atlas Search.

  1. Clique no botão Browse Collections para o seu cluster.

  2. Expanda o banco de dados e selecione a coleção.

  3. Clique na aba Search Indexes da collection.

  1. Clique no nome do cluster.

  2. Clique na aba Atlas Search.

3

Clique no botão Query à direita do índice para consultar.

4

Clique em Edit Query para visualizar uma amostra de sintaxe de consulta padrão no formato JSON .

5

Copie e cole a seguinte consulta no Query Editor e, em seguida, clique no botão Search no Query Editor.

[
{
$search: {
index: "default",
text: {
query: "baseball",
path: "plot"
}
}
}
]
SCORE: 3.8531038761138916 _id: "573a13b3f29313caabd3b409"
fullplot: "Three guys, all their lives, have been living in the shadow of bullies…"
imdb: Object
year: 2006
SCORE: 3.6254453659057617 _id: "573a1399f29313caabcee801"
plot: "A young boy is bequeathed the ownership of a professional baseball tea..."
genres: Array
runtime: 119
SCORE: 3.6254453659057617 _id: "573a139af29313caabcefe18"
plot: "A trained chimpanzee plays third base for a minor-league baseball team..."
genres: Array
runtime: 94
SCORE: 3.489243507385254 _id: "573a1393f29313caabcdca79"
plot: "The story of the life and career of the famed baseball player, Lou Geh..."
genres: Array
runtime: 128
SCORE: 3.489243507385254 _id: "573a1399f29313caabcecef1"
plot: "Babe Ruth becomes a baseball legend but is unheroic to those who know ..."
genres: Array
runtime: 115
SCORE: 3.4249095916748047 _id: "573a1398f29313caabcebccf"
plot: "Two disquieted junior baseball players seek revenge on the local yakuz…"
genres: Array
runtime: 96
SCORE: 3.4249095916748047 _id: "573a13bdf29313caabd5813d"
plot: "Dominican baseball star Miguel "Sugar" Santos is recruited to play in …"
genres: Array
runtime: 114
SCORE: 3.3629050254821777 _id: "573a139af29313caabcefe79"
plot: "An all star baseball player becomes the unhealthy focus of a down on h…"
genres: Array
runtime: 116
SCORE: 3.303105354309082 _id: "573a1399f29313caabced370"
plot: "A fading baseball player is traded to a Japanese team and has trouble …"
genres: Array
runtime: 108
SCORE: 3.303105354309082 _id: "573a13a0f29313caabd05773"
fullplot: "The story of Baseball Hall-of-Famer Hank Greenberg is told through arc…"
imdb: Object
year: 1998

Para saber mais sobre o estágio do pipeline $search , consulte a sua página de referência. Para obter a documentação completa do aggregation pipeline, consulte oManual do Servidor MongoDB .

6

O Search Tester pode não exibir todos os campos nos documentos que ele retorna. Para exibir todos os campos, incluindo o campo que você especifica no caminho da consulta, expanda o documento nos resultados.

1

Abra o mongosh em uma janela do terminal e conecte ao seu cluster. Para obter instruções detalhadas sobre a conexão, consulte Conectar via mongosh.

2

Execute o seguinte comando no prompt mongosh:

use sample_mflix
3

A query a seguir procura a palavra baseball no campo plot . Ela inclui um estágio $limit para limitar a saída a 5 resultados e um estágio $project para excluir todos os campos, exceto title e plot.

db.movies.aggregate([
{
$search: {
"text": {
"query": "baseball",
"path": "plot"
}
}
},
{
$limit: 5
},
{
$project: {
"_id": 0,
"title": 1,
"plot": 1
}
}
])
{
"plot" : "A trio of guys try and make up for missed
opportunities in childhood by forming a three-player
baseball team to compete against standard children
baseball squads.",
"title" : "The Benchwarmers"
}
{
"plot" : "A young boy is bequeathed the ownership of a
professional baseball team.",
"title" : "Little Big League"
}
{
"plot" : "A trained chimpanzee plays third base for a
minor-league baseball team.",
"title" : "Ed"
}
{
"plot" : "The story of the life and career of the famed
baseball player, Lou Gehrig.",
"title" : "The Pride of the Yankees"
}
{
"plot" : "Babe Ruth becomes a baseball legend but is
unheroic to those who know him.",
"title" : "The Babe"
}

Para obter mais informações sobre o estágio do pipeline $search, consulte sua página de referência. Para obter a documentação completa do pipeline de agregação, consulte o Manual do MongoDB Server.

4

$search tem vários operadores para construir diferentes tipos de queries. A query seguinte utiliza o operador composto para combinar vários operadores em uma única query. Tem os seguintes critérios de pesquisa:

  • O campo plot deve conter Hawaii ou Alaska.

  • O campo plot deve conter um número de quatro dígitos, como um ano.

  • O campo genres não pode conter Comedy ou Romance.

  • O campo title não pode conter Beach ou Snow.

db.movies.aggregate([
{
$search: {
"compound": {
"must": [ {
"text": {
"query": ["Hawaii", "Alaska"],
"path": "plot"
},
},
{
"regex": {
"query": "([0-9]{4})",
"path": "plot",
"allowAnalyzedField": true
}
} ],
"mustNot": [ {
"text": {
"query": ["Comedy", "Romance"],
"path": "genres"
}
},
{
"text": {
"query": ["Beach", "Snow"],
"path": "title"
}
} ]
}
}
},
{
$project: {
"title": 1,
"plot": 1,
"genres": 1,
"_id": 0
}
}
])
{
"plot" : "A modern aircraft carrier is thrown back in time
to 1941 near Hawaii, just hours before the Japanese attack
on Pearl Harbor.",
"genres" : [ "Action", "Sci-Fi" ],
"title" : "The Final Countdown"
}
{
"plot" : "Follows John McCain's 2008 presidential
campaign, from his selection of Alaska Governor Sarah
Palin as his running mate to their ultimate defeat in the
general election.",
"genres" : [ "Biography", "Drama", "History" ],
"title" : "Game Change"
}
{
"plot" : "A devastating and heartrending take on grizzly
bear activists Timothy Treadwell and Amie Huguenard, who
were killed in October of 2003 while living among
grizzlies in Alaska.",
"genres" : [ "Documentary", "Biography" ],
"title" : "Grizzly Man"
}
{
"plot" : "Truman Korovin is a lonely, sharp-witted cab
driver in Fairbanks, Alaska, 1980. The usual routine of
picking up fares and spending his nights at his favorite
bar, the Boatel, is disrupted ...",
"genres" : [ "Drama" ],
"title" : "Chronic Town"
}
1

Abra o MongoDB Compass e conecte-se ao cluster. Para obter instruções detalhadas sobre a conexão, consulte Conectar via Compass.

2

Na tela Database, clique no banco de dados sample_mflix e, em seguida, clique na coleção movies.

3

A query a seguir procura a palavra baseball no campo plot . Ela inclui um estágio $limit para limitar a saída a 5 resultados e um estágio $project para excluir todos os campos, exceto title e plot.

Para executar esta query de pesquisa simples do Atlas Search no MongoDB Compass:

  1. Clique na aba Aggregations.

  2. Clique em Select... e, em seguida, configure cada um dos seguintes estágios do pipeline, selecionando o estágio no menu suspenso e adicionando a consulta para esse estágio. Clique em Add Stage para adicionar estágios adicionais.

    estágio do pipeline
    Query
    $search
    {
    "text": {
    "query": "baseball",
    "path": "plot"
    }
    }
    $limit
    5
    $project
    {
    "_id": 0,
    "title": 1,
    "plot": 1
    }

Se você habilitou o Auto Preview, o MongoDB Compass exibe os seguintes documentos ao lado da etapa de pipeline do $project:

{
"plot" : "A trio of guys try and make up for missed
opportunities in childhood by forming a three-player
baseball team to compete against standard children
baseball squads.",
"title" : "The Benchwarmers"
}
{
"plot" : "A young boy is bequeathed the ownership of a
professional baseball team.",
"title" : "Little Big League"
}
{
"plot" : "A trained chimpanzee plays third base for a
minor-league baseball team.",
"title" : "Ed"
}
{
"plot" : "The story of the life and career of the famed
baseball player, Lou Gehrig.",
"title" : "The Pride of the Yankees"
}
{
"plot" : "Babe Ruth becomes a baseball legend but is
unheroic to those who know him.",
"title" : "The Babe"
}

Para obter mais informações sobre o estágio do pipeline $search, consulte sua página de referência. Para obter a documentação completa do pipeline de agregação, consulte o Manual do MongoDB Server.

4

$search tem vários operadores para construir diferentes tipos de queries. A query seguinte utiliza o operador composto para combinar vários operadores em uma única query. Tem os seguintes critérios de pesquisa:

  • O campo plot deve conter Hawaii ou Alaska.

  • O campo plot deve conter um número de quatro dígitos, como um ano.

  • O campo genres não pode conter Comedy ou Romance.

  • O campo title não pode conter Beach ou Snow.

Para executar esta query de pesquisa complexa do Atlas Search no MongoDB Compass:

  1. Clique na aba Aggregations.

  2. Clique em Select... e, em seguida, configure cada um dos seguintes estágios do pipeline, selecionando o estágio no menu suspenso e adicionando a consulta para esse estágio. Clique em Add Stage para adicionar estágios adicionais.

    estágio do pipeline
    Query
    $search
    {
    "compound": {
    "must": [ {
    "text": {
    "query": ["Hawaii", "Alaska"],
    "path": "plot"
    },
    },
    {
    "regex": {
    "query": "([0-9]{4})",
    "path": "plot",
    "allowAnalyzedField": true
    }
    } ],
    "mustNot": [ {
    "text": {
    "query": ["Comedy", "Romance"],
    "path": "genres"
    }
    },
    {
    "text": {
    "query": ["Beach", "Snow"],
    "path": "title"
    }
    } ]
    }
    }
    $project
    {
    "title": 1,
    "plot": 1,
    "genres": 1,
    "_id": 0
    }

Se você habilitou o Auto Preview, o MongoDB Compass exibe os seguintes documentos ao lado da etapa de pipeline do $project:

{
"plot" : "A modern aircraft carrier is thrown back in time
to 1941 near Hawaii, just hours before the Japanese attack
on Pearl Harbor.",
"genres" : [ "Action", "Sci-Fi" ],
"title" : "The Final Countdown"
}
{
"plot" : "Follows John McCain's 2008 presidential
campaign, from his selection of Alaska Governor Sarah
Palin as his running mate to their ultimate defeat in the
general election.",
"genres" : [ "Biography", "Drama", "History" ],
"title" : "Game Change"
}
{
"plot" : "A devastating and heartrending take on grizzly
bear activists Timothy Treadwell and Amie Huguenard, who
were killed in October of 2003 while living among
grizzlies in Alaska.",
"genres" : [ "Documentary", "Biography" ],
"title" : "Grizzly Man"
}
{
"plot" : "Truman Korovin is a lonely, sharp-witted cab
driver in Fairbanks, Alaska, 1980. The usual routine of
picking up fares and spending his nights at his favorite
bar, the Boatel, is disrupted ...",
"genres" : [ "Drama" ],
"title" : "Chronic Town"
}
1
  1. Crie um novo diretório chamado simple-query-example e inicialize seu projeto com o comando dotnet new .

    mkdir simple-query-example
    cd simple-query-example
    dotnet new console
  2. Adicione o driver .NET/C# ao seu projeto como uma dependência.

    dotnet add package MongoDB.Driver
  3. Substitua o conteúdo do arquivo Program.cs pelo seguinte código.

    O exemplo de código executa as seguintes tarefas:

    • Importa pacotes e dependências do mongodb .

    • Estabelece uma ligação ao seu cluster Atlas.

    • Pesquisar a palavra baseball no campo plot . Inclui um:

      • Estágio $limit para limitar a saída a 5 resultados

      • Estágio $project para excluir todos os campos, exceto title e plot

    • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class SimpleQuery
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // define and run pipeline
    23 var results = moviesCollection.Aggregate()
    24 .Search(Builders<MovieDocument>.Search.Text(movie => movie.Plot, "baseball"))
    25 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    26 .Include(movie => movie.Plot)
    27 .Include(movie => movie.Title)
    28 .Exclude(movie => movie.Id))
    29 .Limit(5)
    30 .ToList();
    31
    32 // print results
    33 foreach (var movie in results)
    34 {
    35 Console.WriteLine(movie.ToJson());
    36 }
    37 }
    38}
    39
    40[BsonIgnoreExtraElements]
    41public class MovieDocument
    42{
    43 [BsonIgnoreIfDefault]
    44 public ObjectId Id { get; set; }
    45 public string Plot { get; set; }
    46 public string Title { get; set; }
    47}
  4. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  5. Compile e execute o arquivo Program.cs .

    dotnet run simple-query-example.csproj
    {
    "plot" : "A trio of guys try and make up for missed
    opportunities in childhood by forming a three-player
    baseball team to compete against standard children baseball
    squads.",
    "title" : "The Benchwarmers"
    }
    {
    "plot" : "A young boy is bequeathed the ownership of a
    professional baseball team.",
    "title" : "Little Big League"
    }
    {
    "plot" : "A trained chimpanzee plays third base for a
    minor-league baseball team.",
    "title" : "Ed"
    }
    {
    "plot" : "The story of the life and career of the famed
    baseball player, Lou Gehrig.",
    "title" : "The Pride of the Yankees"
    }
    {
    "plot" : "Babe Ruth becomes a baseball legend but is
    unheroic to those who know him.",
    "title" : "The Babe"
    }
2
  1. Crie um novo diretório denominado complex-query-example e inicialize seu projeto com o comando dotnet new.

    mkdir complex-query-example
    cd complex-query-example
    dotnet new console
  2. Adicione o driver .NET/C# ao seu projeto como uma dependência.

    dotnet add package MongoDB.Driver
  3. Substitua o conteúdo do arquivo Program.cs pelo seguinte código.

    $search tem vários operadores para construir diferentes tipos de queries. Este exemplo de código utiliza o operador composto para combinar vários operadores em uma única consulta. Tem os seguintes critérios de pesquisa:

    • O campo plot deve conter Hawaii ou Alaska.

    • O campo plot deve conter um número de quatro dígitos, como um ano.

    • O campo genres não pode conter Comedy ou Romance.

    • O campo title não pode conter Beach ou Snow.

    1using MongoDB.Bson;
    2using MongoDB.Bson.Serialization.Attributes;
    3using MongoDB.Bson.Serialization.Conventions;
    4using MongoDB.Driver;
    5using MongoDB.Driver.Search;
    6
    7public class ComplexQuery
    8{
    9 private const string MongoConnectionString = "<connection-string>";
    10
    11 public static void Main(string[] args)
    12 {
    13 // allow automapping of the camelCase database fields to our MovieDocument
    14 var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
    15 ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
    16
    17 // connect to your Atlas cluster
    18 var mongoClient = new MongoClient(MongoConnectionString);
    19 var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
    20 var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
    21
    22 // declare data for the compound query
    23 string[] terms = { "Hawaii", "Alaska" };
    24 string[] genres = { "Comedy", "Romance" };
    25 string[] titles = { "Beach", "Snow" };
    26
    27 // define and run pipeline
    28 var results = moviesCollection.Aggregate()
    29 .Search(Builders<MovieDocument>.Search.Compound()
    30 .Must(Builders<MovieDocument>.Search.Text(movie => movie.Plot, terms))
    31 .Must(Builders<MovieDocument>.Search.Regex(movie => movie.Plot, "([0-9]{4})", true))
    32 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Genres, genres)))
    33 .MustNot((Builders<MovieDocument>.Search.Text(movie => movie.Title, titles))))
    34 .Project<MovieDocument>(Builders<MovieDocument>.Projection
    35 .Include(movie => movie.Genres)
    36 .Include(movie => movie.Plot)
    37 .Include(movie => movie.Title)
    38 .Exclude(movie => movie.Id))
    39 .ToList();
    40
    41 // print results
    42 foreach (var movie in results)
    43 {
    44 Console.WriteLine(movie.ToJson());
    45 }
    46 }
    47}
    48
    49[BsonIgnoreExtraElements]
    50public class MovieDocument
    51{
    52 [BsonIgnoreIfDefault]
    53 public ObjectId Id { get; set; }
    54 public string[] Genres { get; set; }
    55 public string Plot { get; set; }
    56 public string Title { get; set; }
    57}
  4. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  5. Compile e execute o arquivo Program.cs .

    dotnet run complex-query-example.csproj
    {
    "genres" : ["Action", "Sci-Fi"],
    "plot" : "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.",
    "title" : "The Final Countdown"
    }
    {
    "genres" : ["Biography", "Drama", "History"],
    "plot" : "Follows John McCain's 2008 presidential campaign,
    from his selection of Alaska Governor Sarah Palin as his
    running mate to their ultimate defeat in the general
    election.",
    "title" : "Game Change"
    }
    {
    "genres" : ["Documentary", "Biography"],
    "plot" : "A devastating and heartrending take on grizzly
    bear activists Timothy Treadwell and Amie Huguenard, who
    were killed in October of 2003 while living among grizzlies
    in Alaska.",
    "title" : "Grizzly Man"
    }
    {
    "genres" : ["Drama"],
    "plot" : "Truman Korovin is a lonely, sharp-witted cab
    driver in Fairbanks, Alaska, 1980. The usual routine of
    picking up fares and spending his nights at his favorite
    bar, the Boatel, is disrupted ...",
    "title" : "Chronic Town"
    }
1
  1. Crie um arquivo denominado simple-query.go.

  2. Copie e cole o exemplo de código no arquivo simple-query.go.

    O exemplo de código executa as seguintes tarefas:

    • Importa pacotes e dependências do mongodb .

    • Estabelece uma ligação ao seu cluster Atlas.

    • Procura a palavra baseball no campo plot . Inclui os seguintes estágios:

      • Estágio $limit para limitar a saída a 5 resultados

      • Estágio $project para excluir todos os campos, exceto title e plot

    • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    1package main
    2import (
    3 "context"
    4 "fmt"
    5 "time"
    6
    7 "go.mongodb.org/mongo-driver/bson"
    8 "go.mongodb.org/mongo-driver/mongo"
    9 "go.mongodb.org/mongo-driver/mongo/options"
    10)
    11// define structure of movies collection
    12type MovieCollection struct {
    13 title string `bson:"Title,omitempty"`
    14 plot string `bson:"Plot,omitempty"`
    15}
    16func main() {
    17 var err error
    18 // connect to the Atlas cluster
    19 ctx := context.Background()
    20 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    21 if err != nil {
    22 panic(err)
    23 }
    24 defer client.Disconnect(ctx)
    25 // set namespace
    26 collection := client.Database("sample_mflix").Collection("movies")
    27 // define pipeline
    28 searchStage := bson.D{{"$search", bson.D{{"text", bson.D{{"path", "plot"},{"query", "baseball"}}}}}}
    29 limitStage := bson.D{{"$limit", 5}}
    30 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"_id", 0}}}}
    31 // specify the amount of time the operation can run on the server
    32 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    33 // run pipeline
    34 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, limitStage, projectStage}, opts)
    35 if err != nil {
    36 panic(err)
    37 }
    38 // print results
    39 var results []bson.D
    40 if err = cursor.All(context.TODO(), &results); err != nil {
    41 panic(err)
    42 }
    43 for _, result := range results {
    44 fmt.Println(result)
    45 }
    46}
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Execute o seguinte comando para consultar sua collection:

    go run simple-query.go
    [
    {plot A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.}
    {title The Benchwarmers}
    ]
    [
    {plot A young boy is bequeathed the ownership of a professional baseball team.}
    {title Little Big League}
    ]
    [
    {plot A trained chimpanzee plays third base for a minor-league baseball team.}
    {title Ed}
    ]
    [
    {plot The story of the life and career of the famed baseball player, Lou Gehrig.}
    {title The Pride of the Yankees}
    ]
    [
    {plot Babe Ruth becomes a baseball legend but is unheroic to those who know him.}
    {title The Babe}
    ]
2
  1. Crie um arquivo denominado complex-query.go.

  2. Copie e cole o exemplo de código no arquivo complex-query.go.

    $search tem vários operadores para construir diferentes tipos de queries. Este exemplo de código utiliza o operador composto para combinar vários operadores em uma única consulta. Tem os seguintes critérios de pesquisa:

    • O campo plot deve conter Hawaii ou Alaska.

    • O campo plot deve conter um número de quatro dígitos, como um ano.

    • O campo genres não pode conter Comedy ou Romance.

    • O campo title não pode conter Beach ou Snow.

    1package main
    2import (
    3 "context"
    4 "fmt"
    5 "time"
    6
    7 "go.mongodb.org/mongo-driver/bson"
    8 "go.mongodb.org/mongo-driver/mongo"
    9 "go.mongodb.org/mongo-driver/mongo/options"
    10)
    11// define structure of movies collection
    12type MovieCollection struct {
    13 title string `bson:"Title,omitempty"`
    14 plot []string `bson:"Plot,omitempty"`
    15}
    16func main() {
    17 var err error
    18 // connect to the Atlas cluster
    19 ctx := context.Background()
    20 client, err := mongo.Connect(ctx, options.Client().ApplyURI("<connection-string>"))
    21 if err != nil {
    22 panic(err)
    23 }
    24 defer client.Disconnect(ctx)
    25 // set namespace
    26 collection := client.Database("sample_mflix").Collection("movies")
    27 // define pipeline
    28 searchStage := bson.D{{"$search", bson.M{
    29 "compound": bson.M{
    30 "must": bson.A{
    31 bson.M{
    32 "text": bson.D{
    33 {"path", "plot"},{"query", []string{"Hawaii", "Alaska"}},
    34 },
    35 },
    36 bson.M{
    37 "regex": bson.M{
    38 "path": "plot","query": "([0-9]{4})","allowAnalyzedField": true,
    39 },
    40 },
    41 },
    42 "mustNot": bson.A{
    43 bson.D{
    44 {"text", bson.M{
    45 "path": "genres","query": []string{"Comedy", "Romance"},
    46 }},
    47 {"text", bson.M{
    48 "path": "title","query": []string{"Beach", "Snow"},
    49 }},
    50 },
    51 },
    52 },
    53 }}}
    54 projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"plot", 1}, {"genres", 1}, {"_id", 0}}}}
    55 // specify the amount of time the operation can run on the server
    56 opts := options.Aggregate().SetMaxTime(5 * time.Second)
    57 // run pipeline
    58 cursor, err := collection.Aggregate(ctx, mongo.Pipeline{searchStage, projectStage}, opts)
    59 if err != nil {
    60 panic(err)
    61 }
    62 // print results
    63 var results []bson.D
    64 if err = cursor.All(context.TODO(), &results); err != nil {
    65 panic(err)
    66 }
    67 for _, result := range results {
    68 fmt.Println(result)
    69 }
    70}
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Execute o seguinte comando para consultar sua collection:

    go run complex-query.go
    [
    {plot A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.}
    {genres [Action Sci-Fi]}
    {title The Final Countdown}
    ]
    [
    {plot Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.}
    {genres [Biography Drama History]}
    {title Game Change}
    ]
    [
    {plot A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.}
    {genres [Documentary Biography]}
    {title Grizzly Man}
    ]
    [
    {plot Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...}
    {genres [Drama]}
    {title Chronic Town}
    ]
1
junit
4.11 ou versão superior
mongodb-driver-sync
4.3.0 ou uma versão superior
slf4j-log4j12
1.7.30 ou uma versão superior
2
  1. Crie um arquivo denominado SimpleQuery.java.

  2. Copie e cole o seguinte código no arquivo SimpleQuery.java.

    O exemplo de código executa as seguintes tarefas:

    • Importa pacotes e dependências do mongodb .

    • Estabelece uma ligação ao seu cluster Atlas.

    • Pesquisar a palavra baseball no campo plot . Inclui um:

      • Estágio $limit para limitar a saída a 5 resultados

      • Estágio $project para excluir todos os campos, exceto title e plot

    • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.limit;
    4import static com.mongodb.client.model.Aggregates.project;
    5import static com.mongodb.client.model.Projections.excludeId;
    6import static com.mongodb.client.model.Projections.fields;
    7import static com.mongodb.client.model.Projections.include;
    8import com.mongodb.client.MongoClient;
    9import com.mongodb.client.MongoClients;
    10import com.mongodb.client.MongoCollection;
    11import com.mongodb.client.MongoDatabase;
    12import org.bson.Document;
    13
    14public class SimpleQuery {
    15 public static void main( String[] args ) {
    16 Document agg = new Document("query", "baseball").append("path","plot");
    17
    18 String uri = "<connection-string>";
    19
    20 try (MongoClient mongoClient = MongoClients.create(uri)) {
    21 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    22 MongoCollection<Document> collection = database.getCollection("movies");
    23
    24 collection.aggregate(Arrays.asList(
    25 eq("$search", eq("text", agg)),
    26 limit(5),
    27 project(fields(excludeId(), include("title", "plot"))))
    28 ).forEach(doc -> System.out.println(doc.toJson()));
    29 }
    30 }
    31}
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Compile e execute o arquivo SimpleQuery.java .

    javac SimpleQuery.java
    java SimpleQuery
    {
    "plot": "A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.",
    "title": "The Benchwarmers"
    }
    {
    "plot": "A young boy is bequeathed the ownership of a professional baseball team.",
    "title": "Little Big League"
    }
    {
    "plot": "A trained chimpanzee plays third base for a minor-league baseball team.",
    "title": "Ed"
    }
    {
    "plot": "The story of the life and career of the famed baseball player, Lou Gehrig.",
    "title": "The Pride of the Yankees"
    }
    {
    "plot": "Babe Ruth becomes a baseball legend but is unheroic to those who know him.",
    "title": "The Babe"
    }
3
  1. Crie um arquivo denominado ComplexQuery.java.

  2. Copie e cole o seguinte código no arquivo ComplexQuery.java.

    $search tem vários operadores para construir diferentes tipos de queries. Este exemplo de código utiliza o operador composto para combinar vários operadores em uma única consulta. Tem os seguintes critérios de pesquisa:

    • O campo plot deve conter Hawaii ou Alaska.

    • O campo plot deve conter um número de quatro dígitos, como um ano.

    • O campo genres não pode conter Comedy ou Romance.

    • O campo title não pode conter Beach ou Snow.

    1import java.util.Arrays;
    2import static com.mongodb.client.model.Filters.eq;
    3import static com.mongodb.client.model.Aggregates.project;
    4import static com.mongodb.client.model.Projections.excludeId;
    5import static com.mongodb.client.model.Projections.fields;
    6import static com.mongodb.client.model.Projections.include;
    7import com.mongodb.client.MongoClient;
    8import com.mongodb.client.MongoClients;
    9import com.mongodb.client.MongoCollection;
    10import com.mongodb.client.MongoDatabase;
    11import org.bson.Document;
    12
    13public class ComplexQuery {
    14 public static void main( String[] args ) {
    15 Document agg = new Document("must", Arrays.asList(
    16 new Document("text", new Document("query", Arrays.asList("Hawaii", "Alaska")).append("path", "plot")),
    17 new Document("regex", new Document("query", "([0-9]{4})").append("path", "plot").append("allowAnalyzedField", true))))
    18 .append("mustNot", Arrays.asList(
    19 new Document("text", new Document("query", Arrays.asList("Comedy", "Romance")).append("path", "genres")),
    20 new Document("text", new Document("query", Arrays.asList("Beach", "Snow")).append("path", "title"))));
    21
    22 String uri = "<connection-string>";
    23
    24 try (MongoClient mongoClient = MongoClients.create(uri)) {
    25 MongoDatabase database = mongoClient.getDatabase("sample_mflix");
    26 MongoCollection<Document> collection = database.getCollection("movies");
    27
    28 collection.aggregate(Arrays.asList(
    29 eq("$search", eq("compound", agg)),
    30 project(fields(excludeId(), include("title", "plot", "genres"))))
    31 ).forEach(doc -> System.out.println(doc.toJson()));
    32 }
    33 }
    34}
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Compile e execute o arquivo ComplexQuery.java .

    javac ComplexQuery.java
    java ComplexQuery
    {
    "plot": "A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.",
    "genres": ["Action", "Sci-Fi"],
    "title": "The Final Countdown"
    }
    {
    "plot": "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.",
    "genres": ["Biography", "Drama", "History"],
    "title": "Game Change"
    }
    {
    "plot": "A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.",
    "genres": ["Documentary", "Biography"],
    "title": "Grizzly Man"
    }
    {
    "plot": "Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...",
    "genres": ["Drama"],
    "title": "Chronic Town"
    }
1
mongodb-driver-kotlin-coroutine
4.10.0 ou uma versão superior
2
  1. Crie um arquivo denominado SimpleQuery.kt.

  2. Copie e cole o seguinte código no arquivo SimpleQuery.kt.

    O exemplo de código executa as seguintes tarefas:

    • Importa pacotes e dependências do mongodb .

    • Estabelece uma ligação ao seu cluster Atlas.

    • Pesquisar a palavra baseball no campo plot . Inclui um:

      • Estágio $limit para limitar a saída a 5 resultados

      • Estágio $project para excluir todos os campos, exceto title e plot

    • Imprime os documentos que correspondem à query da instância AggregateFlow.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Filters.eq
    4import com.mongodb.client.model.Projections.*
    5import com.mongodb.kotlin.client.coroutine.MongoClient
    6import kotlinx.coroutines.runBlocking
    7import org.bson.Document
    8
    9fun main() {
    10 // establish connection and set namespace
    11 val uri = "<connection-string>"
    12 val mongoClient = MongoClient.create(uri)
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define query
    18 val agg = Document("query", "baseball").append("path","plot")
    19
    20 // run query and print results
    21 val resultsFlow = collection.aggregate<Document>(
    22 listOf(
    23 eq("\$search", eq("text", agg)),
    24 limit(5),
    25 project(fields(excludeId(), include("title", "plot")))
    26 )
    27 )
    28 resultsFlow.collect { println(it) }
    29 }
    30 mongoClient.close()
    31}
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Execute o arquivo SimpleQuery.kt.

    Ao executar o programa SimpleQuery.kt no seu IDE, ele imprime os seguintes documentos:

    Document{{plot=A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads., title=The Benchwarmers}}
    Document{{plot=A young boy is bequeathed the ownership of a professional baseball team., title=Little Big League}}
    Document{{plot=A trained chimpanzee plays third base for a minor-league baseball team., title=Ed}}
    Document{{plot=Babe Ruth becomes a baseball legend but is unheroic to those who know him., title=The Babe}}
    Document{{plot=The story of the life and career of the famed baseball player, Lou Gehrig., title=The Pride of the Yankees}}
3
  1. Crie um arquivo denominado ComplexQuery.kt.

  2. Copie e cole o seguinte código no arquivo ComplexQuery.kt.

    $search tem vários operadores para construir diferentes tipos de queries. Este exemplo de código utiliza o operador composto para combinar vários operadores em uma única consulta. Tem os seguintes critérios de pesquisa:

    • O campo plot deve conter Hawaii ou Alaska.

    • O campo plot deve conter um número de quatro dígitos, como um ano.

    • O campo genres não pode conter Comedy ou Romance.

    • O campo title não pode conter Beach ou Snow.

    1import com.mongodb.client.model.Aggregates.limit
    2import com.mongodb.client.model.Aggregates.project
    3import com.mongodb.client.model.Filters.eq
    4import com.mongodb.client.model.Projections.*
    5import com.mongodb.kotlin.client.coroutine.MongoClient
    6import kotlinx.coroutines.runBlocking
    7import org.bson.Document
    8
    9fun main() {
    10 // establish connection and set namespace
    11 val uri = "<connection-string>"
    12 val mongoClient = MongoClient.create(uri)
    13 val database = mongoClient.getDatabase("sample_mflix")
    14 val collection = database.getCollection<Document>("movies")
    15
    16 runBlocking {
    17 // define query
    18 val agg = Document(
    19 "must", listOf(
    20 Document("text", Document("query", listOf("Hawaii", "Alaska"))
    21 .append("path", "plot")),
    22 Document(
    23 "regex",
    24 Document("query", "([0-9]{4})")
    25 .append("path", "plot")
    26 .append("allowAnalyzedField", true)
    27 )
    28 )
    29 )
    30 .append(
    31 "mustNot", listOf(
    32 Document("text", Document("query", listOf("Comedy", "Romance"))
    33 .append("path", "genres")),
    34 Document("text", Document("query", listOf("Beach", "Snow"))
    35 .append("path", "title"))
    36 )
    37 )
    38
    39 // run query and print results
    40 val resultsFlow = collection.aggregate<Document>(
    41 listOf(
    42 eq("\$search", eq("compound", agg)),
    43 project(fields(
    44 excludeId(),
    45 include("title", "plot", "genres")
    46 ))
    47 )
    48 )
    49 resultsFlow.collect { println(it) }
    50 }
    51 mongoClient.close()
    52}
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Execute o arquivo ComplexQuery.kt.

    Ao executar o programa ComplexQuery.kt no seu IDE, ele imprime os seguintes documentos:

    Document{{plot=A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor., genres=[Action, Sci-Fi], title=The Final Countdown}}
    Document{{plot=Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election., genres=[Biography, Drama, History], title=Game Change}}
    Document{{plot=A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska., genres=[Documentary, Biography], title=Grizzly Man}}
    Document{{plot=Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ..., genres=[Drama], title=Chronic Town}}
1
  1. Crie um arquivo denominado simple-query.js.

  2. Copie e cole o exemplo de código no arquivo simple-query.js.

    O exemplo de código executa as seguintes tarefas:

    • Importa mongodb, o driver do Node.js da MongoDB.

    • Cria uma instância da classe MongoClient para estabelecer uma conexão com seu cluster do Atlas.

    • Pesquisa a palavra baseball no campo plot. Ele inclui um estágio $limit para limitar a saída a 5 resultados e um estágio $project para excluir todos os campos, exceto title e plot.

    • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 text: {
    8 query: "baseball",
    9 path: "plot",
    10 },
    11 },
    12 },
    13 {
    14 $limit: 5,
    15 },
    16 {
    17 $project: {
    18 _id: 0,
    19 title: 1,
    20 plot: 1,
    21 },
    22 },
    23];
    24
    25MongoClient.connect(
    26 "<connection-string>",
    27 { useNewUrlParser: true, useUnifiedTopology: true },
    28 async function (connectErr, client) {
    29 assert.equal(null, connectErr);
    30 const coll = client.db("sample_mflix").collection("movies");
    31 let cursor = await coll.aggregate(agg);
    32 await cursor.forEach((doc) => console.log(doc));
    33 client.close();
    34 }
    35);
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Execute o seguinte comando para consultar sua collection:

    node simple-query.js
    {
    plot: 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.',
    title: 'The Benchwarmers'
    }
    {
    plot: 'A young boy is bequeathed the ownership of a professional baseball team.',
    title: 'Little Big League'
    }
    {
    plot: 'A trained chimpanzee plays third base for a minor-league baseball team.',
    title: 'Ed'
    }
    {
    plot: 'The story of the life and career of the famed baseball player, Lou Gehrig.',
    title: 'The Pride of the Yankees'
    }
    {
    plot: 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.',
    title: 'The Babe'
    }
2
  1. Crie um arquivo denominado complex-query.js.

  2. Copie e cole o exemplo de código no arquivo complex-query.js.

    $search tem vários operadores para construir diferentes tipos de queries. O exemplo de código utiliza o operador composto para combinar vários operadores em uma única consulta. Tem os seguintes critérios de pesquisa:

    • O campo plot deve conter Hawaii ou Alaska.

    • O campo plot deve conter um número de quatro dígitos, como um ano.

    • O campo genres não pode conter Comedy ou Romance.

    • O campo title não pode conter Beach ou Snow.

    1const MongoClient = require("mongodb").MongoClient;
    2const assert = require("assert");
    3
    4const agg = [
    5 {
    6 $search: {
    7 compound: {
    8 must: [
    9 {
    10 text: {
    11 query: ["Hawaii", "Alaska"],
    12 path: "plot",
    13 },
    14 },
    15 {
    16 regex: {
    17 query: "([0-9]{4})",
    18 path: "plot",
    19 allowAnalyzedField: true,
    20 },
    21 },
    22 ],
    23 mustNot: [
    24 {
    25 text: {
    26 query: ["Comedy", "Romance"],
    27 path: "genres",
    28 },
    29 },
    30 {
    31 text: {
    32 query: ["Beach", "Snow"],
    33 path: "title",
    34 },
    35 },
    36 ],
    37 },
    38 },
    39 },
    40 {
    41 $project: {
    42 title: 1,
    43 plot: 1,
    44 genres: 1,
    45 _id: 0,
    46 },
    47 },
    48];
    49
    50MongoClient.connect(
    51 "<connection-string>",
    52 { useNewUrlParser: true, useUnifiedTopology: true },
    53 async function (connectErr, client) {
    54 assert.equal(null, connectErr);
    55 const coll = client.db("sample_mflix").collection("movies");
    56 let cursor = await coll.aggregate(agg);
    57 await cursor.forEach((doc) => console.log(doc));
    58 client.close();
    59 }
    60);
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados.

  4. Execute o seguinte comando para consultar sua collection:

    node complex-query.js
    {
    plot: 'A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.',
    genres: [ 'Action', 'Sci-Fi' ],
    title: 'The Final Countdown'
    }
    {
    plot: "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.",
    genres: [ 'Biography', 'Drama', 'History' ],
    title: 'Game Change'
    }
    {
    plot: 'A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.',
    genres: [ 'Documentary', 'Biography' ],
    title: 'Grizzly Man'
    }
    {
    plot: 'Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...',
    genres: [ 'Drama' ],
    title: 'Chronic Town'
    }
1
  1. Crie um arquivo denominado simple-query.py.

  2. Copie e cole o exemplo de código no arquivo simple-query.py.

    O seguinte exemplo de código:

    • Importa pymongo, o driver Python do MongoDB e o módulo dns , que é necessário para conectar pymongo a Atlas usando uma connection string de lista de sementes de DNS .

    • Cria uma instância da classe MongoClient para estabelecer uma conexão com seu cluster do Atlas.

    • Pesquisa a palavra baseball no campo plot. Ele inclui um estágio $limit para limitar a saída a 5 resultados e um estágio $project para excluir todos os campos, exceto title e plot.

    • Itera sobre o cursor para imprimir os documentos que correspondem à consulta.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'index': 'default',
    9 'text': {
    10 'query': 'baseball',
    11 'path': 'plot'
    12 }
    13 }
    14 }, {
    15 '$limit': 5
    16 }, {
    17 '$project': {
    18 '_id': 0,
    19 'title': 1,
    20 'plot': 1
    21 }
    22 }
    23])
    24
    25for i in result:
    26 print(i)
  3. Antes de executar o exemplo, substitua <connection-string> por sua cadeia de conexão do Atlas. Certifique-se de que sua cadeia de conexão inclui as credenciais do usuário do banco de dados. Para saber mais, consulte Conectar via Drivers.

  4. Execute o seguinte comando para consultar sua collection:

    python simple-query.py
    {'plot': 'A trio of guys try and make up for missed opportunities in childhood by forming a three-player baseball team to compete against standard children baseball squads.', 'title': 'The Benchwarmers'}
    {'plot': 'A young boy is bequeathed the ownership of a professional baseball team.', 'title': 'Little Big League'}
    {'plot': 'A trained chimpanzee plays third base for a minor-league baseball team.', 'title': 'Ed'}
    {'plot': 'The story of the life and career of the famed baseball player, Lou Gehrig.', 'title': 'The Pride of the Yankees'}
    {'plot': 'Babe Ruth becomes a baseball legend but is unheroic to those who know him.', 'title': 'The Babe'}
2
  1. Crie um arquivo denominado complex-query.py.

  2. Copie e cole o exemplo de código no arquivo complex-query.py.

    $search tem vários operadores para construir diferentes tipos de queries. A query seguinte utiliza o operador composto para combinar vários operadores em uma única query. Tem os seguintes critérios de pesquisa:

    • O campo plot deve conter Hawaii ou Alaska.

    • O campo plot deve conter um número de quatro dígitos, como um ano.

    • O campo genres não pode conter Comedy ou Romance.

    • O campo title não pode conter Beach ou Snow.

    1import pymongo
    2import dns
    3
    4client = pymongo.MongoClient('<connection-string>')
    5result = client['sample_mflix']['movies'].aggregate([
    6 {
    7 '$search': {
    8 'compound': {
    9 'must': [
    10 {
    11 'text': {
    12 'query': [
    13 'Hawaii', 'Alaska'
    14 ],
    15 'path': 'plot'
    16 }
    17 }, {
    18 'regex': {
    19 'query': '([0-9]{4})',
    20 'path': 'plot',
    21 'allowAnalyzedField': True
    22 }
    23 }
    24 ],
    25 'mustNot': [
    26 {
    27 'text': {
    28 'query': [
    29 'Comedy', 'Romance'
    30 ],
    31 'path': 'genres'
    32 }
    33 }, {
    34 'text': {
    35 'query': [
    36 'Beach', 'Snow'
    37 ],
    38 'path': 'title'
    39 }
    40 }
    41 ]
    42 }
    43 }
    44 }, {
    45 '$project': {
    46 'title': 1,
    47 'plot': 1,
    48 'genres': 1,
    49 '_id': 0
    50 }
    51 }
    52])
    53
    54for i in result:
    55 print(i)
  3. Execute o seguinte comando para consultar sua collection:

    python complex-query.py
    {'plot': 'A modern aircraft carrier is thrown back in time to 1941 near Hawaii, just hours before the Japanese attack on Pearl Harbor.', 'genres': ['Action', 'Sci-Fi'], 'title': 'The Final Countdown'}
    {'plot': "Follows John McCain's 2008 presidential campaign, from his selection of Alaska Governor Sarah Palin as his running mate to their ultimate defeat in the general election.", 'genres': ['Biography', 'Drama', 'History'], 'title': 'Game Change'}
    {'plot': 'A devastating and heartrending take on grizzly bear activists Timothy Treadwell and Amie Huguenard, who were killed in October of 2003 while living among grizzlies in Alaska.', 'genres': ['Documentary', 'Biography'], 'title': 'Grizzly Man'}
    {'plot': 'Truman Korovin is a lonely, sharp-witted cab driver in Fairbanks, Alaska, 1980. The usual routine of picking up fares and spending his nights at his favorite bar, the Boatel, is disrupted ...', 'genres': ['Drama'], 'title': 'Chronic Town'}

Agora que você executou algumas consultas, revise a documentação do Atlas Search para saber mais sobre os diferentes operadores e outras consultas que você pode executar. Mais exemplos de consultas estão disponíveis em toda a documentação do Atlas Search.

Você prefere aprender assistindo?

Acompanhe este tutorial em vídeo passo a passo que demonstra como criar queries do Atlas Search para um aplicativo de demonstração do Restaurant Finder, que também está disponível em http://www.atlassearchrestaurants.com.

Duração: 20 Minutos

Voltar

1: Criar um Índice de Pesquisa

Próximo

Tutoriais