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

curinga

Nesta página

  • Definição
  • Sintaxe
  • Opções
  • Comportamento
  • Exemplos
wildcard

O operador wildcard habilita queries que utilizam caracteres especiais na string de pesquisa que podem corresponder a qualquer caractere.

Personagem
Descrição
?
Corresponde a qualquer caractere único.
*
Corresponde a 0 ou mais caracteres.
\
Personagem de fuga.

wildcard é um operador de nível de termo, o que significa que o campo query não é analisado. Os operadores de nível de termo funcionam bem com oAnalisador de Palavras-chave , porque o campo query é tratado como um único termo, com caracteres especiais incluídos. Para obter um exemplo de query em um campo query analisado em comparação com um campo query não analisado, consulte oexemplo de campo analisado .

wildcard tem a seguinte sintaxe:

{
$search: {
"index": <index name>, // optional, defaults to "default"
"wildcard": {
"query": "<search-string>",
"path": "<field-to-search>",
"allowAnalyzedField": <boolean>,
"score": <options>
}
}
}

wildcard usa os seguintes termos para construir uma consulta:

Campo
Tipo
Descrição
necessidade
default
query
cadeia de caracteres ou matriz de cadeias de caracteres
String ou strings para pesquisar.
sim
path
cadeia de caracteres ou matriz de cadeias de caracteres
Campo ou campos indexados a serem pesquisados. Você também pode especificar um caminho curinga para pesquisar. Consulte construção de caminho para ter mais informações.
sim
allowAnalyzedField
booleano
Deve ser definido para true se a query for executada em um campo analisado.
não
false
score
objeto

Modifique a score atribuída aos resultados dos procurar correspondentes. As opções são:

  • 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 usando a expressão fornecida.

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

não

wildcard é um operador de nível de termo, o que significa que o campo query não é analisado. É possível utilizar o operador wildcard para executar pesquisas em um campo analisado durante a indexação definindo a opção allowAnalyzedField para true, mas resultados refletirá que o texto da query não foi analisado.

Exemplo

Suponha que um campo foo bar baz seja indexado com o analisador padrão. O Atlas Search analisa e indexa o campo como foo, bar e baz. Pesquisar foo bar* neste campo não encontra nada, porque o operador curinga trata foo bar* como um único termo de pesquisa com um curinga no final. Em outras palavras, o Atlas Search pesquisa no campo qualquer termo que comece com foo bar, mas não encontra nada, porque não existe nenhum termo.

Exemplo

A pesquisa de *Star Trek* em um campo indexado com o analisador keyword encontra todos os documentos nos quais o campo contém a string Star Trek em qualquer contexto. A pesquisa de *Star Trek* em um campo indexado com o analisador padrão não encontra nada, pois há um espaço entre Star e Trek, e o índice não contém espaços.

Ao usar o caractere de escape em mongosh ou com um driver, é necessário usar uma barra invertida dupla antes do caractere a ser escapado.

Exemplo

Para criar uma expressão curinga que procure qualquer string que contenha um asterisco literal em um aggregation pipeline, use a seguinte expressão:

"*\\**"

O primeiro e o último asteriscos funcionam como curingas que correspondem a qualquer caractere, e o \\* corresponde a um asterisco literal.

Observação

Use a seguinte expressão para escapar de uma barra invertida literal:

"*\\\*"

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


Os exemplos a seguir usam a collection movies no banco de dados sample_mflix com uma definição de índice personalizada que usa o analisador de palavras-chave. Se você tiver o sample dataset em seu cluster, poderá criar um Atlas Search index na movies e executar as querys de exemplo em seu cluster.

Dica

Se você já carregou o conjunto de dados de amostra, siga o tutorial Iniciar com Atlas Search para criar uma definição de índice e executar queries de Atlas Search.

Para visualizar e editar a sintaxe de query no Search Tester:

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
  1. Clique no botão Query à direita do índice para consultar.

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

Execute o seguinte comando no prompt mongosh para usar o banco de dados sample_mflix:

use sample_mflix

A seguinte definição de índice indexa o campo title na coleção movies com o analisador de palavra-chave:

1{
2 "mappings": {
3 "fields": {
4 "title": {
5 "analyzer": "lucene.keyword",
6 "type": "string"
7 }
8 }
9 }
10}

O exemplo a seguir procurar em todos os campos title os títulos de filmes que começam com Green D, seguidos de qualquer número de outros caracteres.

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

[
{
$search: {
"wildcard": {
"path": "title",
"query": "Green D*"
}
}
}
]
db.movies.aggregate([
{
"$search": {
"wildcard": {
"path": "title",
"query": "Green D*"
}
}
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])

Na guia Aggregations da coleção movies , configure cada um dos seguintes estágios de pipeline selecionando o estágio na lista suspensa e adicionando a consulta para esse estágio. Clique em Add Stage para adicionar estágios adicionais.

estágio do pipeline
Query
$search
{
"wildcard": {
"query": "Green D*",
"path": "title"
}
}
$project
{
"_id": 0,
"title": 1,
}
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class WildcardSingleCharacter
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Green D*"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}
package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"wildcard", bson.D{{"path", "title"}, {"query", "Green D*"}}}}}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class WildcardSingleCharacter {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("query", "Green D*").append("path", "title");
// run pipeline and print results
collection.aggregate(Arrays.asList(
eq("$search", eq("wildcard", agg)),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document("query", "Green D*").append("path", "title")
val resultsFlow = collection.aggregate<Document>(
listOf(
eq("\$search", eq("wildcard", agg)),
project(fields(
excludeId(),
include("title")
))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}
const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {wildcard: {query: "Green D*", path: "title"}}},
{$project: {_id: 0, title: 1}},
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);
import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"wildcard": {"query": "Green D*", "path": "title"}}},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)

A query acima retorna os seguintes resultados:

SCORE: 1 _id: "573a1393f29313caabcddaf5"
plot: "Sophie loved Edmund, but he left town when her parents forced her to m…"
genres: Array
runtime: 141
SCORE: 1 _id: "573a13a2f29313caabd0a4e4"
plot: "The story of some Vietnamese refugees as they first arrive at Camp Pen…"
genres: Array
runtime: 115

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.

{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
[{title Green Dolphin Street}]
[{title Green Dragon}]
{"title": "Green Dolphin Street"}
{"title": "Green Dragon"}
Document{{title=Green Dolphin Street}}
Document{{title=Green Dragon}}
{ title: 'Green Dolphin Street' }
{ title: 'Green Dragon' }
{'title': 'Green Dolphin Street'}
{'title': 'Green Dragon'}

O exemplo a seguir pesquisa todos os campos title em busca de títulos de filmes que começam com a string Wom?n (onde ? pode ser qualquer caractere único), seguido por um espaço e, em seguida, qualquer número de caracteres adicionais.

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

[
{
$search: {
"wildcard": {
"path": "title",
"query": "Wom?n *"
}
}
}
]

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

db.movies.aggregate([
{
"$search": {
"wildcard": {
"path": "title",
"query": "Wom?n *"
}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

Na guia Aggregations da coleção movies , configure cada um dos seguintes estágios de pipeline selecionando o estágio na lista suspensa e adicionando a consulta para esse estágio. Clique em Add Stage para adicionar estágios adicionais.

estágio do pipeline
Query
$search
{
"wildcard": {
"query": "Wom?n *",
"path": "title"
}
}
$limit
5
$project
{
"_id": 0,
"title": 1,
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class WildcardMultipleCharacter
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "Wom?n *"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(5)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"wildcard", bson.D{{"path", "title"}, {"query", "Wom?n *"}}}}}}
limitStage := bson.D{{"$limit", 5}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class WildcardMultiCharacter {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespsace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("query", "Wom?n *").append("path", "title");
// run pipeline and print results
collection.aggregate(Arrays.asList(
eq("$search", eq("wildcard", agg)),
limit(5),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document("query", "Wom?n *").append("path", "title")
val resultsFlow = collection.aggregate<Document>(
listOf(
eq("\$search", eq("wildcard", agg)),
limit(5),
project(fields(
excludeId(),
include("title")
))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {wildcard: {query: "Wom?n *", path: "title"}}},
{$limit: 5},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"wildcard": {"query": "Wom?n *", "path": "title"}}},
{"$limit": 5},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)

A query acima retorna os seguintes resultados:

SCORE: 1 _id: "573a1393f29313caabcdcbdd"
plot: "Rival reporters Sam and Tess fall in love and get married, only to fin…"
genres: Array
runtime: 114
SCORE: 1 _id: "573a1394f29313caabce08c6"
plot: "A married, middle-aged woman is shocked to discover that her husband, …"
genres: Array
runtime: 93
SCORE: 1 _id: "573a1395f29313caabce254c"
plot: "An entomologist searching for insects by the seaside is trapped by loc…"
genres: Array
runtime: 123
SCORE: 1 _id: "573a1396f29313caabce42e5"
plot: "The battle of the sexes and relationships among the elite of Britian's…"
genres: Array
runtime: 131
SCORE: 1 _id: "573a1398f29313caabceb06d"
fullplot: "A woman's lover leaves her, and she tries to contact him to find out w…"
imdb: Object
year: 1988
SCORE: 1 _id: "573a139df29313caabcf9c83"
plot: "A new woman comes between a widower and his adult son."
genres: Array
runtime: 110
SCORE: 1 _id: "573a13a0f29313caabd050bf"
fullplot: "Isabella is a great cook, making her husband's restaurant in Bahia, Br…"
imdb: Object
year: 2000
SCORE: 1 _id: "573a13aaf29313caabd22c05"
countries: Array
genres: Array
runtime: 115
SCORE: 1 _id: "573a13aef29313caabd2d899"
countries: Array
genres: Array
runtime: 72
SCORE: 1 _id: "573a13aff29313caabd32566"
fullplot: "An adaptation of Bishop T.D. Jakes' self-help novel, chronciling a wom…"
imdb: Object
year: 2004

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.

{ "title" : "Woman of the Year" }
{ "title" : "Woman in a Dressing Gown" }
{ "title" : "Woman in the Dunes" }
{ "title" : "Women in Love" }
{ "title" : "Women on the Verge of a Nervous Breakdown" }
{ "title" : "Woman of the Year" }
{ "title" : "Woman in a Dressing Gown" }
{ "title" : "Woman in the Dunes" }
{ "title" : "Women in Love" }
{ "title" : "Women on the Verge of a Nervous Breakdown" }
{ "title" : "Woman of the Year" }
{ "title" : "Woman in a Dressing Gown" }
{ "title" : "Woman in the Dunes" }
{ "title" : "Women in Love" }
{ "title" : "Women on the Verge of a Nervous Breakdown" }
[{title Woman of the Year}]
[{title Woman in a Dressing Gown}]
[{title Woman in the Dunes}]
[{title Women in Love}]
[{title Women on the Verge of a Nervous Breakdown}]
{"title": "Woman of the Year"}
{"title": "Woman in a Dressing Gown"}
{"title": "Woman in the Dunes"}
{"title": "Women in Love"}
{"title": "Women on the Verge of a Nervous Breakdown"}
Document{{title=Woman in the Meadow}}
Document{{title=Woman on the Beach}}
Document{{title=Woman in Love}}
Document{{title=Woman of the Year}}
Document{{title=Woman in a Dressing Gown}}
{ title: 'Woman of the Year' }
{ title: 'Woman in a Dressing Gown' }
{ title: 'Woman in the Dunes' }
{ title: 'Women in Love' }
{ title: 'Women on the Verge of a Nervous Breakdown' }
{'title': 'Woman of the Year'}
{'title': 'Woman in a Dressing Gown'}
{'title': 'Woman in the Dunes'}
{'title': 'Women in Love'}
{'title': 'Women on the Verge of a Nervous Breakdown'}

O exemplo a seguir procura documentos em que o campo title termina com um ponto de interrogação.

Observação

O exemplo a seguir destina-se a ser executado em mongosh. Para obter mais informações sobre como usar os caracteres de escape com um driver, consulte Comportamento dos caracteres de escape.

O caractere * no campo query corresponde a quaisquer caracteres, e a string \\? corresponde a um ponto de interrogação literal.

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

[
{
$search: {
"wildcard": {
"path": "title",
"query": "*\\?"
}
}
}
]

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

db.movies.aggregate([
{
"$search": {
"wildcard": {
"path": "title",
"query": "*\\?"
}
}
},
{
"$limit": 5
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

Na guia Aggregations da coleção movies , configure cada um dos seguintes estágios de pipeline selecionando o estágio na lista suspensa e adicionando a consulta para esse estágio. Clique em Add Stage para adicionar estágios adicionais.

estágio do pipeline
Query
$search
{
"wildcard": {
"query": "*\\?",
"path": "title"
}
}
$limit
5
$project
{
"_id": 0,
"title": 1,
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using MongoDB.Driver.Search;
public class WildcardEscapeCharacter
{
private const string MongoConnectionString = "<connection-string>";
public static void Main(string[] args)
{
// allow automapping of the camelCase database fields to our MovieDocument
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCase", camelCaseConvention, type => true);
// connect to your Atlas cluster
var mongoClient = new MongoClient(MongoConnectionString);
var mflixDatabase = mongoClient.GetDatabase("sample_mflix");
var moviesCollection = mflixDatabase.GetCollection<MovieDocument>("movies");
// define and run pipeline
var results = moviesCollection.Aggregate()
.Search(Builders<MovieDocument>.Search.Wildcard(movie => movie.Title, "*\\?"))
.Project<MovieDocument>(Builders<MovieDocument>.Projection
.Include(movie => movie.Title)
.Exclude(movie => movie.Id))
.Limit(5)
.ToList();
// print results
foreach (var movie in results)
{
Console.WriteLine(movie.ToJson());
}
}
}
[BsonIgnoreExtraElements]
public class MovieDocument
{
[BsonIgnoreIfDefault]
public ObjectId Id { get; set; }
public string Title { get; set; }
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

package main
import (
"context"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// connect to your Atlas cluster
client, err := mongo.Connect(context.TODO(), options.Client().ApplyURI("<connection-string>"))
if err != nil {
panic(err)
}
defer client.Disconnect(context.TODO())
// set namespace
collection := client.Database("sample_mflix").Collection("movies")
// define pipeline stages
searchStage := bson.D{{"$search", bson.D{{"wildcard", bson.D{{"path", "title"}, {"query", "*\\?"}}}}}}
limitStage := bson.D{{"$limit", 5}}
projectStage := bson.D{{"$project", bson.D{{"title", 1}, {"_id", 0}}}}
// run pipeline
cursor, err := collection.Aggregate(context.TODO(), mongo.Pipeline{searchStage, limitStage, projectStage})
if err != nil {
panic(err)
}
// print results
var results []bson.D
if err = cursor.All(context.TODO(), &results); err != nil {
panic(err)
}
for _, result := range results {
fmt.Println(result)
}
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Aggregates.limit;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Projections.fields;
import static com.mongodb.client.model.Projections.include;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import java.util.Arrays;
public class WildcardEscapeCharacter {
public static void main(String[] args) {
// connect to your Atlas cluster
String uri = "<connection-string>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
// set namespace
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
// define pipeline
Document agg = new Document("query", "*\\?").append("path", "title");
// run pipeline and print results
collection.aggregate(Arrays.asList(
eq("$search", eq("wildcard", agg)),
limit(5),
project(fields(excludeId(), include("title"))))).forEach(doc -> System.out.println(doc.toJson()));
}
}
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

import com.mongodb.client.model.Aggregates.limit
import com.mongodb.client.model.Aggregates.project
import com.mongodb.client.model.Filters.eq
import com.mongodb.client.model.Projections.*
import com.mongodb.kotlin.client.coroutine.MongoClient
import kotlinx.coroutines.runBlocking
import org.bson.Document
fun main() {
val uri = "<connection-string>"
val mongoClient = MongoClient.create(uri)
val database = mongoClient.getDatabase("sample_mflix")
val collection = database.getCollection<Document>("movies")
runBlocking {
val agg = Document("query", "*\\?").append("path", "title")
val resultsFlow = collection.aggregate<Document>(
listOf(
eq("\$search", eq("wildcard", agg)),
limit(5),
project(fields(
excludeId(),
include("title")
))
)
)
resultsFlow.collect { println(it) }
}
mongoClient.close()
}

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

const { MongoClient } = require("mongodb");
// connect to your Atlas cluster
const uri =
"<connection-string>";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
// set namespace
const database = client.db("sample_mflix");
const coll = database.collection("movies");
// define pipeline
const agg = [
{$search: {wildcard: {query: "*\\?", path: "title"}}},
{$limit: 5},
{$project: {_id: 0,title: 1}}
];
// run pipeline
const result = await coll.aggregate(agg);
// print results
await result.forEach((doc) => console.log(doc));
} finally {
await client.close();
}
}
run().catch(console.dir);

O estágio $limit limita os resultados a cinco documentos, enquanto o estágio $project limita os resultados somente ao campo title.

import pymongo
# connect to your Atlas cluster
client = pymongo.MongoClient('<connection-string>')
# define pipeline
pipeline = [
{"$search": {"wildcard": {"query": "*\\?", "path": "title"}}},
{"$limit": 5},
{"$project": {"_id": 0, "title": 1}},
]
# run pipeline
result = client["sample_mflix"]["movies"].aggregate(pipeline)
# print results
for i in result:
print(i)

A query acima retorna os seguintes resultados:

SCORE: 1 _id: "573a1390f29313caabcd5ea4"
plot: "A District Attorney's outspoken stand on abortion gets him in trouble …"
genres: Array
runtime: 62
SCORE: 1 _id: "573a1392f29313caabcdab4a"
plot: "Robin is crooning to a Mae West-like Jenny Wren when he is shot with a…"
genres: Array
runtime: 8
SCORE: 1 _id: "573a1394f29313caabce08ab"
plot: "Elmer Fudd is again hunting rabbits - only this time it's an opera. Wa…"
genres: Array
runtime: 7
SCORE: 1 _id: "573a1394f29313caabce08c8"
plot: "To save his career, an ad man wants a sex symbol to endorse a lipstick…"
genres: Array
runtime: 93
SCORE: 1 _id: "573a1395f29313caabce1555"
plot: "In order to get back into the good graces with his wife with whom he h…"
genres: Array
runtime: 115
SCORE: 1 _id: "573a1395f29313caabce1dce"
plot: "A former child star torments her crippled sister in a decaying Hollywo…"
genres: Array
runtime: 134
SCORE: 1 _id: "573a1395f29313caabce2422"
plot: "Roger Willoughby is considered to be a leading expert on sports fishin…"
genres: Array
runtime: 120
SCORE: 1 _id: "573a1395f29313caabce2d63"
plot: "The true story of the departure of the German occupiers from Paris in …"
genres: Array
runtime: 173
SCORE: 1 _id: "573a1395f29313caabce2db5"
plot: "In this excoriating satire of the fashion industry, Polly Maggoo is a …"
genres: Array
runtime: 101
SCORE: 1 _id: "573a1395f29313caabce2ecc"
plot: "A bitter aging couple with the help of alcohol, use a young couple to …"
genres: Array
runtime: 131

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.

{ "title" : "Where Are My Children?" }
{ "title" : "Who Killed Cock Robin?" }
{ "title" : "What's Opera, Doc?" }
{ "title" : "Will Success Spoil Rock Hunter?" }
{ "title" : "Who Was That Lady?" }
{ "title" : "Where Are My Children?" }
{ "title" : "Who Killed Cock Robin?" }
{ "title" : "What's Opera, Doc?" }
{ "title" : "Will Success Spoil Rock Hunter?" }
{ "title" : "Who Was That Lady?" }
{ "title" : "Where Are My Children?" }
{ "title" : "Who Killed Cock Robin?" }
{ "title" : "What's Opera, Doc?" }
{ "title" : "Will Success Spoil Rock Hunter?" }
{ "title" : "Who Was That Lady?" }
[{title Where Are My Children?}]
[{title Who Killed Cock Robin?}]
[{title What's Opera, Doc?}]
[{title Will Success Spoil Rock Hunter?}]
[{title Who Was That Lady?}]
{"title": "Where Are My Children?"}
{"title": "Who Killed Cock Robin?"}
{"title": "What's Opera, Doc?"}
{"title": "Will Success Spoil Rock Hunter?"}
{"title": "Who Was That Lady?"}
Document{{title=Who Are You, Polly Magoo?}}
Document{{title=Where Were You When the Lights Went Out?}}
Document{{title=Why Does Herr R. Run Amok?}}
Document{{title=What's Up, Doc?}}
Document{{title=Who Is Killing the Great Chefs of Europe?}}
{ title: 'Where Are My Children?' }
{ title: 'Who Killed Cock Robin?' }
{ title: "What's Opera, Doc?" }
{ title: 'Will Success Spoil Rock Hunter?' }
{ title: 'Who Was That Lady?' }
{'title': 'Where Are My Children?'}
{'title': 'Who Killed Cock Robin?'}
{'title': "What's Opera, Doc?"}
{'title': 'Will Success Spoil Rock Hunter?'}
{'title': 'Who Was That Lady?'}

Voltar

texto

Próximo

3. Construir um caminho de consulta