title: Mongodb: How to merge $facet output 2 by 2?
body: <p>Playground:<a href="https://mongoplayground.net/p/YUV_fReyGsr" rel="nofollow noreferrer">https://mongoplayground.net/p/YUV_fReyGsr</a>
  I have following query. I need to combine the result 2 by 2. Meaning I need to combine facet &quot;1&quot;,&quot;2&quot; as a result and facet &quot;3&quot;,&quot;4&quot; as another result. It's guaranteed that the number of facet will be even. Also, each pair of facet should get at most one record(it might not matter)</p>
  <pre><code>db.collection.aggregate([
    {
      &quot;$facet&quot;: {
        &quot;1&quot;: [
          {
            $match: {
              &quot;ID&quot;: &quot;2&quot;
            }
          }
        ],
        &quot;2&quot;: [
          {
            $match: {
              &quot;array.ID&quot;: &quot;2&quot;
            }
          }
        ],
        &quot;3&quot;: [
          {
            $match: {
              &quot;array.ID&quot;: &quot;4&quot;
            }
          }
        ],
        &quot;4&quot;: [
          {
            $match: {
              &quot;ID&quot;: &quot;4&quot;
            }
          }
        ]
      }
    }
  ])
  </code></pre>
  <p>The expected result will be</p>
  <pre><code>[
    {
      &quot;1&quot;: [
        {
          &quot;ID&quot;: &quot;1&quot;,
          &quot;array&quot;: [
            {
              &quot;ID&quot;: &quot;2&quot;,
              &quot;attribute1&quot;: &quot;456&quot;
            },
            {
              &quot;ID&quot;: &quot;3&quot;,
              &quot;attribute1&quot;: &quot;567&quot;
            }
          ],
          &quot;attr1&quot;: &quot;123&quot;
        }
      ],
      &quot;2&quot;: [
        {
          &quot;ID&quot;: &quot;4&quot;,
          &quot;array&quot;: [
            {
              &quot;ID&quot;: &quot;5&quot;,
              &quot;attr1&quot;: &quot;456&quot;
            }
          ],
          &quot;attr1&quot;: &quot;123&quot;
        }
      ]
    }
  ]
  </code></pre>