I have documents like this:
{
"many" : {},
"other" : {},
"fields" : {},
"phases" : [
{
"type" : 10,
"states" : [
{
"type" : 10,
"time" : ISODate("2018-04-25T13:06:42.990+02:00")
},
{
"type" : 20,
"time" : ISODate("2018-04-25T13:26:12.122+02:00")
},
{
"type" : 30,
"time" : ISODate("2018-04-25T13:26:30.124+02:00")
}
]
},
{
"type" : 20,
"states" : [
{
"type" : 10,
"time" : ISODate("2018-04-25T13:27:58.201+02:00")
}
]
}
]
}
Within an aggregation, I'm trying to flatten the states including the parent's type like this (desired output):
"states" : [
{
"phase": 10,
"type" : 10,
"time" : ISODate("2018-04-25T13:06:42.990+02:00")
},
{
"phase": 10,
"type" : 20,
"time" : ISODate("2018-04-25T13:26:12.122+02:00")
},
{
"phase": 10,
"type" : 30,
"time" : ISODate("2018-04-25T13:26:30.124+02:00")
},
{
"phase": 20,
"type" : 10,
"time" : ISODate("2018-04-25T13:27:58.201+02:00")
}
]
I already accomplished the additional states field without the phase field with this aggregation:
db.docs.aggregate([
{
$addFields: {
states: {
$reduce: {
input: "$phases",
initialValue: [],
in: { $concatArrays: ["$$value", "$$this.states"] }
}
}
}
}
])
The 'many other fields' should be preserved, so I believe grouping is not an option.
MongoDB version is 3.4.
I tried many things without result. I wonder if and how this is possible.