title: MongoDB: how to $lookup a field in an array?
body: <p>I am trying to retrieve some lookup data for an embedded array in a document. Here is a sample of the data:</p>
  
  <pre><code>[
     {
        "_id": "58a4fa0e24180825b05e14e9",
        "user_id": "589cf6511b94281f34617a13",
        "user": {
           "firstname": "John",
           "lastname": "Doe"
        },
        "stages": [
           {
              "user_id": "589cf6511b94281f34617a13"
           },
           {
              "user_id": "589cf6511b94281f346343c3"
           }
        ],
     }
  ]
  </code></pre>
  
  <p>As you see, <code>stages</code> is an array, containing <code>user_id</code> fields only. These are pointing to the <code>_id</code> field in another collection called <code>users</code>.</p>
  
  <p>Here is how I got the above result:</p>
  
  <pre><code>db.collection('things').aggregate([{
          $match: finder
      },
      {
          $lookup: {
              from: 'users',
              localField: 'user_id',
              foreignField: '_id',
              as: 'user'
          }
      },
      {
          $unwind: '$user'
      }
  ]);
  </code></pre>
  
  <p>Now, this is pretty straightforward: a selection of records, with the <code>user</code> field looked up with <code>$lookup</code>. But how can I do the same with the elements of <code>stages</code>? The desired result would be this:</p>
  
  <pre><code>[
     {
        "_id": "58a4fa0e24180825b05e14e9",
        "user_id": "589cf6511b94281f34617a13",
        "user": {
           "firstname": "John",
           "lastname": "Doe"
        },
  
        "stages": [
           {
              "user_id": "589cf6511b94281f34617a13",
              "firstname": "John",
              "lastname": "Doe"
           },
           {
              "user_id": "589cf6511b94281f346343c3"
              "firstname": "Jane",
              "lastname": "Doe"
           }
        ],
     }
  ]
  </code></pre>