title: MongoDb $elemMatch with $lookup variable
body: <p>I have a given MongoDb collection with documents which look similar to this:</p>
  <pre><code>{
  items: [
    { id: 1, data: 'a' },
    { id: 2, data: 'b' },
    { id: 3, data: 'c' },
  ]
  }
  </code></pre>
  <p>Now I have to <code>$lookup</code> from this collection. I need the array data from the element with id = 2 where id = 1 data matches the lookup value <code>$$value</code>. My first naive try to find the correct document looked like this:</p>
  <pre><code>$match {
    items: { $elemMatch: {
      id: 1,
      data: '$$value'
    } }
  }
  </code></pre>
  <p>But the <code>$$value</code> is not evaluated, so the data is compared to the literal instead of its value. I also tried to evaluate the value using <code>$expr</code>, but I wasn't able to get the syntax right (if possible at all?).</p>
  <p>The only working way I was able to get working was by extracting the data first and do the matching afterwards:</p>
  <pre><code>[
      {
          $project: {
              _id: 0,
              data1: {
                  $filter: {
                      input: '$items', as: 'item',
                      cond: {$eq: ['$$item.id', 1]}
                  }
              },
              data2: {
                  $filter: {
                      input: '$items', as: 'item',
                      cond: {$eq: ['$$item.id', 2]}
                  }
              },
          }
      },
      {
          $set: {
              data1: {$arrayElemAt: ['$data1.data', 0]},
              data2: {$arrayElemAt: ['$data2.data', 0]}
          }
      },
      {
          $match: {
              $expr: {$eq: ['$data1', '$$value']}
          }
      }
  ];
  </code></pre>
  <p>But as one might expect, this approach is much slower. For the data involved the query took over 7s, whereas the upper approach (using a constant instead of a variable <code>$$value</code>) over 3x as fast.</p>
  <p>Is it possible to use the variable <code>$$value</code> directly in the <code>$elemMatch</code> operator? Or is there any other optimization available to speed-up the collection lookup?</p>