Using Atlas Search
1. Creating Search Index
db.products.createSearchIndex("default", {
mappings: { dynamic: true }
});
2. Using $search Aggregation Stage
db.products.aggregate([
{ $search: { index:"default", text:{ query:"wireless", path:"name" } } },
{ $limit: 20 }
]);
3. Implementing Text Search
| Operator | Detail |
| text | Analyzed full-text search |
| phrase | Exact phrase match |
| queryString | Lucene syntax (AND, OR, NOT, *) |
4. Using Autocomplete
{ $search: { autocomplete: { query:"wir", path:"name", tokenOrder:"sequential" } } }
| Setting | Detail |
| Index type | "autocomplete" with edgeGram tokenizer |
| fuzzy | Typo tolerance |
5. Using Fuzzy Matching
| Option | Detail |
| fuzzy.maxEdits | 1–2 typos |
| fuzzy.prefixLength | Chars that must match |
| fuzzy.maxExpansions | Cap on term variants |
6. Using Wildcards
| Operator | Detail |
| wildcard | Glob patterns: *, ? |
| regex | Full regex with allowAnalyzedField |
7. Implementing Faceted Search
db.products.aggregate([
{ $searchMeta: { facet: {
operator: { text: { query:"laptop", path:"name" } },
facets: { brandFacet: { type:"string", path:"brand" } }
} } }
]);
8. Using Highlighting
| Option | Detail |
| highlight.path | Field(s) to highlight |
| Output | $meta:"searchHighlights" |
9. Scoring and Ranking Results
| Mechanism | Detail |
| $meta:"searchScore" | Relevance score per doc |
| score.boost | Multiply |
| score.function | Custom expression (decay, log, etc.) |
10. Using Compound Queries
{ $search: { compound: {
must: [{ text:{ query:"laptop", path:"name" } }],
should: [{ text:{ query:"gaming", path:"tags", score:{boost:{value:2}} } }],
filter: [{ range:{ path:"price", lte: 2000 } }],
mustNot: [{ text:{ query:"refurbished", path:"description" } }]
} } }
| Clause | Detail |
| must | Required + contributes to score |
| should | Optional; boosts score |
| filter | Required, no score impact |
| mustNot | Exclusion |
11. Configuring Custom Analyzers
{
"analyzers": [{
"name": "myCustom",
"charFilters": [{"type":"htmlStrip"}],
"tokenizer": {"type":"standard"},
"tokenFilters": [{"type":"lowercase"}, {"type":"asciiFolding"}]
}],
"mappings": { "dynamic": false,
"fields": { "title": {"type":"string","analyzer":"myCustom"} }
}
}
| Component | Examples |
| charFilters | htmlStrip, mapping, persian |
| tokenizers | standard, keyword, whitespace, edgeGram, nGram |
| tokenFilters | lowercase, asciiFolding, stemmer, stopwords, synonym, shingle |