title: How do I produce the union of embedded arrays in mongodb aggregate
body: <p>I have a set of documents of the form:</p>
  <pre><code>{
      skill_id: 2,
      skill_recs: [
          {
              _id: 4,
              member_ids: [1, 4, 5]
          }
      ]
  },
  {
      skill_id: 5,
      skill_recs: [
          {
              _id: 4,
              member_ids: [1, 7, 9]
          }
      ]
  }
  </code></pre>
  <p>Now I want to aggregate a set of these documents such that skill_recs are combined by _id and the member_ids of all combined docs are merged into a single union of values...</p>
  <pre><code>{ _id: 4,
    member_ids: [1, 4, 5, 7, 9]
  }
  </code></pre>
  <p>I get most of the way with:</p>
  <pre><code>db.aggregate([
      {
          $unwind: '$skill_recs'
      },
      {
          $group: {
              _id: '$skill_recs._id',
              all_member_ids: {$push: '$skill_recs.member_ids'}
          }
      },
      {
          $addFields: {
              member_ids: {$setUnion: '$all_member_ids'}
          }
      }
  ])
  </code></pre>
  <p>but the <code>$setUnion</code> doesn't do a union of the array of arrays that it is passed.</p>
  <p>Instead it produces:</p>
  <pre><code>{ _id: 4,
    member_ids: [[1, 4, 5], [1, 7, 9]]
  }
  </code></pre>
  <p>Any way to produce the union of these arrays?</p>