title: MongoDB Aggregation with sum of identical array elements how to?
body: <p>I am building statistics on most used combination of cards, this I can do easily by unwinding $players and grouping with _id of $players.spells.d -- it works quite fast and gives me exactly what I want. </p>
  
  <p>The issue I have is I cannot figure out how to take into consideration the level of the card. (Cards can be upgraded) -- when level is missing, it means it is level 1. So what I would like to get in the end is the deck id (a combination of all the cards, they are already sorted so no need to do any magic tricks, already generated with $players.spells.d grouping below), with the average level of each individual card for that combination.</p>
  
  <p>This is my query:</p>
  
  <pre><code>db.matches.aggregate([
      {$unwind: "$players"},
      {$group: {
              '_id': '$players.spells.card',
              'count': {'$sum' : 1}
          }
      },
      {$sort: {'count' : -1}}
  ]);
  </code></pre>
  
  <p>Here's what a match document look like, each match has 2 players:</p>
  
  <pre><code>{
      "_id" : 123,
      "players" : [
          {
              "id" : 41,
              "spells" : [
                  {
                      "card" : 11,
                      "level" : 2
                  },
                  {
                      "card" : 12
                  },
                  {
                      "card" : 13,
                      "level" : 2
                  },
                  {
                      "card" : 14
                  },
                  {
                      "card" : 15,
                      "level" : 2
                  },
                  {
                      "card" : 16,
                      "level" : 2
                  },
                  {
                      "card" : 17,
                      "level" : 2
                  },
                  {
                      "card" : 18
                  }
              ]
          },
          {
              "id" : 31,
              "spells" : [
                  {
                      "card" : 7
                  },
                  {
                      "card" : 88
                  },
                  {
                      "card" : 9
                  },
                  {
                      "card" : 10
                  },
                  {
                      "card" : 11
                  },
                  {
                      "card" : 12
                  },
                  {
                      "card" : 13
                  },
                  {
                      "card" : 14
                  }
              ]
          }
      ]
  }
  </code></pre>
  
  <p>Thanks in advance for any help!</p>