The Atlas Search phrase operator finds terms near one another in a specified field. Use it for proximity searches when their relative position matters more than an exact phrase match. The slop property sets how many words may appear between the searched terms. section 11.5.1
Find nearby terms in business names
In a $search stage, set phrase.query to ["food", "license"], path to "business_name", and slop to 3. This permits up to three intervening words. One returned name is “FOOD CART VENDOR LICENSE# C4029.” 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
}
])
See the complete aggregation pipeline, including the result limit and output-field selection. section 11.5.1
