A proximity query finds documents where search terms occur near one another. It is useful when the distance between terms matters more than an exact, uninterrupted phrase—for example, when searching legal clauses or customer reviews. section 11.5.1
In Atlas Search, use the phrase operator in a $search aggregation stage. Set query to the terms, path to the field, and slop to the allowed number of intervening words. Unlike a fuzzy text query, this example controls term spacing rather than accommodating misspellings. section 11.5.1
db.inspections.aggregate([
{
$search: {
index: "MongoDB-in-Action",
phrase: {
query: ["food", "license"], // Words to search for
path: "business_name", // Field to search in
slop: 3 // Allows up to 3 intervening words
➥ // between "food" and "license"
}
}
},
{
$limit: 1 // Limits the number of results to 1
},
{
$set: {
// Adds necessary fields to the output documents
business_name: "$business_name",
result: "$result",
sector: "$sector"
}
},
{
$unset: ["_id", "address", "date"] // Removes the '_id',
➥ // 'address', and 'date' fields from
➥ // the output documents
}
])
The query searches business_name for “food” and “license” with slop: 3. The following $limit: 1 keeps the displayed result brief; it does not establish that only one document matches. section 11.5.1
A matching business name
“FOOD CART VENDOR LICENSE# C4029” contains the queried words with other words between them, illustrating why a proximity query can find a relevant name without requiring an uninterrupted phrase. section 11.5.1
Positional matching and relevance scoring are related but distinct: term proximity can also affect a Lucene search result’s score. Use slop to express the spacing required by the query, rather than treating a score alone as that requirement. section 11.5.1 section 11.2
