2
{ 
    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.

turivishal
  • 34,368
  • 7
  • 36
  • 59
E F
  • 474
  • 3
  • 15

1 Answers1

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

Playground

turivishal
  • 34,368
  • 7
  • 36
  • 59