title: MongoDB: apply $filter stage only if a condition is met?
body: <p>I have a data model that looks like this:</p>
  <pre><code>{
    &quot;company&quot;: &lt;company name&gt;,
    ...,
    &quot;subFields&quot;: [
      {
        ...,
        &quot;division&quot; &lt;division name&gt;
      },
      ...
      ]
    }
  }
  </code></pre>
  <p>Given this data model, my mongoDB pipeline needs to just match documents whose <code>company</code> is in a list <code>all_companies</code>, and filter the contents of others whose company is in a list <code>special_companies</code>, each according to its own rule. So for example for <code>special company #1</code> we only want <code>subFields</code> elements whose <code>division</code> field has a specific value, thus the following filter must be applied:</p>
  <pre><code>{
    &quot;$addFields&quot;: {
      &quot;subFields&quot;: {
         &quot;$filter&quot;: {
           &quot;input&quot;: &quot;$subFields&quot;,
           &quot;as&quot;: &quot;subFields&quot;,
           &quot;cond&quot;: {&quot;$eq&quot;: [&quot;$$subFields.division&quot;, &lt;division of special company #1&gt;]}
         }
       }
    }
  }
  </code></pre>
  <p>So in practice there should be a kind of if statement after the general <code>$match: {&quot;company&quot;: {&quot;$in&quot;: all_companies}}</code> stage.</p>
  <pre><code>if company == special company #1:
      then apply filter #1
  if company == special company #2:
      then apply filter #2
  ...
  else:
      just pass all the results of $match
  </code></pre>
  <p>How can this be accomplished using aggregation operators?</p>