$search is a MongoDB aggregation pipeline stage for full-text search. It queries an Atlas Search index built with Lucene; every field you search must be included in that index. Use it when an application needs to find matching documents by their text rather than simply reshape or group documents. section 11.5.1 section 1.5
Listing 11.4 The $search prototype form
{
$search: {
"index": "<index-name>",
"<operator-name>"|"<collector-name>": {
<operator-specification>|<collector-specification>
},
"highlight": {
<highlight-options>
},
"concurrent": true | false,
"count": {
<count-options>
},
"searchAfter"|"searchBefore": "<encoded-token>",
"scoreDetails": true| false,
"sort": {
<fields-to-sort>: 1 | -1
},
"returnStoredSource": true | false,
"tracking": {
<tracking-option>
}
}
}
The stage specifies an index and a search operator or collector. If index is omitted, Atlas Search uses an index named default. The prototype also shows optional controls for highlighting, result counts, pagination, scoring details, sorting, and other search behavior. section 11.5.1
Build a query around the kind of match the application needs:
- Use compound.must when several conditions must match. An inspections query searches business_name for “food,” result for “PASS,” and sector for “127.” section 11.5.1
- Use text.fuzzy for misspellings. maxEdits sets the allowed edits, while prefixLength requires an exact starting prefix; a misspelled business name can still return “BUILDING TO SERVE INC.” section 11.5.1
- Use phrase with slop for terms separated by intervening words, or wildcard with * and ? for pattern matching. The wildcard example sets allowAnalyzedField to search an analyzed field. section 11.5.1
Inspect and summarize matches
Run db.inspections.aggregate() with $search against the named index, then add score: { $meta: "searchScore" } in a $set stage to expose each match’s relevance score. Subsequent stages can limit results or use $facet to count matches by inspection status, year, or sector. This keeps search and result analysis in one aggregation pipeline. section 11.5.1
For a hands-on query, connect to an Atlas cluster with mongosh and select the database containing the indexed collection. Check the index name and indexed fields before testing; a query aimed at fields outside the Atlas Search index does not meet the stage’s stated requirements. section 11.5.1
