0

I'm new to this topic of aggregations. I have in my database a structure like this:

  {
    "world": "Comic",
    "characters": [
      {
        "character": "megaman",
        "type":"hero",
        "code":"123"
      },
      {
        "character": "dr willow",
        "type":"villain",
        "code":"1234"
      },
      {
        "character": "spiderman",
        "type":"hero",
        "code":"12345"
      },
      {
        "character": "venom",
        "type":"villain",
        "code":"123456"
      }
      
    ]
  }

I would like to output that if the character is of type = heroe it is added to the array of array_heroe and if it is a villain it is added to the array of array_villain.

how can I do it?

I would expect this output for this case:

{
  "array_hero": [
    {
      "character": "megaman",
      "type": "hero",
      "code": "123"
    },
    {
      "character": "spiderman",
      "type": "hero",
      "code": "12345"
    }
  ],
  "array_villain": [
    {
      "character": "dr willow",
      "type": "villain",
      "code": "1234"
    },
    {
      "character": "venom",
      "type": "villain",
      "code": "123456"
    }
  ]
}
yavg
  • 2,761
  • 7
  • 45
  • 115
  • Aggregation pipeline update ($merge) + $cond + $concatArrays. – D. SM Jul 16 '20 at 01:20
  • @D.SM can you help me this time please? I am sure that if I see this working, I will know a little more about this, and that is the idea to learn, I have tried some things but it is not worth putting that I have done, in fact it is very different from what you advise me. – yavg Jul 16 '20 at 02:12

1 Answers1

2

There are many ways to accomplish that. One is $filter:

db.collection.aggregate([
    {$addFields:{
          array_hero:{
             $filter:{
                  input: "$characters",
                  cond: {$eq:["$$this.type","hero"]}
             }
          },
          array_villain: 
              ... filter as above ...
     }}
])
Joe
  • 25,000
  • 3
  • 22
  • 44
  • I have a question regarding this question. Can you help me please? https://stackoverflow.com/questions/62938971/i-use-filter-to-filter-my-data-but-i-just-want-to-output-an-array-with-whateve – yavg Jul 16 '20 at 16:20