liveBook · Manning

Phrase operator

As explained in MongoDB 8.0 in Action, Third Edition

A phrase operator is an Atlas Search operator that matches terms occurring in a specified relative arrangement and allowable distance.

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

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Works through query, path, and slop in an aggregation pipeline, without detailing search internals.
Examples
Searches inspection business names for “food” near “license” and returns a food-cart vendor name.
What it assumes
Assumes an Atlas Search index and a MongoDB collection; demonstrates pipeline configuration rather than index creation.
What you can do after
Apply it via Atlas Search to find terms separated by a configured number of words.
How it connects
Connects proximity search to the $search aggregation stage and its slop property.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.