title: MongoDB: Find all subdocuments that match a regex condition
body: <p>I'm trying to filter MongoDB subdocuments based on regex. I already know that I must use MongoDB's aggregation function, as <code>find()</code> only returns the first document.</p>
  <p>Assume I have data in the following format:</p>
  <pre class="lang-json prettyprint-override"><code>{
      &quot;owner&quot;: &quot;Jim&quot;,
      &quot;pets&quot;: [
          { &quot;name&quot;: &quot;Max&quot;, ... },
          { &quot;name&quot;: &quot;Mocha&quot;, ... },
          { &quot;name&quot;: &quot;Spanky&quot;, ... },
          ...
      ]
  },
  {
      ...
  }
  </code></pre>
  <p>Let's say I want to find all of <code>Jim</code>'s pets whose name matches a regular expression (say, all pets whose names start with &quot;M&quot;). How might I do this? I've found <a href="https://stackoverflow.com/questions/55614581/mongodb-how-to-find-all-subdocuments-that-match-a-criteria">this question and answer</a>, but it doesn't work because <code>$filter</code> doesn't allow the use of <code>$regex</code> (apparently).</p>
  <p>Using MongoDB 5.</p>