Question: I would like to combine arrays within arrays in MongodB

for example,
test collection has documents in following formats

```
**{
cmp_id :1
depts : [{"dept_id":1, emps:[1,2,3]}, {"dept_id":2, emps:[4,5,6]}, {"dept_id":2, emps:[7,8,9]} ]
}**

```

I need following output, How can I?

```
***{
cmp_id :1,
empids : [1,2,3,4,5,6,7,8,9]
}***

```

Answer: 
You can use below aggregation

```
db.collection.aggregate([
  {
    $project: {
      depts: {
        $reduce: {
          input: "$depts",
          initialValue: [],
          in: {
            $concatArrays: [
              "$$value",
              "$$this.emps"
            ]
          }
        }
      }
    }
  }
])

```

[**MongoPlayground**](https://mongoplayground.net/p/fHV78g4BjT_)
```
db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$depts"
            }
        },

        // Stage 2
        {
            $unwind: {
                path: "$depts.emps"
            }
        },

        // Stage 3
        {
            $group: {
                _id: '$cmp_id',
                empids: {
                    $push: '$depts.emps'
                }

            }
        },

    ]

);

```