展开,但在每个结果行中保留原始数组

Unwind, but keep original array in each result row

{ 
    name: 'John Smith',
    appointments: [
        {date: 'date1', type: 'type one'},
        {date: 'date2', type: 'type two'}
    ]
},
{ 
    name: 'Michael Jackson',
    appointments: [
        {date: 'date3', type: 'type three'},
    ]
}

因此我需要以下内容:

{ 
    name: 'John Smith',
    appointment: {date: 'date1', type: 'type one'},
    appointments: [
        {date: 'date1', type: 'type one'},
        {date: 'date2', type: 'type two'}
    ]
},
{ 
    name: 'John Smith',
    appointment: {date: 'date2', type: 'type two'},
    appointments: [
        {date: 'date1', type: 'type one'},
        {date: 'date2', type: 'type two'}
    ]
},
{ 
    name: 'Michael Jackson',
    appointment: {date: 'date3', type: 'type three'},
    appointments: [
        {date: 'date3', type: 'type three'},
    ]
}

是否有任何形式的聚合展开可以将 appointments 展开为 appointment,但仍会在每个结果记录中保留原始约会数组?

感谢任何帮助。

  • $addFieldsappointment
  • 中克隆 appointments
  • $unwind解构appointment数组
db.collection.aggregate([
  { $addFields: { appointment: "$appointments" } },
  { $unwind: "$appointment" }
])

Playground