Reputation: 535
Consider, we have a document like below;
{
"name" : "ABC",
"destination" : {
"id" : "123",
"place": "xyz"
},
"elements": [
{
"_id": "123",
"name": "abc",
"minorElements": [
[{}, {}, {}, .....{}],
[{}, {}, {}, .....{}],
...
],
"majorElements": [
[{}, {}, {}, .....{}],
[{}, {}, {}, .....{}],
...
]
}
]
}
How to write mongo db aggregation to concatenate all array fields and create a resultant document like;
"name" : "ABC",
"destination" : {
"id" : "123",
"place": "xyz"
},
{
"elements": [{}, {}, {}, ..... {} ]
// elements contains all minorElements + majorElements + ...
}
Upvotes: 0
Views: 56
Reputation: 13113
Does this meet your requirements?
db.collection.aggregate([
{
$addFields: {
elements: {
$reduce: {
input: "$elements",
initialValue: [],
in: {
$let: {
vars: {
elem: "$$this"
},
in: {
$reduce: {
input: {
$objectToArray: "$$elem"
},
initialValue: [],
in: {
$concatArrays: [
"$$value",
{
$cond: [
{
$isArray: "$$this.v"
},
"$$this.v",
[]
]
}
]
}
}
}
}
}
}
}
}
}
])
Upvotes: 1