title: MongoDB $lookup on array of documents containing object id
body: <p>I want to make aggregation pipeline in MongoDB v4.4.</p>
  <p>I have two collections.</p>
  <ol>
  <li><p><code>users</code> collection</p>
  <pre><code>[
    { _id: &quot;user1&quot;, username: &quot;john&quot; },
    { _id: &quot;user2&quot;, username: &quot;bob&quot; },
  ]
  </code></pre>
  </li>
  <li><p><code>articles</code> collection</p>
  <pre><code>[
    {
      _id: &quot;article1&quot;,
      view_history: [
        { user: &quot;user1&quot;, viewed_at: ISODate(&quot;...&quot;) },
        { user: &quot;user2&quot;, viewed_at: ISODate(&quot;...&quot;) },
        { user: &quot;user1&quot;, viewed_at: ISODate(&quot;...&quot;) },
      ]
    }
  ]
  </code></pre>
  </li>
  </ol>
  <p>My desired result after running aggregation on <code>articles</code> collection is:</p>
  <pre><code>[
    {
      _id: &quot;article1&quot;,
      view_history: [
        { user: &quot;john&quot;, viewed_at: ISODate(&quot;...&quot;) },
        { user: &quot;bob&quot;, viewed_at: ISODate(&quot;...&quot;) },
        { user: &quot;john&quot;, viewed_at: ISODate(&quot;...&quot;) },
      ]
    }
  ]
  </code></pre>
  <p>So <code>user</code> fields on each history item in <code>view_history</code> are substituted with the user's <code>username</code>.</p>
  <p>I tried many answers on SO, but can't find any solution for my situation.
  Here's what I got so far:</p>
  <pre><code>db.articles.aggregate([
    {
      $lookup: {
        from: &quot;users&quot;,
        localField: &quot;view_history.user&quot;,
        foreignField: &quot;_id&quot;,
        as: &quot;output&quot;,
      }
    }
  ])
  </code></pre>
  <p>Which yields:</p>
  <pre><code>[
    {
      _id: &quot;article1&quot;,
      view_history: [
        { user: &quot;user1&quot;, viewed_at: ISODate(&quot;...&quot;) },
        { user: &quot;user2&quot;, viewed_at: ISODate(&quot;...&quot;) },
        { user: &quot;user1&quot;, viewed_at: ISODate(&quot;...&quot;) },
      ],
      output: [
        { _id: &quot;user1&quot;, username: &quot;john&quot; },
        { _id: &quot;user2&quot;, username: &quot;bob&quot; },
      ]
    }
  ]
  </code></pre>
  <p>(There's only one <code>user1</code> in <code>output</code>, and <code>viewed_at</code> not included)</p>