1

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]
}***

2 Answers 2

1

You can use below aggregation

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

MongoPlayground

Sign up to request clarification or add additional context in comments.

Comments

0
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'
                }

            }
        },

    ]



);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.