Search code examples
mongodbaggregation-frameworknosql-aggregation

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'},
    ]
}

As a result i need the following:

{ 
    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'},
    ]
}

Is there any form of aggregation unwind that will unwind appointments into appointment, but will still keep the original appointments array in each result record?

Appreciate any help.


Solution

    • $addFields to clone appointments in appointment
    • $unwind deconstruct appointment array
    db.collection.aggregate([
      { $addFields: { appointment: "$appointments" } },
      { $unwind: "$appointment" }
    ])
    

    Playground