1

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

1 Answer 1

1

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"] }
      }
    }
  }}
])
Sign up to request clarification or add additional context in comments.

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.