Combine two documents

Hello,
I`m working on some aggregation pipeline.
My previous step end with two following documents:
{ x: 1, y: 60, z: 111}
and
{ x: 1, y: 90, z: 222}

i`m using x as id and wanna combine two document to be like that:
{ x: 1, y1: { z: 111 }, y2: { z: 222} }

any help would be appreciated

I`ve been trying to group them by X value; but at the end still have array; and after unwind step I back to two documents.

Hello, @Daniel_Sorkin ! It’s been a while since your last post :slight_smile:

You can try this solution:

db.aggregate([
  {
    // here are your samples documents
    $documents: [
      { x: 1, y: 60, z: 111},
      { x: 1, y: 90, z: 222}
    ],
  },
  {
    $group: {
      _id: '$x',
      y1: {
        $first: '$z'
      },
      y2: {
        $last: '$z'
      }
    }
  },
  // check the output of the $group stage
  // maybe you won't need $addFields stage
  {
    $addFields: {
      y1: {
        z: '$y1'
      },
      y2: {
        z: '$y2'
      }
    }
  }
]);

thank you for your help