Docs Menu
Docs Home
/
MongoDB Atlas
/ / / /

queryString

On this page

  • Definition
  • Syntax
  • Options
  • Examples
  • Boolean Operator Queries
  • Range Queries
  • Wildcard Queries
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. Atlas 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.

Tip

See also:

Examples for some sample queries that use the operators and delimiters to search the sample movies collection.

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

?
Indicates any single character to match.
*
Indicates 0 or more characters to match.
/
Delimiter for regular expression.
~

Indicates fuzzy search to find strings which are similar to the search term. If you use this with multiple terms in a string, the queryString operator does a proximity search for the terms within the specified number of terms.

Note

For fuzzy search, the queryString operator matches terms up to at most 2 edits. Higher distances are not useful as it might match a significant amount of the dictionary term. For example, "foo":"stop"~2 is equal to the following:

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

For proximity search, the queryString operator matches terms using the distance specified between words in the search phrase. For example, "foo":"New York"~2 is equal to the following:

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

Note

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.

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.

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

Note

When you query values in arrays, Atlas Search doesn't alter the score of the matching results based on the number of values inside the array that matched the query. The score would be the same as a single match regardless of the number of matches inside an array.

no

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 Atlas 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.

Example

The following query searches for the combination of 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, Atlas Search performs a search at defaultPath because there are no fields in the query. It returns the following results:

{ "title" : "Rocky IV" }

The following example uses the queryString operator to query for movies with the title Rocky and not II, III, VI, or V.

Example

The following query searches for the string Rocky and not any form of the numbers 2, 3, 4, or 5 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 NOT ((II OR 2 OR Two) OR (III OR 3 OR Three) OR (IV OR 4 OR Four) OR (V OR 5 OR Five))"
7 }
8 }
9 },
10 {
11 $project: {
12 "_id": 0,
13 "title": 1
14 }
15 }
16])

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

[
{ title: 'Rocky' },
{ title: 'Rocky Marciano' },
{ title: 'Rocky Balboa' },
{ title: 'The Rocky Horror Picture Show' },
{ title: 'The Adventures of Rocky & Bullwinkle' }
]

The following example uses the queryString operator to query for movies with the title The Italian in the Drama genre.

Example

The following query searches a combination of fields for movies with the title The Italian in the Drama genre. The plot field in the defaultPath will be searched only if no matching results can be found in either of the fields specified in the query field. The query field contains escaped double quotes as delimiters for the phrase to search.

The query includes a $project stage to:

  • Exclude all fields except _id, title, plot, and genres

  • Add a field named score

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "plot",
6 "query": "title:\"The Italian\" AND genres:Drama"
7 }
8 }
9 },
10 {
11 $project: {
12 "_id": 1,
13 "title": 1,
14 "plot": 1,
15 "genres": 1,
16 score: { $meta: "searchScore" }
17 }
18 }
19])

This query returns the following results:

1{
2 "_id" : ObjectId("573a1390f29313caabcd56df"),
3 "plot" : "An immigrant leaves his sweetheart in Italy to find a better life across the sea in the grimy slums of New York. They are eventually reunited and marry. But life in New York is hard and ...",
4 "genres" : [ "Drama" ],
5 "title" : "The Italian",
6 "score" : 4.975106716156006
7}
8{
9 "_id" : ObjectId("573a13b3f29313caabd3e36c"),
10 "plot" : "Set in 2002, an abandoned 5-year-old boy living in a rundown orphanage in a small Russian village is adopted by an Italian family.",
11 "genres" : [ "Drama" ],
12 "title" : "The Italian",
13 "score" : 4.975106716156006
14}
15{
16 "_id" : ObjectId("573a13c7f29313caabd756ee"),
17 "plot" : "A romantic fairy tale about a 19-year old orphan girl who, as her sole inheritance, gets an antique key that unlocks both an old Italian villa and the secrets of her family history.",
18 "genres" : [ "Comedy", "Drama", "Romance" ],
19 "title" : "The Italian Key",
20 "score" : 4.221206188201904
21}
22{
23 "_id" : ObjectId("573a13caf29313caabd7d1e4"),
24 "plot" : "A chronicle of the 1969 bombing at a major national bank in Milan and its aftermath.",
25 "genres" : [ "Drama" ],
26 "title" : "Piazza Fontana: The Italian Conspiracy",
27 "score" : 3.4441356658935547
28}

The following example uses the queryString operator to query for movie plots that contain the terms captain or kirk and enterprise.

Example

The following query searches for a combination of terms, captain or kirk and enterprise, in the plot field. It includes a $limit stage to limit the output to 3 results and a $project stage to:

  • Exclude all fields except title, plot, and fullplot

  • Add a field named score

1db.movies.aggregate([
2 {
3 $search: {
4 "queryString": {
5 "defaultPath": "fullplot",
6 "query": "plot:(captain OR kirk) AND enterprise"
7 }
8 }
9 },
10 {
11 $limit: 3
12 },
13 {
14 $project: {
15 "_id": 0,
16 "title": 1,
17 "plot": 1,
18 "fullplot": 1,
19 score: { $meta: "searchScore" }
20 }
21 }
22])

This query returns the following results:

1{
2 "plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.",
3 "fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.",
4 "title" : "Star Trek: Generations",
5 "score" : 11.274821281433105
6}
7{
8 "plot" : "Captain Kirk and his crew must deal with Mr. Spock's long-lost half-brother who hijacks the Enterprise for an obsessive search for God at the center of the galaxy.",
9 "fullplot" : "When the newly-christened starship Enterprise's shakedown cruise goes poorly, Captain Kirk and crew put her into Spacedock for repairs. But an urgent mission interrupts their Earth-bound shore leave. A renegade Vulcan named Sybok has taken three ambassadors hostage on Nimbus III, the Planet of Galactic Peace. This event also attracts the attention of a Klingon captain who wants to make a name for himself and sets out to pursue the Enterprise. Sybok's ragtag army captures the Enterprise and takes her on a journey to the center of the galaxy in search of the Supreme Being.",
10 "title" : "Star Trek V: The Final Frontier",
11 "score" : 9.889547348022461
12}
13{
14 "plot" : "When an alien spacecraft of enormous power is spotted approaching Earth, Admiral Kirk resumes command of the Starship Enterprise in order to intercept, examine and hopefully stop the intruder.",
15 "fullplot" : "A massive alien spacecraft of enormous power is approaching Earth, destroying everything in its path. The only star ship in range is the USS Enterprise still in dry-dock after a major overhaul. As Captain Willard Decker readies his ship and his crew to face this menace, Admiral James T. Kirk arrives with orders to take command of the Enterprise and intercept the alien intruder. But it has been three years since Kirk last commanded the Enterprise on its historic five year mission... is he up to the task of saving the Earth?",
16 "title" : "Star Trek: The Motion Picture",
17 "score" : 8.322310447692871
18}

The documents in the above results match because:

  • In the first document, the plot field, which is the field to search per the query, contains both captain and kirk, although only either one is required to meet the criteria for a match. For the term enterprise, Atlas Search searches the fullplot field, which is the defaultPath, because the plot field does not contain enterprise, and finds enterprise in the fullplot field.

  • In the second document, the plot field contains all three search terms.

  • In the third document, the plot field contains kirk and enterprise.

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

Example

The following queries search for a combination of the terms, captain, kirk, and chess in the plot field. Each query returns a different result depending on how the search terms are grouped.

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])

This query returns the following results:

{
"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 above 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 query searches for captain or both kirk and chess in the plot field.

db.movies.aggregate([
{
$search: {
"queryString": {
"defaultPath": "fullplot",
"query": "plot:captain OR (kirk AND chess)"
}
}
},
{
$limit: 5
},
{
$project: {
"_id": 0,
"title": 1,
"plot": 1,
"fullplot": 1,
score: { $meta: "searchScore" }
}
}
])

This query returns the following results:

{
"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" : 9.227973937988281
}
{
"plot" : "Captain Picard, with the help of supposedly dead Captain Kirk, must stop a madman willing to murder on a planetary scale in order to enter an energy ribbon.",
"title" : "Star Trek: Generations",
"fullplot" : "In the late 23rd century, the gala maiden voyage of the third Starship Enterprise (NCC-1701-B) boasts such luminaries as Pavel Chekov, Montgomery Scott and the legendary Captain James T. Kirk as guests. But the maiden voyage turns to disaster as the unprepared ship is forced to rescue two transport ships from a mysterious energy ribbon. The Enterprise manages to save a handful of the ships' passengers and barely makes it out intact... but at the cost of Captain Kirk's life. Seventy-eight years later, Captain Jean-Luc Picard and the crew of the Enterprise-D find themselves at odds with the renegade scientist Tolian Soran... who is destroying entire star systems. Only one man can help Picard stop Soran's scheme... and he's been dead for seventy-eight years.",
"score" : 3.3556222915649414
}
{
"plot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every ...",
"title" : "Scent of a Woman",
"fullplot" : "An army cadet accompanies an irascible, blind captain on a week-long trip from Turin to Naples. The captain, Fausto, who wants no pity, brooks no disagreement, and charges into every situation, nicknames the youth Ciccio (\"Babyfat\"), and spends the next few days ordering him about and generally behaving badly in public. In Rome, Fausto summons a priest to ask for his blessing; in Naples, where Fausto joins a blind lieutenant for drinking and revelry, the two soldiers talk quietly and seriously about \"going through with it.\" Also in Naples is Sara, in love with Fausto, but treated cruelly by him. What do the blind soldiers plan? Can Sara soften Fausto's hardened heart?",
"score" : 3.2553727626800537
}
{
"plot" : "A seductive woman falls in love with a mysterious ship's captain.",
"title" : "Pandora and the Flying Dutchman",
"fullplot" : "Albert Lewin's interpretation of the legend of the Flying Dutchman. In a little Spanish seaport named Esperanza, during the 30s, appears Hendrick van der Zee, the mysterious captain of a yacht (he is the only one aboard). Pandora is a beautiful woman (who men kill and die for). She's never really fallen in love with any man, but she feels very attracted to Hendrick... We are soon taught that Hendrick is the Flying Dutchman, this sailor of the 17th century that has been cursed by God to wander over the seas until the Doomsday... unless a woman is ready to die for him...",
"score" : 3.2536067962646484
}
{
"plot" : "The adventures of pirate Captain Red and his first mate Frog.",
"title" : "Pirates",
"fullplot" : "Captain Red runs a hardy pirate ship with the able assistance of Frog, a dashing young French sailor. One day Capt. Red is captured and taken aboard a Spanish galleon, but thanks to his inventiveness, he raises the crew to mutiny, takes over the ship, and kidnaps the niece of the governor of Maracaibo. The question is, can he keep this pace up?",
"score" : 3.2536067962646484
}

The documents in the above results match because the plot field contains the term captain. The first document gets a higher score because Atlas Search also finds the terms kirk and chess in the fullplot field although the terms are not required to be present to meet the criteria for a match.

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.

Example

1 db.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]

Atlas 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, Atlas Search creates separate tokens for the terms in the title field and matches the query term to the individual tokens. Specifically, Atlas 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, Atlas 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 example uses the queryString operator to query the movie genres for drama and the titles for a range of textual values between man and men, including both, in ascending alphabetical order.

Example

1 db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "plot",
6 "query": "title:[man TO men] AND genres: Drama"
7 }
8 }
9 },
10 {
11 "$limit": 10
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1,
17 "genres": 1
18 }
19 }
20 ])
1[
2 { genres: [ 'Drama' ], title: 'The Wedding March' },
3 { genres: [ 'Drama' ], title: 'Maria Chapdelaine' },
4 { genres: [ 'Drama' ], title: 'Of Mice and Men' },
5 { genres: [ 'Drama' ], title: 'All the King's Men' },
6 { genres: [ 'Drama' ], title: 'Wuya yu maque' },
7 { genres: [ 'Drama' ], title: 'The Men' },
8 { genres: [ 'Drama' ], title: 'The Member of the Wedding' },
9 { genres: [ 'Drama' ], title: 'The Great Man' },
10 { genres: [ 'Drama' ], title: 'A Matter of Dignity' },
11 { genres: [ 'Drama' ], title: 'The Last Angry Man' }
12]

The documents in the results match because the genres field contains the term drama and the movie title field contains terms between Man and Men in alphabetical order (Man, Maque, March, Maria, Matter, Member, and Men in the results).

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 uses wildcard expression to search the title field for movie titles that contain characters cou*t?*, where * indicates any additional number of characters and ? indicates any single character.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "cou*t?*"
7 }
8 }
9 },
10 {
11 "$limit": 5
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1
17 }
18 }
19])
1[
2 { title: 'A Day in the Country' },
3 { title: 'Diary of a Country Priest' },
4 { title: 'Cry, the Beloved Country' },
5 { title: 'The Country Girl' },
6 { title: 'Raintree County' }
7]

The documents in the results match because the title field contains the term Country or County, which matches the query criteria for characters starting with cou followed by any number of characters (n in the results) and then t followed by at least one or many characters (r as in country or y as in county in the results).

The following query uses a regular expression to search the title field for movie titles that contain characters that start with any character followed by the characters tal and either y or ian after tal.

1db.movies.aggregate([
2 {
3 "$search": {
4 "queryString": {
5 "defaultPath": "title",
6 "query": "/.tal(y|ian)/"
7 }
8 }
9 },
10 {
11 "$limit": 5
12 },
13 {
14 "$project": {
15 "_id": 0,
16 "title": 1
17 }
18 }
19])
1[
2 { title: 'The Italian' },
3 { title: 'Journey to Italy' },
4 { title: 'Divorce Italian Style' },
5 { title: 'Marriage Italian Style' },
6 { title: 'Jealousy, Italian Style' }
7]

The documents in the results match because the title field contains the term Italy or Italian, which matches the query criteria for any character (I in the results) followed by tal with either y (as in Italy in the results) or ian (as in Italian in the results).

Back

phrase

Next

range