I have this collection :
{
"_id": ObjectId("6045eec8f113547ddd3472d9"),
"execution": {
"_id": ObjectId("6045eec8f113547ddd3472d8"),
"steps": [
{
"_id": ObjectId("6045eec8f113547ddd3472d7"),
"actions": [
{
"_id": ObjectId("6045eec8f113547ddd3472d6"),
"title": "action title"
}
]
}
]
}
}
and i want to achieve this result:
{
"_id": ObjectId("6045eec8f113547ddd3472d9"),
"allActions": [
{
"_id": ObjectId("6045eec8f113547ddd3472d6"),
"title": "action title"
}
]
}
to clarify more, i want to add an array that groups together all "actions" under the "steps" array
db.getCollection("missions").aggregate([
{
$match: {
_id: ObjectId("6045eec8f113547ddd3472d9")
}
},
{
$addFields: {
"allActions": "$execution.steps"
}
}
])
Could someone help me complete the part of the code that will allow me to achieve the desired output?
CodePudding user response:
You may just use $reduce
and $concatArrays
to group all the entries in the actions
array
db.missions.aggregate([
{
$match: {
_id: ObjectId("6045eec8f113547ddd3472d9")
}
},
{
$addFields: {
"allActions": {
"$reduce": {
"input": "$execution.steps.actions",
"initialValue": [],
"in": {
"$concatArrays": [
"$$value",
"$$this"
]
}
}
}
}
}
])
Here is the Mongo playground for your reference.