For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

queryString Operator

queryString

The queryString operator supports querying a combination of indexed fields and values. You can perform text, wildcard, regular expression, fuzzy, and range searches on string fields using the queryString operator.

queryString has the following syntax:

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

queryString uses the following terms to construct a query:

Field
Type
Description
Necessity

defaultPath

string

The indexed field to search by default. MongoDB Search only searches the field in defaultPath if you omit the field to search in the query.

yes

query

string

One or more indexed fields and values to search. Fields and values are colon-delimited. For example, to search the plot field for the string baseball, use plot:baseball. The following operators are available to combine multiple search criteria:

You can combine the fields and values using the following:

  • AND: Indicates AND boolean operator. All search values must be present for a document to be included in the results.

  • OR: Indicates OR boolean operator. At least one of the search value must be present for a document to be included in the results.

  • NOT: Indicates NOT boolean operator. Specified search value must be absent for a document to be included in the results.

  • TO: Indicates the range to search. You can use [] for an inclusive range, {} for an exclusive range, or {] and [} for an half-open range. Any value that falls within the specified range must be present for a document to be included in the results.

  • (): Delimiters for subqueries. Use the parentheses to group fields and values to search.

You can run wildcard and regular expression queries using the following:

  • ?: Indicates any single character to match.

  • *: Indicates 0 or more characters to match.

    The queryString operator doesn't support a wildcard query with * as the first character in the query. The queryString operator treats any character preceding the * as prefix or as characters that must exactly match.

  • /: Delimiter for regular expression.

  • ~: Indicates fuzzy search to find strings which are similar to the search term by up to the specified number of edits. For example, { "query":"foo":"stop"~2 } is equal to the following:

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

    The queryString operator only supports fuzzy search for up to at most 2 edits. Higher distances are not useful as the results may match many dictionary terms.

    If you use ~ with multiple terms in a string, the queryString operator does a proximity search for the terms within the specified number of terms. For example, { "query":"foo":"New York"~2 } is equal to the following:

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

yes

score

object

The score assigned to matching search results. You can modify the default score using the following options:

  • boost: multiply the result score by the given number.

  • constant: replace the result score with the given number.

  • function: replace the result score with the given expression.

When querying array values, MongoDB Search assigns higher scores if more values in the array match the query.

For information on using score in your query, see Score the Documents in the Results.

no

By default, the text operator uses the bm25 similarity algorithm to score documents depending on their relevance to the query.

You can change which similarity algorithm is used by specifying a different similarity algorithm in the similarity.type property for the string fields in your MongoDB Search index definition. To learn how to configure a MongoDB Search index for the string type, see How to Index String Fields.

To learn more about the supported similarity algorithms, see Score Details.

The following examples use the movies collection in the sample_mflix database. If you have the sample dataset on your cluster , you can create the MongoDB Search index named default with dynamic mappings and run the example queries on your cluster.

The following example uses the queryString operator to query for movies with the title Rocky and either IV, 4, or Four at path title in the movies collection. In the following query, a field is specified in the defaultPath, but no fields are specified in the query. The query includes a $project stage to exclude all fields except title.

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

For this query, MongoDB Search performs a search at defaultPath because there are no fields in the query. It returns the following results:

{ "title" : "Rocky IV" }

The examples in this section use the queryString operator to query for movie plots that contain the terms captain, kirk, and chess. This examples shows how different grouping of the same search terms using parentheses can result in different documents to be included in the search results.

The queries also includes a $project stage to:

  • Exclude all fields except title, plot, and fullpath

  • Add a field named score

The following query searches for chess and either captain or kirk in the plot field.

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

The document in the results is a match because the plot contains the terms captain and kirk, although only one is needed to meet the criteria for a match, and the term chess, although not in the plot, appears in the fullplot, which is the defaultPath.

The following example uses the queryString operator to query the movie titles a range of textual values from the characters count to any character (defined using the wildcard character *) in ascending alphabetical order.

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

MongoDB Search results include movies with titles Blacksmith Scene and A Corner in Wheat although the range in the query starts from characters count. When you index with the default analyzer, lucene.standard, MongoDB Search creates separate tokens for the terms in the title field and matches the query term to the individual tokens. Specifically, MongoDB Search creates the following tokens, at least one of which (indicated by √) matches the query criteria:

Title
Standard Analyzer Tokens

Blacksmith Scene

blacksmith, scene √

A Corner in Wheat

a, corner, in, wheat √

If you index using the lucene.keyword analyzer, MongoDB Search would create a single token for the whole string in the title field, resulting in results similar to the following for the same query:

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

The following examples use the queryString operator to query for movie titles using fuzzy, wildcard, and regular expressions. The queries include a $project stage to exclude all fields except title.

The following query uses fuzzy (~) to do a fuzzy search in the title field for movie titles that contain terms similar to catch with up to a two character variation.

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

The following query searches the title field in the movies collection for Marvel, Avengers, Iron Man, or Captain America.

The following query returns movies in the following buckets (years) that match the search criteria:

  • 2000, inclusive lower bound for this bucket

  • 2005, exclusive upper bound for the 2000 bucket and inclusive lower bound for this bucket

  • 2010, exclusive upper bound for the 2005 bucket and inclusive lower bound for this bucket

  • 2015, exclusive upper bound for the 2010 bucket and inclusive lower bound for this bucket

  • 2020, exclusive upper bound for the 2015 bucket

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