> For the complete MongoDB documentation index, see www.mongodb.com/docs/llms.txt

<!--
Tab options on this page. Append to the .md URL to filter:
  ?tabs=<id,...>   select specific tabs (e.g. ?tabs=nodejs,shell)
  ?allTabs=true    include every tab
  (no param)       default: one tab per tabset

Available tabs:
  other tabs: fts-vs, data-explorer
-->

# `wildcard` Operator

## Definition

The `wildcard` operator enables queries which use special characters in the search string that can match any character.

| Character | Description |
| --- | --- |
| `?` | Matches any single character. |
| `*` | Matches 0 or more characters. |
| `\` | Escape character. |

`wildcard` is a term-level operator, meaning that the `query` field is not analyzed. Term-level operators work well with the [Keyword Analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer), because the `query` field is treated as a single term, with special characters included. For an example of querying against an analyzed `query` field, see the [analyzed field example.](https://www.mongodb.com/docs/search/query/operators-collectors/wildcard.md#std-label-analyzed-example)

## Syntax

`wildcard` has the following syntax:

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

## Options

`wildcard` uses the following terms to construct a query:

| Field | Type | Description | Necessity | Default |
| --- | --- | --- | --- | --- |
| `query` | string or array of strings | String or strings to search for. | yes | |
| `path` | string or array of strings | Indexed field or fields to search. You can also specify a wildcard path to search. | yes | |
| `allowAnalyzedField` | boolean | Set to `true` if you run your query against a field indexed with a tokenizing analyzer. This avoids the field's analyzer from splitting the indexed value into many terms. Fields indexed with the [Keyword Analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) don't require this option. | no | `false` |
| `score` | object | Modify the [score](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref) assigned to matching search term results. Options are: `boost`: multiply the result score by the given number.; `constant`: replace the result score with the given number.; `function`: replace the result score using the given expression. For information on using `score` in your query, see [Score the Documents in the Results.](https://www.mongodb.com/docs/search/query/score/overview.md#std-label-scoring-ref) | no | |

## Behavior

`wildcard` is a term-level operator, meaning that the `query` field isn't analyzed. Use the `wildcard` operator on fields indexed with tokenizing analyzers by setting `allowAnalyzedField` to `true`. Fields indexed with the [Keyword Analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) already treat the field value as a single term, so `allowAnalyzedField: true` isn't required.

If you use `wildcard` with `allowAnalyzedField: true`, MongoDB Search applies character filters and token filters based on the specified analyzer or custom analyzer for the field. MongoDB Search skips the tokenization and the output is always a single token.

The following examples show how the `wildcard` operator behaves when performing a search on analyzed fields:

**Example:**

### Standard Analyzer

Suppose that a field `foo bar baz` is indexed with the [standard analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer). MongoDB Search analyzes and indexes the field as  `foo`, `bar` and `baz`. Searching for `foo bar*` on this field finds nothing, because the wildcard operator treats `foo bar*` as a single search term with a wildcard at the end. In other words, MongoDB Search searches the field for any term that begins with `foo bar` but finds nothing, because no term exists.

**Example:**

### Keyword Analyzer

Searching for `*Star Trek*` on a field indexed with the [keyword analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer) finds all documents in which the field contains the string `Star Trek` in any context. Searching for `*Star
    Trek*` on a field indexed with the [standard analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/standard.md#std-label-ref-standard-analyzer) finds nothing, because there is a space between `Star` and `Trek`, and the index contains no spaces.

### Escape Character Behavior

When using the escape character in [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) or with a [driver](https://www.mongodb.com/docs/drivers/), you must use a double backslash before the character to be escaped.

**Example:**

To create a wildcard expression which searches for any string containing a literal asterisk in an aggregation pipeline, use the following expression:

```none
"*\\**"
```

The first and last asterisks act as wildcards which match any characters, and the `\\*` matches a literal asterisk.

Use the following expression to escape a literal backslash:

```none
"*\\\*"
```

## Examples

The following examples use the `movies` collection in the `sample_mflix` database with a custom index definition that uses the [keyword analyzer](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer). If you have the [sample dataset](https://www.mongodb.com/docs/manual/sample-data.md#std-label-available-sample-datasets) on your cluster, you can create a MongoDB Search index on the `movies` collection and run the example queries on your cluster.

To view and edit query syntax in the Search Tester:

1. In Atlas, go to the Search & Vector Search page for your cluster.

   You can go the MongoDB Search page from the Search & Vector Search option, or the Data Explorer.

   ### Search & Vector Search

   If it's not already displayed, select the organization that contains your project from the  Organizations menu in the navigation bar.

   If it's not already displayed, select your project from the Projects menu in the navigation bar.

   In the sidebar, click Search & Vector Search under the Database heading.

   - If you have no clusters, click Create cluster to create one. To learn more, see [Create an Atlas Infinite or Atlas Core Cluster.](https://www.mongodb.com/docs/atlas/tutorial/create-new-cluster.md#std-label-create-new-cluster)

   - If your project has multiple clusters, select the cluster you want to use from the Select cluster dropdown, then click Go to Search.

   The [Search & Vector Search](https://cloud.mongodb.com/go?l=https%3A%2F%2Fcloud.mongodb.com%2Fv2%2F%3Cproject%3E%23%2Fclusters%2FatlasSearch%2F%3Ccluster%3E) page displays.

2. View and edit the query syntax.

   Click the Query button to the right of the index to query.

   Click Edit Query to view a default query syntax sample in JSON (Javascript Object Notation) format.

To learn how to run the following queries in the Atlas UI, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

Run the following command at [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh) prompt to use the `sample_mflix` database:

```shell
use sample_mflix
```

To learn how to run the following queries in the [`mongosh`](https://www.mongodb.com/docs/mongodb-shell.md#mongodb-binary-bin.mongosh), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries in the MongoDB Compass, see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries by using the [MongoDB .NET/C# Driver](https://www.mongodb.com/docs/drivers/csharp/current/), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries by using the [MongoDB Go# driver](https://www.mongodb.com/docs/drivers/go/current/), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries by using the [MongoDB Java driver](https://www.mongodb.com/docs/drivers/java-drivers/), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries by using the [MongoDB Kotlin driver](https://www.mongodb.com/docs/drivers/kotlin-drivers/), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries by using the [MongoDB Node Driver](https://www.mongodb.com/docs/drivers/node/current/), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

To learn how to run the following queries by using the [PyMongo driver](https://www.mongodb.com/docs/drivers/pymongo/), see [Define Your Query.](https://www.mongodb.com/docs/search/about/searching.md#std-label-atlas-search-queries)

### Index Example

The following index definition indexes the `title` field in the `movies` collection with the [keyword analyzer:](https://www.mongodb.com/docs/search/indexes/analyzers/keyword.md#std-label-ref-keyword-analyzer)

```javascript
{
   "mappings": {
      "fields": {
         "title": {
         "analyzer": "lucene.keyword",
         "type": "string"
         }
      }
   }
}
```

### Query Examples

The following example searches all `title` fields for movie titles that begin with `Green D`, followed by any number of other characters.

```json
[
   {
      $search: {
         index: "default",
         "wildcard": {
                     "query": "Green D*",
                     "path": "title"
                  }
      }
   }
]
```

**Output:**

```javascript
SCORE: 1  _id:  "573a1393f29313caabcddaf5"
   awards: Object
   cast: Array (4)
   title: "Green Dolphin Street"

SCORE: 1  _id:  "573a13a2f29313caabd0a4e4"
   awards: Object
   cast: Array (4)
   title: "Green Dragon"
```

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

```

**Output:**

```javascript
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
```

```text
In the :guilabel:`Aggregations` tab of the ``movies`` collection,
configure each of the following pipeline stages by selecting the stage
from the dropdown and adding the query for that stage. Click
:guilabel:`Add Stage` to add additional stages.

.. list-table::
   :header-rows: 1
   :widths: 25 75

   * - Pipeline Stage
     - Query

   * - ``$search``
     - .. code-block:: javascript
          
          {
            "wildcard": {
              "query": "Green D*",
              "path": "title"
            }
          }

   * - ``$project``
     - .. code-block:: javascript
          
          {
            "_id": 0,
            "title": 1,
          }

```

**Output:**

```javascript
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
```

```csharp
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; }
}

```

**Output:**

```javascript
{ "title" : "Green Dolphin Street" }
{ "title" : "Green Dragon" }
```

```go
package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	// connect to your Atlas cluster
	client, err := mongo.Connect(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)
	}
}

```

**Output:**

```javascript
[{title Green Dolphin Street}]
[{title Green Dragon}]
```

```java
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()));
        }
    }
}

```

**Output:**

```javascript
{"title": "Green Dolphin Street"}
{"title": "Green Dragon"}
```

```kotlin
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()
}
```

**Output:**

```javascript
Document{{title=Green Dolphin Street}}
Document{{title=Green Dragon}}
```

```javascript
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);

```

**Output:**

```javascript
{ title: 'Green Dolphin Street' }
{ title: 'Green Dragon' }
```

```python
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)

```

**Output:**

```javascript
{'title': 'Green Dolphin Street'}
{'title': 'Green Dragon'}
```

The following example searches all `title` fields for movie titles that begin with the string `Wom?n` (where `?` may be any single character), followed by a space and then any number of additional characters.

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

**Output:**

```javascript
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:  "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

SCORE: 1  _id:  "573a13b0f29313caabd332de"
fullplot: "Two college friends get together and reminisce on the woman they both …"
imdb: Object
year: 2004
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

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

```

**Output:**

```javascript
[
   { title: 'Woman of the Year' },
   { title: 'Woman in a Dressing Gown' },
   { title: 'Women in Love' },
   { title: 'Women on the Verge of a Nervous Breakdown' },
   { title: 'Woman Wanted' }
]
```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```json
In the :guilabel:`Aggregations` tab of the ``movies`` collection,
configure each of the following pipeline stages by selecting the stage
from the dropdown and adding the query for that stage. Click
:guilabel:`Add Stage` to add additional stages.

.. list-table::
   :header-rows: 1
   :widths: 25 75

   * - Pipeline Stage
     - Query

   * - ``$search``
     - .. code-block:: javascript
          
          {
            "wildcard": {
              "query": "Wom?n *",
              "path": "title"
            }
          }
   
   * - ``$limit``
     - .. code-block:: javascript
          
          5

   * - ``$project``
     - .. code-block:: javascript
          
          {
            "_id": 0,
            "title": 1,
          }

```

**Output:**

```javascript
{ title: 'Woman of the Year' },
{ title: 'Woman in a Dressing Gown' },
{ title: 'Women in Love' },
{ title: 'Women on the Verge of a Nervous Breakdown' },
{ title: 'Woman Wanted' }
```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```csharp
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; }
}

```

**Output:**

```javascript
{ title: 'Woman of the Year' },
{ title: 'Woman in a Dressing Gown' },
{ title: 'Women in Love' },
{ title: 'Women on the Verge of a Nervous Breakdown' },
{ title: 'Woman Wanted' }
```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```go
package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	// connect to your Atlas cluster
	client, err := mongo.Connect(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)
	}
}

```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```java
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()));
        }
    }
}

```

**Output:**

```javascript
[{title Woman of the Year}]
[{title Woman in a Dressing Gown}]
[{title Women in Love}]
[{title Women on the Verge of a Nervous Breakdown}]
[{title Woman Wanted}]
```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```kotlin
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()
}
```

**Output:**

```javascript
{"title": "Woman of the Year"}
{"title": "Woman in a Dressing Gown"}
{"title": "Women in Love"}
{"title": "Women on the Verge of a Nervous Breakdown"}
{"title": "Woman Wanted"}
```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```javascript
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);

```

**Output:**

```javascript
{ title: 'Woman of the Year' }
{ title: 'Woman in a Dressing Gown' }
{ title: 'Women in Love' }
{ title: 'Women on the Verge of a Nervous Breakdown' }
{ title: 'Woman Wanted' }
```

The `$limit` stage limits the results to 5 documents, while the `$project` stage limits the results to only the `title` field.

```python
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)

```

**Output:**

```javascript
{'title': 'Woman of the Year'}
{'title': 'Woman in a Dressing Gown'}
{'title': 'Women in Love'}
{'title': 'Women on the Verge of a Nervous Breakdown'}
{'title': 'Woman Wanted'}
```

The following example searches using the **escape character** for documents in which the `title` field ends with a question mark.

The `*` character in the `query` field matches any characters, and the `\\?` string matches a literal question mark.

Copy and paste the following query into the Query Editor, and then click the Search button in the Query Editor.

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

**Output:**

```javascript
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
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

### Tab

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

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

```

**Output:**

```javascript
{ "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?" }
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```text
In the :guilabel:`Aggregations` tab of the ``movies`` collection,
configure each of the following pipeline stages by selecting the stage
from the dropdown and adding the query for that stage. Click
:guilabel:`Add Stage` to add additional stages.

.. list-table::
   :header-rows: 1
   :widths: 25 75

   * - Pipeline Stage
     - Query

   * - ``$search``
     - .. code-block:: javascript
          
          {
            "wildcard": {
              "query": "*\\?",
              "path": "title"
            }
          }
   
   * - ``$limit``
     - .. code-block:: javascript
          
          5

   * - ``$project``
     - .. code-block:: javascript
          
          {
            "_id": 0,
            "title": 1,
          }

```

**Output:**

```javascript
{ "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?" }
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```csharp
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; }
}

```

**Output:**

```javascript
{ "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?" }
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```go
package main

import (
	"context"
	"fmt"

	"go.mongodb.org/mongo-driver/v2/bson"
	"go.mongodb.org/mongo-driver/v2/mongo"
	"go.mongodb.org/mongo-driver/v2/mongo/options"
)

func main() {
	// connect to your Atlas cluster
	client, err := mongo.Connect(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)
	}
}

```

**Output:**

```javascript
[{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?}]
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```java
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()));
        }
    }
}

```

**Output:**

```javascript
{"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?"}
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```kotlin
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()
}


```

**Output:**

```javascript
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?}}
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```javascript
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);

```

**Output:**

```javascript
{ 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?' }
```

The Search Tester might not display all the fields in the documents it returns. To view all the fields, including the field that you specify in the query path, expand the document in the results.

```python
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)

```

**Output:**

```javascript
{'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?'}
```

The following query uses the [`$searchMeta`](https://www.mongodb.com/docs/search/query/aggregation-stages/searchmeta.md#mongodb-pipeline-pipe.-searchMeta) stage to search for movies that contain the term `summer` anywhere in the `title` field and retrieve the number of movies that match the criteria in each genre.

```json
db.movies.aggregate([
   {
      "$searchMeta": {
         "facet": {
         "operator": {
            "wildcard": {
               "path": "title",
               "query": "*summer*"
            }
         },
         "facets": {
            "genresFacet": {
               "type": "string",
               "path": "genres"
            }
         }
         }
      }
   }
])
```

**Output:**

```javascript
[
   {
      count: { lowerBound: Long('6') },
      facet: {
         genresFacet: {
            buckets: [
               { _id: 'Comedy', count: Long('5') },
               { _id: 'Fantasy', count: Long('3') },
               { _id: 'Romance', count: Long('3') },
               { _id: 'Drama', count: Long('2') },
               { _id: 'Horror', count: Long('1') },
               { _id: 'Mystery', count: Long('1') }
            ]
         }
      }
   }
]
```
