E F
E F

Reputation: 492

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.

Upvotes: 2

Views: 566

Answers (1)

turivishal
turivishal

Reputation: 36104

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

Playground

Upvotes: 2

Related Questions