Create a Query
After you create an Atlas Search index on
the collection for all the fields that you want to search, you can
create Atlas Search queries using the $search
and
$searchMeta
stages.
You can create and run an Atlas Search query by performing the following steps.
Construct your Atlas Search query.
Select an aggregation pipeline stage.
Select a tab corresponding to the aggregation pipeline stage you want to use:
You can use the $search aggregation pipeline to perform a full-text search of the indexed fields for data that matches your query.
{ $search: { "index": "<index-name>", ... } } You can use the $searchMeta aggregation pipeline stage to return metadata about your search results.
{ $searchMeta: { "index": "<index-name>", ... } } To learn more, see Choose the Aggregation Pipeline Stage.
Specify operators.
Select one or more operators or collectors to perform a specific search on your collection.
{ $search: { "index": "<index-name>", "<operator-name>": { <operator-specifications> }, } } { $searchMeta: { "index": "<index-name>", "<operator-name>"|"<collector-name>": { <operator-specifications>|<collector-specifications> } } } To learn more, see Use Operators and Collectors in Atlas Search Queries.
(Optional) Retrieve additional information about your Atlas Search query.
Specify one or more options to adjust your Atlas Search query results.
{ $search: { "index": "<index-name>", "<operator-name>": { <operator-specifications> }, "highlight": { <highlight-options> } } } You can customize your search results in the following ways:
OptionUse CaseModify thescore
of the documents in the results to ensure Atlas Search returns relevant results.Retrieve a detailed breakdown of the score for each document Atlas Search returns.- Display your search terms in their original
- context as fields in your query result.
Retrieve information and execution statistics about which Lucene queries Atlas Search executed to satify your query, and how much time your query spends in the various stages of execution.Run your Atlas Search query more efficiently by only retrieving fields stored onmongot
as specified in your Atlas Search index definition for a collection.Display the number of results from your Atlas Search query.Sort your Atlas Search query results by number, string, and date fields and by score.Return metadata, such as the number of results, along with your Atlas Search query.
{ $searchMeta: { "index": "<index-name>", "<operator-name>": { <operator-specifications> }, "count": { <count-options> } } } To learn more, see Define Additional Search Options.
Run your Atlas Search query.
Review your Atlas Search query syntax and then run it in
your application using a driver,
mongosh
, Compass,
or the Search Tester.
Note
If you are experiencing issues with your Atlas Search $search
queries, see Troubleshoot Atlas Search Errors.