Writing $search Queries: Text, Phrase, and Wildcard
Learners will query with text, phrase, and wildcard operators inside the $search aggregation stage and project the search score.
The $search Aggregation Stage
Atlas Search queries are written using the $search aggregation stage—a special pipeline stage that routes the query to the Lucene engine rather than the MongoDB query planner. The $search stage must be the first stage in an aggregation pipeline. Inside it, you specify an operator (like text, phrase, or wildcard) that determines how the query string is matched against indexed documents.
The text Operator: Keyword Search
The text operator is the standard keyword search operator. It tokenizes the query string using the same analyzer used to build the index, then looks for documents containing those tokens. It supports multi-word queries where any word can match (OR semantics by default) and the path field specifies which indexed fields to search in—either a specific field name or all fields via { wildcard: '*' }.
db.articles.aggregate([
{
$search: {
index: 'default',
text: {
query: 'mongodb aggregation pipeline',
path: 'content' // search in the 'content' field only
}
}
},
{
$project: {
title: 1,
author: 1,
score: { $meta: 'searchScore' }
}
},
{ $limit: 10 }
])All lessons in this course
- Creating an Atlas Search Index
- Writing $search Queries: Text, Phrase, and Wildcard
- Autocomplete and Fuzzy Matching
- Facets and Compound Queries