MongoDB enterprise - how to get searched array item on the result

I am working on Enterprise MongoDB and using $text search on array embedded fields. How to get the matched array element from the result. Currently I get the first array element by default if there is a match.

Without knowing anything about the data… some general guidelines… to retrieve the matched array element when using $text search on array embedded fields in, you can use the aggregation framework to filter and project the specific matched elements. Here’s a step-by-step approach:

  1. Ensure your collection has a text index.
  2. Use the $match stage with $text to search for the term.
  3. Use the $filter stage to extract the matched elements from the array.
  4. Use $project to include only the necessary fields.

Here’s a basic example…


db.yourcollection.aggregate([
  {
    $match: {
      $text: { $search: "<your search word>" }
    }
  },
  {
    $addFields: {
      textScore: { $meta: "textScore" }
    }
  },
  {
    $project: {
      items: {
        $filter: {
          input: "$items",
          as: "item",
          cond: { $regexMatch: { input: "$$item.description", regex: "<your search word>", options: "i" } }
        }
      },
      textScore: 1
    }
  }
])