querystring
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: beg1, beg2, beg3, beg4, eg1, eg2, to, to-and, fuzzy, wildcard, regex, searchmeta-stage, searchmeta-variable -->
queryString Operator
Definition
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.
Syntax
queryString has the following syntax:
{
"$search": {
"index": <index name>, // optional, defaults to "default"
"queryString": {
"defaultPath": "<default-field-to-search>",
"query": "(<field-to-search>: (<search-values>) AND|OR (<search-values>)) AND|OR (<search-values>)"
}
}
}
Options
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 |
Scoring Behavior
By default, the [text](https://www.mongodb.com/docs/search/query/operators-collectors/text.md#std-label-text-ref 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](https://www.mongodb.com/docs/search/indexes/field-types/string-type.md#std-label-bson-data-types-string.
To learn more about the supported similarity algorithms, see [Score Details.](https://www.mongodb.com/docs/search/query/score/get-details.md#std-label-fts-similarity-algorithms
Examples
The following examples use the movies collection in the sample_mflix database. 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 the MongoDB Search index named default with dynamic mappings and run the example queries on your cluster.
Boolean Operator Queries
Basic Examples
AND OR
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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to exclude all fields except title.
db.movies.aggregate([
{
$search: {
"queryString": {
"defaultPath": "title",
"query": "Rocky AND (IV OR 4 OR Four)"
}
}
},
{
$project: {
"_id": 0,
"title": 1
}
}
])
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" }
Advanced Examples
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](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to:
-
Exclude all fields except
title,plot, andfullpath -
Add a field named
score
Example 1
The following query searches for chess and either captain or kirk in the plot field.
db.movies.aggregate([
{
$search: {
"queryString": {
"defaultPath": "fullplot",
"query": "plot:(captain OR kirk) AND chess"
}
}
},
{
$project: {
"_id": 0,
"title": 1,
"plot": 1,
"fullplot": 1,
score: { $meta: "searchScore" }
}
}
])
Output:
{
"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.
Range Queries
TO
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.
db.movies.aggregate([
{
"$search": {
"queryString": {
"defaultPath": "plot",
"query": "title:[count TO *]"
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])
Output:
[
{ title: 'Blacksmith Scene' },
{ title: 'The Great Train Robbery' },
{ title: 'The Land Beyond the Sunset' },
{ title: 'A Corner in Wheat' },
{ title: 'Winsor McCay, the Famous Cartoonist of the N.Y. Herald and His Moving Comics' },
{ title: 'Traffic in Souls' },
{ title: 'Gertie the Dinosaur' },
{ title: 'In the Land of the Head Hunters' },
{ title: 'The Perils of Pauline' },
{ title: 'The Birth of a Nation' }
]
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' }
]
Wildcard Queries
The following examples use the queryString operator to query for movie titles using fuzzy, wildcard, and regular expressions. The queries include a [$project](https://www.mongodb.com/docs/manual/reference/operator/aggregation/project.md#mongodb-pipeline-pipe.-project stage to exclude all fields except title.
Fuzzy Example
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.
db.movies.aggregate([
{
"$search": {
"queryString": {
"defaultPath": "title",
"query": "catch~2"
}
}
},
{
"$limit": 10
},
{
"$project": {
"_id": 0,
"title": 1
}
}
])
Output:
[
{ title: 'Catch-22' },
{ title: 'Catch That Girl' },
{ title: 'Catch That Kid' },
{ title: 'Catch a Fire' },
{ title: 'Catch Me Daddy' },
{ title: 'Death Watch' },
{ title: 'Patch Adams' },
{ title: "Batch '81" },
{ title: 'Briar Patch' },
{ title: 'Night Watch' }
]
Metadata Query
The following query searches the title field in the movies collection for Marvel, Avengers, Iron Man, or Captain
America.
$searchMeta stage
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
db.movies.aggregate([
{
"$searchMeta": {
"facet": {
"operator": {
"queryString": {
"defaultPath": "title",
"query": "\"Marvel\" OR \"Avengers\" OR \"Iron Man\" OR \"Captain America\""
}
},
"facets": {
"yearFacet": {
"type": "number",
"path": "year",
"boundaries": [1990, 2000, 2005, 2010, 2015, 2020 ]
}
}
}
}
}
])
Output:
[
{
count: { lowerBound: Long('16') },
facet: {
yearFacet: {
buckets: [
{ _id: 1990, count: Long('1') },
{ _id: 2000, count: Long('0') },
{ _id: 2005, count: Long('4') },
{ _id: 2010, count: Long('10') },
{ _id: 2015, count: Long('1') }
]
}
}
}
]
