Reputation: 696
I have below two document on the collection. I need the output grouped by manager level with the list of items assigned under his team.
Input
{
"emp" : "emp1",
"itemList" : [
"item1",
"item2",
"item3",
"item4"
],
"reportingTo" : "manager1"
}
{
"emp" : "emp2",
"itemList" : [
"item5",
"item2",
"item3",
"item4"
],
"reportingTo" : "manager1"
}
output:
{
"reportingTo":"manager1",
"itemList" : [
"item1",
"item2",
"item3",
"item4",
"item5"
]
}
Upvotes: 1
Views: 71
Reputation: 46451
You can use below aggregation
db.collection.aggregate([
{ "$group": {
"_id": "$reportingTo",
"itemList": {
"$addToSet": "$itemList"
}
}},
{ "$project": {
"reportingTo": "$_id",
"itemList": {
"$reduce": {
"input": "$itemList",
"initialValue": [],
"in": { "$setUnion": ["$$this", "$$value"] }
}
}
}}
])
Upvotes: 1